This commit is contained in:
Orionis312050 committed 2026-04-17 12:08:37 +02:00
1 parent 4beb27e618
commit 76de333507
30 files changed
+5047 -2113

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "slate",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
+3058 -11
View File
File diff suppressed because it is too large. Load diff
+18 -1
View File
@@ -10,23 +10,40 @@
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tabs": "^1.1.13",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"jwt-decode": "^4.0.0",
"lucide-react": "^1.8.0",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"react-markdown": "^10.1.0",
"react-router-dom": "^7.14.1",
"socket.io-client": "^4.8.3"
"rehype-raw": "^7.0.0",
"remark-gfm": "^4.0.1",
"socket.io-client": "^4.8.3",
"tailwind-merge": "^3.5.0",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@tailwindcss/vite": "^4.2.2",
"@types/node": "^24.12.2",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"autoprefixer": "^10.5.0",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"postcss": "^8.5.10",
"tailwindcss": "^4.2.2",
"typescript": "~6.0.2",
"typescript-eslint": "^8.58.0",
"vite": "^8.0.4"
+71 -54
View File
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { BrowserRouter as Router, Routes, Route, Navigate, Link } from 'react-router-dom';
import HomeView from './views/HomeView';
import ServiceView from './views/ServiceView';
import LoginView from './views/LoginView';
@@ -9,90 +9,107 @@ import AIChatSidebar from './components/AIChatSidebar';
import { AuthProvider, useAuth } from './context/AuthContext';
import ProtectedRoute from './components/ProtectedRoute';
import { LogOut, Settings, Bot, Moon, Sun } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
function AppContent() {
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
const [isChatOpen, setIsChatOpen] = useState(false);
const { user, logout } = useAuth();
// Gestion du thème
const [theme, setTheme] = useState<'dark' | 'light'>(
(localStorage.getItem('theme') as 'dark' | 'light') || 'dark'
);
useEffect(() => {
document.body.className = theme === 'light' ? 'light-theme' : '';
const root = window.document.documentElement;
if (theme === 'dark') {
root.classList.add('dark');
root.classList.remove('light-theme');
} else {
root.classList.remove('dark');
root.classList.add('light-theme');
}
localStorage.setItem('theme', theme);
}, [theme]);
// Écouteur pour ouvrir l'IA automatiquement lors d'une analyse de log
// Écouteur pour ouvrir l'IA automatiquement
useEffect(() => {
const handleOpenAI = () => setIsChatOpen(true);
window.addEventListener('analyze-log', handleOpenAI);
return () => window.removeEventListener('analyze-log', handleOpenAI);
}, []);
// Détection du service ID dans l'URL pour le contexte IA (omis car inutilisé)
return (
<div className={`app-container ${theme}`}>
<header>
<h1 onClick={() => window.location.href = '/'} style={{ cursor: 'pointer' }}>
Log<span className="ai-gradient-text">AI</span>
</h1>
<div style={{ display: 'flex', gap: '0.75rem' }}>
{user && (
<>
<button
className="btn btn-ai"
onClick={() => setIsChatOpen(!isChatOpen)}
title="Assistant IA"
>
<Bot size={18} />
<span>Assistant</span>
</button>
<button
className="btn btn-outline"
onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
title={theme === 'dark' ? 'Passer au thème clair' : 'Passer au thème sombre'}
>
{theme === 'dark' ? <Sun size={18} /> : <Moon size={18} />}
</button>
<button
className="btn btn-outline"
onClick={() => setIsSettingsOpen(true)}
title="Paramètres Globaux"
>
<Settings size={18} />
<span>Paramètres</span>
</button>
<button
className="btn btn-danger-outline"
onClick={logout}
title="Déconnexion"
>
<LogOut size={18} />
<span>Quitter</span>
</button>
</>
)}
<div className="min-h-screen bg-background text-foreground flex flex-col font-sans transition-colors duration-300">
<header className="sticky top-0 z-40 w-full border-b bg-background/80 backdrop-blur-md">
<div className="max-w-7xl mx-auto px-4 h-16 flex items-center justify-between">
<Link to="/" className="text-2xl font-bold tracking-tighter hover:opacity-80 transition-opacity">
Log<span className="ai-gradient-text">AI</span>
</Link>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="icon"
className="rounded-full shadow-sm"
onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
title={theme === 'dark' ? 'Mode clair' : 'Mode sombre'}
>
{theme === 'dark' ? <Sun size={18} /> : <Moon size={18} />}
</Button>
{user && (
<div className="flex items-center gap-2 border-l pl-2 ml-1">
<Button
size="sm"
className={cn(
"gap-2 transition-all ai-gradient-btn",
isChatOpen ? "ring-2 ring-secondary/20 shadow-md" : "hover:shadow-sm"
)}
onClick={() => setIsChatOpen(!isChatOpen)}
>
<Bot size={18} className="text-secondary-foreground" />
<span className="hidden sm:inline">Assistant</span>
</Button>
<Button
variant="ghost"
size="icon"
className="rounded-full hover:bg-muted"
onClick={() => setIsSettingsOpen(true)}
title="Paramètres"
>
<Settings size={18} />
</Button>
<Button
variant="ghost"
size="icon"
className="rounded-full hover:bg-destructive/10 hover:text-destructive text-muted-foreground mr-1"
onClick={logout}
title="Déconnexion"
>
<LogOut size={18} />
</Button>
</div>
)}
</div>
</div>
</header>
<main className={`main-content ${isChatOpen ? 'sidebar-open' : ''}`}>
<main className={cn(
"flex-1 transition-all duration-300",
isChatOpen ? "mr-[var(--sidebar-width)]" : ""
)}>
<Routes>
{/* Public Routes */}
<Route path="/login" element={<LoginView />} />
<Route path="/signup" element={<SignupView />} />
{/* Protected Routes */}
<Route element={<ProtectedRoute />}>
<Route path="/" element={<HomeView />} />
<Route path="/service/:id" element={<ServiceView />} />
</Route>
{/* Fallback */}
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</main>
@@ -101,7 +118,7 @@ function AppContent() {
<AIChatSidebar
isOpen={isChatOpen}
onClose={() => setIsChatOpen(false)}
currentService={null /* Remplacé dynamiquement par ID si besoin */}
currentService={null}
/>
</div>
);
+187 -80
View File
@@ -1,6 +1,13 @@
import React, { useState, useEffect, useRef } from 'react';
import { Bot, User, History, MessageSquare, ChevronLeft, Trash2, Loader2, Send, Plus, X, Cpu, Square } from 'lucide-react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import type { LogService, Conversation, Message } from '../types';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import { Separator } from '@/components/ui/separator';
interface AIChatSidebarProps {
isOpen: boolean;
@@ -18,13 +25,49 @@ export default function AIChatSidebar({ isOpen, onClose, currentService }: AICha
const messagesEndRef = useRef<HTMLDivElement>(null);
const abortControllerRef = useRef<AbortController | null>(null);
const [view, setView] = useState<'chat' | 'history'>('chat');
const [sidebarWidth, setSidebarWidth] = useState(() => {
const saved = localStorage.getItem('aiSidebarWidth');
return saved ? parseInt(saved, 10) : 480;
});
const [isResizing, setIsResizing] = useState(false);
// Resize Handlers
const handleMouseDown = (e: React.MouseEvent) => {
e.preventDefault();
setIsResizing(true);
};
useEffect(() => {
const handleMouseMove = (e: MouseEvent) => {
if (!isResizing) return;
const newWidth = window.innerWidth - e.clientX;
if (newWidth > 350 && newWidth < window.innerWidth * 0.8) {
setSidebarWidth(newWidth);
}
};
const handleMouseUp = () => {
setIsResizing(false);
localStorage.setItem('aiSidebarWidth', sidebarWidth.toString());
};
if (isResizing) {
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('mouseup', handleMouseUp);
document.body.style.cursor = 'col-resize';
}
return () => {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
document.body.style.cursor = 'default';
};
}, [isResizing, sidebarWidth]);
// Charger les conversations au montage
useEffect(() => {
if (isOpen) fetchConversations();
}, [isOpen]);
// Charger les messages quand la conversation change
useEffect(() => {
if (currentConv) {
fetchMessages(currentConv.id);
@@ -34,7 +77,6 @@ export default function AIChatSidebar({ isOpen, onClose, currentService }: AICha
}
}, [currentConv]);
// Auto-scroll
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages, isTyping]);
@@ -44,7 +86,6 @@ export default function AIChatSidebar({ isOpen, onClose, currentService }: AICha
const res = await fetch(`${import.meta.env.VITE_API_URL || 'http://localhost:3001'}/api/ai/conversations`, { credentials: 'include' });
const data = await res.json();
setConversations(data);
// Si aucune conv n'est sélectionnée, prendre la plus récente
if (!currentConv && data.length > 0) {
setCurrentConv(data[0]);
}
@@ -109,18 +150,16 @@ export default function AIChatSidebar({ isOpen, onClose, currentService }: AICha
const sendMessage = async (text: string) => {
if (!text.trim()) return;
// Si pas de conversation active, on en crée une
let targetConv = currentConv;
if (!targetConv) {
targetConv = await startNewChat();
if (!targetConv) return; // Sécurité en cas d'échec de création
if (!targetConv) return;
}
const userMsg: Message = { role: 'user', content: text };
setMessages(prev => [...prev, userMsg]);
setInput('');
setIsTyping(true); // Loader pendant le tout premier temps de latence réseau
setIsTyping(true);
setIsGenerating(true);
const abortController = new AbortController();
@@ -158,15 +197,12 @@ export default function AIChatSidebar({ isOpen, onClose, currentService }: AICha
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.substring(6));
if (data.type === 'chunk') {
if (isFirstChunk) {
// Dès le premier mot, on enlève le loader "Qwen réfléchit" car l'IA a commencé à taper
setIsTyping(false);
setMessages(prev => [...prev, { role: 'assistant', content: data.content || "" }]);
isFirstChunk = false;
} else {
// On met à jour le dernier message avec la dernière fraction de texte reçue
setMessages(prev => {
const newMessages = [...prev];
const lastIndex = newMessages.length - 1;
@@ -180,19 +216,15 @@ export default function AIChatSidebar({ isOpen, onClose, currentService }: AICha
});
}
} else if (data.type === 'done') {
// Si la conversation était "Nouvelle", c'est le moment de relire le titre qui a été généré
if (targetConv.title === "Nouvelle discussion") {
fetchConversations();
// et on met à jour la reférence locale pour ne pas avoir de glitch visuel
setCurrentConv((prev: Conversation | null) => prev ? {...prev, title: text.substring(0, 30)} : prev);
}
} else if (data.error) {
setIsTyping(false);
setMessages(prev => [...prev, { role: 'assistant', content: `Erreur : ${data.error}` }]);
}
} catch (e) {
// Parse error possible si un flux JSON est morcelé, on ignore et ça se complètera au prochain chunk
}
} catch (e) {}
}
}
}
@@ -200,22 +232,19 @@ export default function AIChatSidebar({ isOpen, onClose, currentService }: AICha
} catch (error: any) {
setIsTyping(false);
setIsGenerating(false);
if (error.name === 'AbortError') {
// L'utilisateur a annulé, on ne rajoute pas de message d'erreur
} else {
if (error.name !== 'AbortError') {
setMessages(prev => [...prev, { role: 'assistant', content: "Erreur réseau / Déconnexion stream." }]);
}
}
};
// Écouge des événements d'analyse externes
useEffect(() => {
const handleAnalyzeLog = (e: any) => {
const { line, serviceName } = e.detail;
const contextMsg = `Analyse ce log du service '${serviceName}' : "${line}"`;
if (!isOpen) {
// L'App gèrera l'ouverture, mais on peut préparer le message
}
const isDiagnostic = line.trim().startsWith('###');
const contextMsg = isDiagnostic
? line.trim()
: `Analyse ce log du service '${serviceName}' : "${line}"`;
sendMessage(contextMsg);
};
@@ -224,45 +253,87 @@ export default function AIChatSidebar({ isOpen, onClose, currentService }: AICha
}, [isOpen, currentConv]);
return (
<div className={`ai-sidebar ${isOpen ? 'open' : ''}`}>
<div className="ai-sidebar-header">
{view === 'history' ? (
<div className="ai-header-title">
<button className="btn-icon" onClick={() => setView('chat')}><ChevronLeft size={20} /></button>
<span>Historique</span>
</div>
) : (
<div className="ai-header-title" onClick={() => setView('history')} style={{ cursor: 'pointer' }}>
<History size={18} />
<span style={{ fontSize: '0.9rem' }}>{currentConv?.title || "Assistant"}</span>
</div>
)}
<div style={{ display: 'flex', gap: '0.5rem' }}>
<button className="btn-icon" onClick={startNewChat} title="Nouvelle discussion"><Plus size={18} /></button>
<button className="btn-icon" onClick={onClose}><X size={20} /></button>
<div
className={cn(
"fixed top-0 right-0 h-full bg-card border-l border-muted/50 shadow-2xl transition-all duration-500 z-50 flex flex-col",
isOpen ? "translate-x-0" : "translate-x-full"
)}
style={{ width: sidebarWidth }}
>
{/* Resize Handle */}
<div
className="absolute left-0 top-0 w-1.5 h-full cursor-col-resize hover:bg-primary/20 transition-colors z-50"
onMouseDown={handleMouseDown}
/>
{/* Header */}
<div className="flex items-center justify-between p-6 bg-muted/5">
<div className="flex items-center gap-4">
{view === 'history' ? (
<Button variant="ghost" size="icon" className="rounded-xl h-10 w-10" onClick={() => setView('chat')}>
<ChevronLeft size={22} />
</Button>
) : (
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
<Bot size={22} />
</div>
<div className="flex flex-col">
<span className="text-sm font-bold tracking-tight">AI Assistant</span>
<span className="text-[10px] text-muted-foreground uppercase font-bold tracking-widest opacity-60">Session Active</span>
</div>
</div>
)}
</div>
<div className="flex items-center gap-2">
{view === 'chat' && (
<Button variant="ghost" size="icon" className="rounded-xl h-10 w-10 text-muted-foreground hover:text-foreground" onClick={() => setView('history')} title="Historique">
<History size={20} />
</Button>
)}
<Button variant="ghost" size="icon" className="rounded-xl h-10 w-10 text-muted-foreground hover:text-foreground" onClick={startNewChat} title="Nouveau message">
<Plus size={22} />
</Button>
<Button variant="ghost" size="icon" className="rounded-xl h-10 w-10 text-muted-foreground hover:text-destructive" onClick={onClose}>
<X size={22} />
</Button>
</div>
</div>
<Separator className="opacity-50" />
<div className="ai-messages">
{/* Content */}
<div className="flex-1 overflow-y-auto p-6 space-y-8 scrollbar-thin">
{view === 'history' ? (
<div className="ai-conv-list">
<div className="space-y-4">
<h4 className="text-[10px] font-bold uppercase tracking-[0.2em] text-muted-foreground mb-4">Conversations récentes</h4>
{conversations.length === 0 ? (
<p className="no-data">Aucune conversation passée.</p>
<div className="text-center py-24 text-muted-foreground italic opacity-50">Aucun historique disponible</div>
) : (
conversations.map(conv => (
<div
key={conv.id}
className={`ai-conv-item ${currentConv?.id === conv.id ? 'active' : ''}`}
className={cn(
"group flex items-center gap-4 p-4 rounded-2xl border transition-all cursor-pointer",
currentConv?.id === conv.id ? "bg-muted/10 border-primary/20 shadow-sm" : "border-transparent hover:bg-muted/10"
)}
onClick={() => setCurrentConv(conv)}
>
<MessageSquare size={14} />
<div className="ai-conv-info">
<span className="ai-conv-title">{conv.title}</span>
<span className="ai-conv-date">{new Date(conv.updatedAt).toLocaleDateString()}</span>
<div className="w-10 h-10 rounded-xl bg-muted flex items-center justify-center text-muted-foreground group-hover:bg-primary/10 group-hover:text-primary transition-colors">
<MessageSquare size={18} />
</div>
<button className="btn-delete-conv" onClick={(e) => deleteConversation(e, conv.id)}>
<Trash2 size={12} />
</button>
<div className="flex-1 min-w-0">
<div className="font-bold text-sm truncate">{conv.title}</div>
<div className="text-[10px] text-muted-foreground uppercase font-bold tracking-tighter opacity-60">{new Date(conv.updatedAt).toLocaleDateString()}</div>
</div>
<Button
variant="ghost"
size="icon"
className="opacity-0 group-hover:opacity-100 h-8 w-8 text-destructive hover:bg-destructive/10 rounded-lg"
onClick={(e) => deleteConversation(e, conv.id)}
>
<Trash2 size={14} />
</Button>
</div>
))
)}
@@ -270,29 +341,60 @@ export default function AIChatSidebar({ isOpen, onClose, currentService }: AICha
) : (
<>
{!currentConv && (
<div className="ai-welcome">
<Cpu size={48} className="ai-welcome-icon" />
<h3>Prêt pour une nouvelle session ?</h3>
<p>Cliquez sur "+" pour démarrer une discussion ou consultez votre historique.</p>
<button className="btn btn-primary" onClick={startNewChat} style={{ marginTop: '1.5rem' }}>
<Plus size={16} /> Nouvelle discussion
</button>
<div className="flex flex-col items-center justify-center h-full text-center space-y-8 py-20 animate-in fade-in duration-1000">
<div className="w-20 h-20 rounded-3xl bg-primary/5 flex items-center justify-center text-primary group">
<Cpu size={40} className="group-hover:scale-110 transition-transform" />
</div>
<div className="space-y-3">
<h3 className="font-bold text-2xl tracking-tight">Système de diagnostic IA</h3>
<p className="text-sm text-muted-foreground px-12 leading-relaxed">
Posez vos questions sur les logs ou laissez l'IA analyser automatiquement les comportements suspects.
</p>
</div>
<Button onClick={startNewChat} className="rounded-2xl h-12 px-10 font-bold ai-gradient-btn shadow-lg">
<Plus size={18} className="mr-2" /> Démarrer une analyse
</Button>
</div>
)}
{messages.filter(m => m.role !== 'system').map((msg, idx) => (
<div key={idx} className={`ai-message-wrapper ${msg.role}`}>
<div className="ai-message-avatar">
{msg.role === 'assistant' ? <Bot size={14} /> : <User size={14} />}
<div key={idx} className={cn(
"flex gap-4 animate-in slide-in-from-bottom-2 duration-300",
msg.role === 'assistant' ? "flex-row" : "flex-row-reverse"
)}>
<div className={cn(
"w-9 h-9 rounded-xl flex items-center justify-center shrink-0 border",
msg.role === 'assistant' ? "bg-muted text-muted-foreground border-muted-foreground/10" : "bg-primary text-primary-foreground border-primary/20"
)}>
{msg.role === 'assistant' ? <Bot size={18} /> : <User size={18} />}
</div>
<div className={cn(
"max-w-[88%] p-4 rounded-xl text-sm leading-relaxed prose dark:prose-invert prose-sm",
msg.role === 'assistant' ? "bg-muted border border-muted-foreground/20 rounded-tl-none shadow-md" : "bg-card border border-muted-foreground/20 rounded-tr-none text-foreground font-medium shadow-md"
)}>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw]}
>
{msg.content}
</ReactMarkdown>
</div>
<div className="ai-message-content">{msg.content}</div>
</div>
))}
{isTyping && (
<div className="ai-message-wrapper assistant">
<div className="ai-message-avatar"><Loader2 size={14} className="spin" /></div>
<div className="ai-message-content typing">Qwen réfléchit...</div>
<div className="flex gap-4 animate-in fade-in duration-500">
<div className="w-9 h-9 rounded-xl bg-muted border border-muted-foreground/10 text-muted-foreground flex items-center justify-center shrink-0">
<Loader2 size={18} className="animate-spin" />
</div>
<div className="bg-muted/10 border border-muted/50 p-4 rounded-[2rem] rounded-tl-none text-sm font-medium text-muted-foreground flex items-center gap-3">
<div className="flex gap-1">
<div className="w-1 h-1 bg-primary rounded-full animate-bounce [animation-delay:-0.3s]" />
<div className="w-1 h-1 bg-primary rounded-full animate-bounce [animation-delay:-0.15s]" />
<div className="w-1 h-1 bg-primary rounded-full animate-bounce" />
</div>
Traitement en cours...
</div>
</div>
)}
<div ref={messagesEndRef} />
@@ -300,32 +402,37 @@ export default function AIChatSidebar({ isOpen, onClose, currentService }: AICha
)}
</div>
{/* Input area */}
{view === 'chat' && currentConv && (
<div className="ai-input-area">
<form onSubmit={(e) => { e.preventDefault(); sendMessage(input); }}>
<div className="ai-input-wrapper">
<input
type="text"
placeholder="Posez une question..."
<div className="p-6 border-t bg-muted/10">
<form className="space-y-4" onSubmit={(e) => { e.preventDefault(); sendMessage(input); }}>
<div className="relative group">
<Input
placeholder="Posez une question à l'IA..."
className="pr-14 h-14 bg-card border-muted/50 rounded-2xl shadow-inner focus:border-primary/50 focus:ring-primary/10 transition-all text-base"
value={input}
onChange={(e) => setInput(e.target.value)}
disabled={isGenerating}
/>
<button type="submit" disabled={!input.trim() || isGenerating}>
<Button
size="icon"
className="absolute right-2 top-2 h-10 w-10 rounded-xl"
disabled={!input.trim() || isGenerating}
>
<Send size={18} />
</button>
</Button>
</div>
{isGenerating && (
<div style={{ textAlign: 'center', marginTop: '0.75rem' }}>
<button
type="button"
className="btn btn-outline"
style={{ fontSize: '0.75rem', padding: '0.25rem 0.75rem', margin: '0 auto' }}
<div className="flex justify-center animate-in slide-in-from-top-1 duration-300">
<Button
variant="outline"
size="sm"
className="h-9 gap-2 text-[10px] font-bold uppercase tracking-widest text-destructive border-destructive/20 hover:bg-destructive/10 rounded-xl px-4"
onClick={stopGeneration}
>
<Square size={12} fill="currentColor" />
Stopper la réponse
</button>
Interrompre
</Button>
</div>
)}
</form>
+83 -43
View File
@@ -1,5 +1,22 @@
import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Loader2 } from 'lucide-react';
export default function AddServiceModal({ onClose, onAdded }: { onClose: () => void, onAdded: () => void }) {
const [formData, setFormData] = useState({
@@ -49,52 +66,75 @@ export default function AddServiceModal({ onClose, onAdded }: { onClose: () => v
}
};
return createPortal(
<div className="modal-overlay" onClick={onClose}>
<div className="glass-panel modal-content" onClick={e => e.stopPropagation()}>
return (
<Dialog open={true} onOpenChange={onClose}>
<DialogContent className="sm:max-w-[425px]">
<form onSubmit={handleSubmit}>
<h2 style={{ marginBottom: '1.5rem', color: 'var(--text-main)' }}>Nouveau Service</h2>
<DialogHeader>
<DialogTitle className="text-xl">Nouveau Service</DialogTitle>
</DialogHeader>
<div className="form-group">
<label>Nom du service (Affichage)</label>
<input required type="text" className="form-control" value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} placeholder="ex: Mon App Backend" />
<div className="grid gap-4 py-4">
<div className="grid gap-2">
<Label htmlFor="name">Nom du service (Affichage)</Label>
<Input
id="name"
required
value={formData.name}
onChange={e => setFormData({...formData, name: e.target.value})}
placeholder="ex: Mon App Backend"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="type">Environnement Source</Label>
<Select
value={formData.type}
onValueChange={(val) => setFormData({...formData, type: val})}
>
<SelectTrigger id="type">
<SelectValue placeholder="Choisir un type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="docker">Conteneur Docker</SelectItem>
<SelectItem value="os_service">Service Système Natif (Host)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor="target">Rechercher le conteneur ou service...</Label>
<div className="relative">
<Input
id="target"
required
list="targets-list"
value={formData.pathOrContainerId}
onChange={e => setFormData({...formData, pathOrContainerId: e.target.value})}
placeholder={formData.type === 'docker' ? 'Saisissez ou choisissez...' : 'Saisissez ou choisissez...'}
disabled={isLoading}
className={isLoading ? "pr-10" : ""}
/>
{isLoading && (
<div className="absolute right-3 top-1/2 -translate-y-1/2">
<Loader2 size={16} className="animate-spin text-muted-foreground" />
</div>
)}
</div>
<datalist id="targets-list">
{availableTargets.map(target => (
<option key={target.id} value={target.id}>{target.name}</option>
))}
</datalist>
</div>
</div>
<div className="form-group">
<label>Environnement Source</label>
<select className="form-control" value={formData.type} onChange={e => setFormData({...formData, type: e.target.value})}>
<option value="docker">Conteneur Docker</option>
<option value="os_service">Service Système Natif (Host)</option>
</select>
</div>
<div className="form-group">
<label>Rechercher le conteneur ou service...</label>
<input
required
type="text"
list="targets-list"
className="form-control"
value={formData.pathOrContainerId}
onChange={e => setFormData({...formData, pathOrContainerId: e.target.value})}
placeholder={formData.type === 'docker' ? 'Saisissez ou choisissez un conteneur...' : 'Saisissez ou choisissez un service système...'}
disabled={isLoading}
/>
{isLoading && <small style={{ color: 'var(--text-muted)', display: 'block', marginTop: '0.5rem' }}>Analyse des services en cours...</small>}
<datalist id="targets-list">
{availableTargets.map(target => (
<option key={target.id} value={target.id}>{target.name}</option>
))}
</datalist>
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: '1rem', marginTop: '1.5rem' }}>
<button type="button" className="btn" onClick={onClose}>Annuler</button>
<button type="submit" className="btn btn-primary">Créer le service</button>
</div>
<DialogFooter className="gap-2 sm:gap-0">
<Button type="button" variant="ghost" onClick={onClose}>Annuler</Button>
<Button type="submit">Créer le service</Button>
</DialogFooter>
</form>
</div>
</div>,
document.body
</DialogContent>
</Dialog>
);
}
+117 -85
View File
@@ -1,19 +1,21 @@
import { useEffect, useState, useRef } from 'react';
import { io, Socket } from 'socket.io-client';
import { Download, Sparkles } from 'lucide-react';
import { Download, Sparkles, Play, Pause, CircleCheck, Terminal } from 'lucide-react';
import type { LogService } from '../types';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
export default function LogTerminal({ service, initialLogs = [] }: {
service: LogService,
initialLogs?: { id: string, line: string, isError: boolean }[]
export default function LogTerminal({ service, initialLogs = [] }: {
service: LogService,
initialLogs?: { id: string, line: string, isError: boolean }[]
}) {
const [logs, setLogs] = useState<{ id: string, line: string, isError: boolean }[]>(initialLogs);
const [isPaused, setIsPaused] = useState(false);
const isPausedRef = useRef(false); // Ref pour éviter les fermetures (closures) obsolètes
const isPausedRef = useRef(false);
const pendingLogsRef = useRef<{ id: string, line: string, isError: boolean }[]>([]);
const socketRef = useRef<Socket | null>(null);
// Synchronisation de la ref avec l'état
useEffect(() => {
isPausedRef.current = isPaused;
}, [isPaused]);
@@ -25,16 +27,15 @@ export default function LogTerminal({ service, initialLogs = [] }: {
});
}
// On ne vide les logs que si le service change, et on injecte les logs initiaux
setLogs(initialLogs);
pendingLogsRef.current = [];
const handleLogLine = (data: { serviceId: number | string, line: string }) => {
if (data.serviceId === service.id) {
const isError = service.alertKeyword
? data.line.includes(service.alertKeyword)
: (data.line.includes('ERROR') || data.line.includes('Exception'));
const isError = service.alertKeyword
? data.line.includes(service.alertKeyword)
: (data.line.includes('ERROR') || data.line.includes('Exception'));
const newLog = { id: Date.now() + Math.random().toString(), line: data.line, isError };
if (!isPausedRef.current) {
@@ -49,7 +50,7 @@ export default function LogTerminal({ service, initialLogs = [] }: {
return () => {
socketRef.current?.off('logLine', handleLogLine);
};
}, [service.id]); // DÉPENDANCE UNIQUEMENT SUR L'ID DU SERVICE
}, [service.id]);
const terminalContentRef = useRef<HTMLDivElement>(null);
@@ -63,15 +64,12 @@ export default function LogTerminal({ service, initialLogs = [] }: {
useEffect(() => {
if (!isPaused && terminalContentRef.current) {
// Défilement interne du conteneur sans affecter la page entière
terminalContentRef.current.scrollTop = terminalContentRef.current.scrollHeight;
}
}, [logs, isPaused]);
const handleExport = () => {
if (logs.length === 0) return;
// Header CSV
const csvContent = [
"ID,Status,Log Line",
...logs.map(log => `${log.id},${log.isError ? 'ERROR' : 'INFO'},"${log.line.replace(/"/g, '""')}"`)
@@ -81,7 +79,7 @@ export default function LogTerminal({ service, initialLogs = [] }: {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", `logs_${service.name}_${new Date().toISOString().slice(0,10)}.csv`);
link.setAttribute("download", `logs_${service.name}_${new Date().toISOString().slice(0, 10)}.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
@@ -89,117 +87,151 @@ export default function LogTerminal({ service, initialLogs = [] }: {
};
const handleAnalyzeLog = (line: string) => {
// Émission d'un événement global pour la sidebar
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line, serviceName: service.name }
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line, serviceName: service.name }
}));
};
const handleAnalyzeChunk = (chunk: { id: string, line: string, isError: boolean }[]) => {
if (chunk.length === 0) return;
const batchText = chunk.map(l => l.line).join('\n');
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line: `Voici un ensemble de ${chunk.length} logs :\n${batchText}`, serviceName: service.name }
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line: `Voici un ensemble de ${chunk.length} logs :\n${batchText}`, serviceName: service.name }
}));
};
const handleGlobalCheckup = () => {
if (logs.length === 0) return;
// Limite de caractères par défaut (Ollama LLaMA3 = ~8K context, on reste safe avec 6000 chars)
const MAX_CHARS = 6000;
let batchText = "";
let truncated = false;
let includedCount = 0;
// On part de la fin vers le début pour privilégier les logs les plus récents
for (let i = logs.length - 1; i >= 0; i--) {
const lineWithBreak = logs[i].line + '\n';
if (batchText.length + lineWithBreak.length > MAX_CHARS) {
truncated = true;
break;
}
// Ajout au début pour conserver l'ordre chronologique (haut vers bas)
batchText = lineWithBreak + batchText;
includedCount++;
const lineWithBreak = logs[i].line + '\n';
if (batchText.length + lineWithBreak.length > MAX_CHARS) {
truncated = true;
break;
}
batchText = lineWithBreak + batchText;
includedCount++;
}
const message = truncated
? `Fais un diagnostic de ces logs récents. (Attention : l'historique a été tronqué car il était trop grand. Voici les ${includedCount} logs les plus récents) :\n\n${batchText}`
: `Fais un diagnostic complet pour ce service. Voici l'intégralité des ${includedCount} logs dans la console :\n\n${batchText}`;
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line: message, serviceName: service.name }
const message = truncated
? `### 📊 Diagnostic complet demandé\n\n*Analyse des ${includedCount} logs les plus récents...*\n\n<details>\n<summary>Voir les logs transmis à l'IA</summary>\n\n\`\`\`\n${batchText}\n\`\`\`\n</details>`
: `### 📊 Diagnostic complet demandé\n\n*Analyse de l'intégralité des logs (${includedCount})...*\n\n<details>\n<summary>Voir les logs transmis à l'IA</summary>\n\n\`\`\`\n${batchText}\n\`\`\`\n</details>`;
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line: message, serviceName: service.name }
}));
};
const chunkedLogs = [];
// Chunk starting from the end so latest logs are strictly grouped by 5
for (let i = logs.length; i > 0; i -= 5) {
const start = Math.max(0, i - 5);
chunkedLogs.unshift(logs.slice(start, i));
}
return (
<div className={`terminal-container ${isPaused ? 'paused' : 'live'}`}>
<div className="terminal-controls">
<div style={{ display: 'flex', gap: '0.75rem' }}>
<button className={`btn-terminal ${isPaused ? 'btn-resume' : 'btn-pause'}`} onClick={togglePause}>
{isPaused ? '▶ Reprendre' : '⏸ Pauser'}
{isPaused && pendingLogsRef.current.length > 0 && (
<span className="pending-badge">{pendingLogsRef.current.length}</span>
)}
</button>
<button className="btn-terminal btn-outline-sm" onClick={handleExport} title="Exporter en CSV">
<Download size={14} /> Exporter
</button>
<button
className="btn-terminal btn-outline-sm"
style={{ color: 'var(--accent-color)', borderColor: 'rgba(59, 130, 246, 0.3)' }}
onClick={handleGlobalCheckup}
title="Analyser l'intégralité de la console via l'IA"
<div className="flex flex-col h-[75vh] bg-[#1a1b1e] overflow-hidden border-t">
{/* Terminal Toolbar */}
<div className="flex items-center justify-between px-6 py-4 bg-background dark:bg-card border-b border-border/40">
<div className="flex items-center gap-3">
<Button
variant={isPaused ? "secondary" : "ghost"}
size="sm"
onClick={togglePause}
className={cn("h-10 px-4 gap-2 rounded-xl transition-all", isPaused && "bg-destructive/10 text-destructive hover:bg-destructive/20 border border-destructive/20")}
>
<Sparkles size={14} /> Diagnostic Complet
</button>
{isPaused ? <Play size={16} /> : <Pause size={16} />}
<span className="font-bold uppercase tracking-widest text-[10px]">{isPaused ? 'Reprendre' : 'Pauser'}</span>
{isPaused && pendingLogsRef.current.length > 0 && (
<Badge variant="destructive" className="ml-1 h-5 min-w-5 flex items-center justify-center p-0 text-[10px] font-bold">
{pendingLogsRef.current.length}
</Badge>
)}
</Button>
<Button variant="ghost" size="sm" onClick={handleExport} className="h-10 px-4 gap-2 rounded-xl text-muted-foreground hover:text-foreground hover:bg-white/5 border border-transparent hover:border-white/5">
<Download size={16} />
<span className="font-bold uppercase tracking-widest text-[10px]">Exporter</span>
</Button>
<Button
variant="ghost"
size="sm"
onClick={handleGlobalCheckup}
className="h-10 px-4 gap-2 rounded-xl ai-outline-v2 font-bold uppercase tracking-widest text-[10px]"
>
{/* SVG Gradient Definition */}
<svg width="0" height="0" className="absolute">
<defs>
<linearGradient id="ai-gradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stopColor="#3b82f6" />
<stop offset="46%" stopColor="#a855f7" />
<stop offset="100%" stopColor="#f97316" />
</linearGradient>
</defs>
</svg>
<div className="ai-icon-box">
<Sparkles size={16} className="ai-icon-svg" />
<span>Diagnostic IA</span>
</div>
</Button>
</div>
<div className="flex items-center gap-4">
<Badge variant="outline" className={cn(
"gap-2 border-none px-4 py-1.5 rounded-full text-[10px] font-bold tracking-[0.2em]",
isPaused ? "bg-destructive/10 text-destructive" : "bg-green-500/10 text-green-500"
)}>
<div className={cn("w-2 h-2 rounded-full", isPaused ? "bg-destructive" : "bg-green-500 animate-pulse")} />
{isPaused ? 'TERMINAL PAUSÉ' : 'FLUX EN DIRECT'}
</Badge>
</div>
<span className="live-indicator">
<span className={`status-dot ${isPaused ? 'dot-red' : 'dot-green'}`}></span>
{isPaused ? 'TERMINAL EN PAUSE' : 'LOGS EN DIRECT'}
</span>
</div>
<div className="terminal-content" ref={terminalContentRef}>
{/* Terminal View */}
<div
className="flex-1 overflow-y-auto p-6 font-mono text-[13px] antialiased scrollbar-terminal selection:bg-primary/30"
ref={terminalContentRef}
>
{chunkedLogs.length === 0 ? (
<div style={{ color: 'var(--text-muted)', display: 'flex', height: '100%', alignItems: 'center', justifyContent: 'center' }}>
En attente de nouveaux logs pour '{service.name}'...
<div className="flex flex-col items-center justify-center h-full gap-4 opacity-20 italic">
<Terminal size={64} className="stroke-[1px]" />
<p className="tracking-widest uppercase text-xs font-bold">Initialisation de la sortie standard...</p>
</div>
) : (
chunkedLogs.map((chunk, chunkIndex) => (
<div key={`chunk-${chunkIndex}`} className="log-chunk">
<div className="chunk-lines">
<div key={`chunk-${chunkIndex}`} className="group relative flex hover:bg-white/[0.03] transition-colors">
<div className="flex-1 py-1.5 pl-4">
{chunk.map(log => (
<div key={log.id} className="log-line-wrapper">
<div className="log-line">
<span className={`log-text ${log.isError ? 'log-error' : ''}`}>
{log.line}
</span>
</div>
<button
className="btn-analyze-log"
<div key={log.id} className="flex items-start gap-4 group/line py-0.5">
<span className={cn(
"flex-1 break-all whitespace-pre-wrap leading-relaxed tracking-tight",
log.isError ? "text-destructive font-bold" : "text-white/80"
)}>
{log.line}
</span>
<button
className="opacity-0 group-hover/line:opacity-100 p-1.5 text-secondary/40 hover:text-secondary transition-all"
onClick={() => handleAnalyzeLog(log.line)}
title="Analyser ce log uniquement"
title="Analyser la ligne"
>
<Sparkles size={12} />
<Sparkles size={14} />
</button>
</div>
))}
</div>
<div className="chunk-sidebar" onClick={() => handleAnalyzeChunk(chunk)} title="Analyser cette zone de logs">
<div className="chunk-sidebar-icon">
<Sparkles size={14} />
</div>
{/* Chunk Sidebar */}
<div
className="w-12 flex items-center justify-center cursor-pointer border-l border-transparent hover:border-secondary/20 hover:bg-secondary/5 text-transparent hover:text-secondary/50 transition-all"
onClick={() => handleAnalyzeChunk(chunk)}
title="Analyser ce bloc de logs"
>
<Sparkles size={18} />
</div>
</div>
))
+144 -52
View File
@@ -1,5 +1,22 @@
import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { CheckCircle2, Cpu, Globe, Link as LinkIcon } from 'lucide-react';
export default function SettingsModal({ onClose }: { onClose: () => void }) {
const [formData, setFormData] = useState({
@@ -7,7 +24,8 @@ export default function SettingsModal({ onClose }: { onClose: () => void }) {
notionDbId: '',
ollamaUrl: '',
ollamaModel: '',
searxngUrl: ''
searxngUrl: '',
aiLanguage: 'Français'
});
const [saved, setSaved] = useState(false);
@@ -23,7 +41,8 @@ export default function SettingsModal({ onClose }: { onClose: () => void }) {
notionDbId: data.notionDbId || '',
ollamaUrl: data.ollamaUrl || '',
ollamaModel: data.ollamaModel || '',
searxngUrl: data.searxngUrl || ''
searxngUrl: data.searxngUrl || '',
aiLanguage: data.aiLanguage || 'Français'
});
}
})
@@ -48,57 +67,130 @@ export default function SettingsModal({ onClose }: { onClose: () => void }) {
}
};
return createPortal(
<div className="modal-overlay" onClick={onClose}>
<div className="glass-panel modal-content" onClick={e => e.stopPropagation()}>
<form onSubmit={handleSubmit} style={{ maxHeight: '90vh', overflowY: 'auto' }}>
<h2 style={{ marginBottom: '1.5rem', color: 'var(--text-main)' }}>Paramètres Globaux</h2>
<div style={{ padding: '1.5rem', background: 'rgba(59, 130, 246, 0.05)', borderRadius: '8px', border: '1px solid rgba(59, 130, 246, 0.2)', marginBottom: '1.5rem' }}>
<h4 style={{ fontSize: '1rem', marginBottom: '1rem', color: 'var(--text-main)' }}>Intégration Notion</h4>
<div className="form-group">
<label>Token d'intégration Notion (Internal App)</label>
<input type="password" className="form-control" value={formData.notionToken} onChange={e => setFormData({...formData, notionToken: e.target.value})} placeholder="secret_..." />
</div>
<div className="form-group" style={{ marginBottom: 0 }}>
<label>ID de la base de données (Database ID)</label>
<input type="text" className="form-control" value={formData.notionDbId} onChange={e => setFormData({...formData, notionDbId: e.target.value})} placeholder="ex: a1b2c3d4e5f6..." />
</div>
</div>
<div style={{ padding: '1.5rem', background: 'rgba(16, 185, 129, 0.05)', borderRadius: '8px', border: '1px solid rgba(16, 185, 129, 0.2)', marginBottom: '1.5rem' }}>
<h4 style={{ fontSize: '1rem', marginBottom: '1rem', color: 'var(--text-main)' }}>Intégration IA (Ollama Local)</h4>
<div className="form-group">
<label>URL de l'API Ollama</label>
<input type="text" className="form-control" value={formData.ollamaUrl} onChange={e => setFormData({...formData, ollamaUrl: e.target.value})} placeholder="ex: http://localhost:11434" />
</div>
<div className="form-group" style={{ marginBottom: 0 }}>
<label>Nom du modèle (ex: qwen:7b, llama3)</label>
<input type="text" className="form-control" value={formData.ollamaModel} onChange={e => setFormData({...formData, ollamaModel: e.target.value})} placeholder="ex: qwen:7b" />
</div>
</div>
return (
<Dialog open={true} onOpenChange={onClose}>
<DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-hidden flex flex-col p-0">
<DialogHeader className="p-6 pb-2 border-b">
<DialogTitle className="text-2xl font-bold tracking-tight">Paramètres Globaux</DialogTitle>
</DialogHeader>
<div style={{ padding: '1.5rem', background: 'rgba(234, 179, 8, 0.05)', borderRadius: '8px', border: '1px solid rgba(234, 179, 8, 0.2)', marginBottom: '1.5rem' }}>
<h4 style={{ fontSize: '1rem', marginBottom: '1rem', color: 'var(--text-main)' }}>Recherche Web (SearXNG)</h4>
<div className="form-group" style={{ marginBottom: 0 }}>
<label>URL de SearXNG (pour enrichir l'IA)</label>
<input type="text" className="form-control" value={formData.searxngUrl} onChange={e => setFormData({...formData, searxngUrl: e.target.value})} placeholder="ex: http://localhost:8080" />
<div className="flex-1 overflow-y-auto p-6 pt-2 space-y-8 scrollbar-thin">
{/* Notion Integration */}
<section className="space-y-4">
<div className="flex items-center gap-2 text-primary font-semibold">
<LinkIcon size={18} />
<h4>Intégration Notion</h4>
</div>
<div className="grid gap-4 bg-muted/30 p-4 rounded-xl border">
<div className="grid gap-2">
<Label htmlFor="notionToken">Token d'intégration (Internal App)</Label>
<Input
id="notionToken"
type="password"
value={formData.notionToken}
onChange={e => setFormData({...formData, notionToken: e.target.value})}
placeholder="secret_..."
/>
</div>
<div className="grid gap-2">
<Label htmlFor="notionDbId">ID de la base de données</Label>
<Input
id="notionDbId"
type="text"
value={formData.notionDbId}
onChange={e => setFormData({...formData, notionDbId: e.target.value})}
placeholder="ex: a1b2c3d4e5f6..."
/>
</div>
</div>
</section>
{/* AI Integration */}
<section className="space-y-4">
<div className="flex items-center gap-2 text-secondary font-semibold">
<Cpu size={18} />
<h4>Intégration IA (Ollama Local)</h4>
</div>
<div className="grid gap-4 bg-secondary/5 p-4 rounded-xl border border-secondary/20">
<div className="grid gap-2">
<Label htmlFor="ollamaUrl">URL de l'API Ollama</Label>
<Input
id="ollamaUrl"
type="text"
value={formData.ollamaUrl}
onChange={e => setFormData({...formData, ollamaUrl: e.target.value})}
placeholder="ex: http://localhost:11434"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="ollamaModel">Nom du modèle</Label>
<Input
id="ollamaModel"
type="text"
value={formData.ollamaModel}
onChange={e => setFormData({...formData, ollamaModel: e.target.value})}
placeholder="ex: qwen:7b, llama3"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="language">Langue de sortie</Label>
<Select
value={formData.aiLanguage}
onValueChange={(val) => setFormData({...formData, aiLanguage: val})}
>
<SelectTrigger id="language">
<SelectValue placeholder="Choisir une langue" />
</SelectTrigger>
<SelectContent>
<SelectItem value="Français">Français</SelectItem>
<SelectItem value="English">English</SelectItem>
<SelectItem value="Español">Español</SelectItem>
<SelectItem value="Deutsch">Deutsch</SelectItem>
<SelectItem value="Italiano">Italiano</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</section>
{/* Search Integration */}
<section className="space-y-4">
<div className="flex items-center gap-2 text-amber-500 font-semibold">
<Globe size={18} />
<h4>Recherche Web (SearXNG)</h4>
</div>
<div className="grid gap-4 bg-amber-500/5 p-4 rounded-xl border border-amber-500/20">
<div className="grid gap-2">
<Label htmlFor="searxngUrl">URL de SearXNG (enrichissement IA)</Label>
<Input
id="searxngUrl"
type="text"
value={formData.searxngUrl}
onChange={e => setFormData({...formData, searxngUrl: e.target.value})}
placeholder="ex: http://localhost:8080"
/>
</div>
</div>
</section>
</div>
<DialogFooter className="p-6 border-t bg-muted/10">
<div className="flex items-center justify-between w-full">
<div className="flex items-center gap-2">
{saved && (
<div className="flex items-center gap-1.5 text-green-500 animate-in fade-in slide-in-from-left-1">
<CheckCircle2 size={16} />
<span className="text-sm font-medium">Sauvegardé avec succès</span>
</div>
)}
</div>
<div className="flex gap-2">
<Button variant="ghost" onClick={onClose}>Fermer</Button>
<Button onClick={handleSubmit}>Enregistrer les modifications</Button>
</div>
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: '1rem', alignItems: 'center' }}>
{saved && <span style={{ color: 'var(--success-color)', fontSize: '0.875rem' }}>Sauvegardé !</span>}
<button type="button" className="btn" onClick={onClose}>Fermer</button>
<button type="submit" className="btn btn-primary">Enregistrer</button>
</div>
</form>
</div>
</div>,
document.body
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+19
View File
@@ -0,0 +1,19 @@
import React from 'react';
export const DockerIcon = ({ size = 24, className = "" }: { size?: number, className?: string }) => (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={className}
>
<path d="M22 7.7a.8.8 0 0 0-.5-.7l-9-5.2a.8.8 0 0 0-.8 0l-9 5.2a.8.8 0 0 0-.5.7v10.4c0 .3.2.6.5.7l9 5.2a.8.8 0 0 0 .8 0l9-5.2c.3-.1.5-.4.5-.7V7.7Z" />
<path d="M3.3 7L12 12l8.7-5" />
<path d="M12 22V12" />
</svg>
);
+36
View File
@@ -0,0 +1,36 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }
+56
View File
@@ -0,0 +1,56 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }
+79
View File
@@ -0,0 +1,79 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-lg border bg-card text-card-foreground shadow-sm",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"text-2xl font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
+122
View File
@@ -0,0 +1,122 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}
+22
View File
@@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }
+24
View File
@@ -0,0 +1,24 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }
+158
View File
@@ -0,0 +1,158 @@
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown, ChevronUp } from "lucide-react"
import { cn } from "@/lib/utils"
const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
))
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-select-content-transform-origin]",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
}
+31
View File
@@ -0,0 +1,31 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = "horizontal", decorative = true, ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className
)}
{...props}
/>
)
)
Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }
+15
View File
@@ -0,0 +1,15 @@
import { cn } from "@/lib/utils"
function Skeleton({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn("animate-pulse rounded-md bg-muted", className)}
{...props}
/>
)
}
export { Skeleton }
+53
View File
@@ -0,0 +1,53 @@
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }
+220 -1410
View File
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+1
View File
@@ -13,6 +13,7 @@ export interface GlobalSettings {
ollamaUrl: string;
ollamaModel: string;
searxngUrl: string;
aiLanguage?: string;
}
export interface Message {
+196 -154
View File
@@ -3,6 +3,13 @@ import { useNavigate } from 'react-router-dom';
import { PlusCircle, Clock, Server, HardDrive, LayoutGrid, Search, SearchX, Globe, ChevronRight } from 'lucide-react';
import AddServiceModal from '../components/AddServiceModal';
import type { LogService } from '../types';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Separator } from "@/components/ui/separator";
import { DockerIcon } from '../components/icons/DockerIcon';
interface SystemService {
name: string;
@@ -18,6 +25,7 @@ export default function HomeView() {
const [isModalOpen, setIsModalOpen] = useState(false);
const [searchTerm, setSearchTerm] = useState('');
const [systemServices, setSystemServices] = useState<SystemService[]>([]);
const [activeTab, setActiveTab] = useState('all');
const navigate = useNavigate();
const fetchServices = async () => {
@@ -28,7 +36,6 @@ export default function HomeView() {
const data = await res.json();
setServices(data);
// Load recents from localStorage
const recentIds: number[] = JSON.parse(localStorage.getItem('recentServiceIds') || '[]');
const recents = data.filter((s: LogService) => recentIds.includes(s.id as any))
.sort((a: LogService, b: LogService) => recentIds.indexOf(a.id as any) - recentIds.indexOf(b.id as any));
@@ -39,7 +46,7 @@ export default function HomeView() {
};
const fetchSystemServices = async () => {
if (systemServices.length > 0) return; // Only fetch once or when forced
if (systemServices.length > 0) return;
try {
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3001';
const [dockerRes, osRes] = await Promise.allSettled([
@@ -50,12 +57,8 @@ export default function HomeView() {
let dockerData: any[] = [];
let osData: any[] = [];
if (dockerRes.status === 'fulfilled') {
dockerData = await dockerRes.value.json();
}
if (osRes.status === 'fulfilled') {
osData = await osRes.value.json();
}
if (dockerRes.status === 'fulfilled') dockerData = await dockerRes.value.json();
if (osRes.status === 'fulfilled') osData = await osRes.value.json();
const combined: SystemService[] = [
...dockerData.map((d: any) => ({ name: d.name, id: d.id, image: d.image, type: 'docker' as const, state: d.state })),
@@ -64,8 +67,6 @@ export default function HomeView() {
setSystemServices(combined);
} catch (e) {
console.error('Erreur lors du fetch des services système', e);
} finally {
// setIsSearchingSystem(false);
}
};
@@ -73,11 +74,14 @@ export default function HomeView() {
fetchServices();
}, []);
// Filter systems services based on search
const filteredRegistered = services.filter(s =>
s.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
s.pathOrContainerId.toLowerCase().includes(searchTerm.toLowerCase())
);
const filteredRegistered = services.filter(s => {
const matchesSearch = s.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
s.pathOrContainerId.toLowerCase().includes(searchTerm.toLowerCase());
const matchesTab = activeTab === 'all' ||
(activeTab === 'docker' && s.type === 'docker') ||
(activeTab === 'os' && s.type === 'os_service');
return matchesSearch && matchesTab;
});
const filteredSystem = systemServices.filter(s => {
const term = searchTerm.toLowerCase();
@@ -85,14 +89,17 @@ export default function HomeView() {
(s.id && s.id.toLowerCase().includes(term)) ||
(s.image && s.image.toLowerCase().includes(term));
// On ne l'affiche en éphémère que s'il n'est pas déjà enregistré par son ID ou son Nom exact
const isAlreadyRegistered = services.some(reg =>
reg.name === s.name ||
reg.pathOrContainerId === s.id ||
(s.id && reg.pathOrContainerId.includes(s.id))
);
return matchesSearch && !isAlreadyRegistered;
const matchesTab = activeTab === 'all' ||
(activeTab === 'docker' && s.type === 'docker') ||
(activeTab === 'os' && s.type === 'os');
return matchesSearch && !isAlreadyRegistered && matchesTab;
});
const handleSearchFocus = () => {
@@ -100,151 +107,186 @@ export default function HomeView() {
};
return (
<div className="home-view fade-in">
<section className="welcome-banner glass-panel">
<div>
<h2 style={{ margin: 0, fontSize: '1.8rem' }}>Bienvenue sur votre Log AI</h2>
<p style={{ color: 'var(--text-muted)', marginTop: '0.5rem' }}>Visualisez et analysez vos logs de services en temps réel avec l'IA.</p>
</div>
<button className="btn btn-primary" onClick={() => setIsModalOpen(true)}>
<PlusCircle size={18} />
Ajouter un Service
</button>
</section>
{/* Barre de Recherche */}
<section className="search-section">
<div className="search-bar-container glass-panel">
<Search size={20} className="search-icon" />
<input
type="text"
placeholder="Rechercher un service enregistré ou un conteneur sur l'hôte..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onFocus={handleSearchFocus}
/>
{searchTerm && (
<button className="btn-clear-search" onClick={() => setSearchTerm('')}>
<SearchX size={18} />
</button>
)}
</div>
</section>
{searchTerm && (
<section className="dashboard-section search-results fade-in">
<div className="section-header">
<Globe size={20} color="var(--accent-color)" />
<h3>Résultats pour "{searchTerm}"</h3>
<div className="max-w-7xl mx-auto px-4 py-8 space-y-12 fade-in">
{/* Welcome Banner */}
<div className="relative overflow-hidden rounded-3xl bg-card border shadow-sm">
<div className="absolute inset-0 bg-gradient-to-r from-primary/10 via-transparent to-secondary/5" />
<CardContent className="relative flex flex-col md:flex-row items-center justify-between p-10 gap-8">
<div className="space-y-3">
<h2 className="text-4xl font-bold tracking-tight">Bienvenue sur votre Log <span className="ai-gradient-text tracking-tighter">AI</span></h2>
<p className="text-muted-foreground text-lg max-w-xl">Supervisez et diagnostiquez vos services en temps réel avec la puissance de l'IA.</p>
</div>
<div className="search-results-list">
{/* Résultats Enregistrés */}
{filteredRegistered.map(s => (
<div key={`reg-${s.id}`} className="glass-panel search-result-item" onClick={() => navigate(`/service/${s.id}`)}>
<div className="res-icon registered">
{s.type === 'docker' ? <Server size={18} /> : <HardDrive size={18} />}
</div>
<div className="res-info">
<span className="res-name">{s.name}</span>
<span className="res-meta">Auto-Log (Enregistré)</span>
</div>
<div className="res-status">
<ChevronRight size={18} />
</div>
</div>
))}
<Button size="lg" className="h-14 px-10 rounded-2xl shadow-lg hover:shadow-primary/20 transition-all font-semibold" onClick={() => setIsModalOpen(true)}>
<PlusCircle size={22} className="mr-2" />
Ajouter un Service
</Button>
</CardContent>
</div>
{/* Résultats Système (Éphémères) */}
{filteredSystem.map((s, idx) => (
<div
key={`sys-${idx}`}
className="glass-panel search-result-item ephemeral"
onClick={() => navigate(`/service/ephemeral?type=${s.type}&target=${s.id || s.name}&name=${s.name}`)}
{/* Barre de Recherche et Filtres */}
<section className="space-y-8">
<div className="relative max-w-3xl mx-auto">
<div className="relative group">
<Search size={22} className="absolute left-4 top-1/2 -translate-y-1/2 text-muted-foreground transition-colors group-focus-within:text-primary" />
<Input
type="text"
placeholder="Rechercher un service, un conteneur, une image..."
className="h-14 pl-12 pr-12 text-lg rounded-2xl bg-card border-muted/50 focus:border-primary/50 focus:ring-primary/20 transition-all shadow-sm"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onFocus={handleSearchFocus}
/>
{searchTerm && (
<button
className="absolute right-4 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
onClick={() => setSearchTerm('')}
>
<div className="res-icon system">
{s.type === 'docker' ? <Server size={18} /> : <HardDrive size={18} />}
</div>
<div className="res-info">
<span className="res-name">{s.name}</span>
<span className="res-meta">
{s.type === 'docker' ? `Image: ${s.image || 'N/A'}` : 'Exploration Éphémère (Machine)'}
</span>
</div>
<div className="res-badge">Éphémère</div>
<div className="res-status">
<ChevronRight size={18} />
</div>
</div>
))}
{filteredRegistered.length === 0 && filteredSystem.length === 0 && (
<div className="no-search-results">
<p>Aucun service correspondant à votre recherche.</p>
</div>
<SearchX size={22} />
</button>
)}
</div>
</section>
)}
</div>
{!searchTerm && (
<>
{recentServices.length > 0 && (
<section className="dashboard-section">
<div className="section-header">
<Clock size={20} color="var(--accent-color)" />
<h3>Récemment Consultés</h3>
</div>
<div className="recent-grid">
{recentServices.map(s => (
<div
key={s.id}
className="glass-panel recent-card"
onClick={() => navigate(`/service/${s.id}`)}
>
<div className="recent-card-icon">
{s.type === 'docker' ? <Server size={20} /> : <HardDrive size={20} />}
</div>
<div className="recent-card-info">
<h4>{s.name}</h4>
<span>{s.type === 'docker' ? 'Conteneur' : 'Système'}</span>
</div>
</div>
))}
</div>
</section>
)}
<Tabs defaultValue="all" className="w-full" onValueChange={setActiveTab}>
<div className="flex flex-col items-center gap-6">
<TabsList className="bg-muted/30 p-1 rounded-xl border border-muted/50">
<TabsTrigger value="all" className="rounded-lg px-8 py-2 data-[state=active]:bg-card data-[state=active]:shadow-sm">Tous</TabsTrigger>
<TabsTrigger value="docker" className="rounded-lg px-8 py-2 data-[state=active]:bg-card data-[state=active]:shadow-sm">Docker</TabsTrigger>
<TabsTrigger value="os" className="rounded-lg px-8 py-2 data-[state=active]:bg-card data-[state=active]:shadow-sm">Système</TabsTrigger>
</TabsList>
</div>
<section className="dashboard-section">
<div className="section-header">
<LayoutGrid size={20} color="var(--accent-hover)" />
<h3>Tous les Services ({services.length})</h3>
</div>
<div className="service-grid">
{services.map(s => (
<div
key={s.id}
className="glass-panel service-card"
onClick={() => navigate(`/service/${s.id}`)}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', marginBottom: '1rem' }}>
{s.type === 'docker' ? <Server size={24} color="var(--accent-color)" /> : <HardDrive size={24} color="var(--accent-hover)" />}
<h3 style={{ margin: 0, fontSize: '1.1rem' }}>{s.name}</h3>
</div>
<p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', fontFamily: 'monospace', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{s.pathOrContainerId}
</p>
<TabsContent value={activeTab} className="mt-8 space-y-12">
{searchTerm && (
<section className="space-y-6 fade-in">
<div className="flex items-center gap-4">
<Globe className="text-primary" size={20} />
<h3 className="text-xl font-bold tracking-tight">Résultats de recherche</h3>
<Separator className="flex-1" />
</div>
))}
{services.length === 0 && (
<p style={{ color: 'var(--text-muted)', gridColumn: '1 / -1', textAlign: 'center', padding: '3rem' }}>
Aucun service configuré. Commencez par en ajouter un !
</p>
)}
</div>
</section>
</>
)}
<div className="grid gap-4">
{filteredRegistered.map(s => (
<Card
key={`reg-${s.id}`}
className="hover:bg-muted/20 border-transparent hover:border-primary/20 transition-all cursor-pointer group shadow-none hover:shadow-md"
onClick={() => navigate(`/service/${s.id}`)}
>
<CardContent className="flex items-center p-5 gap-5">
<div className="w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center text-primary group-hover:bg-primary group-hover:text-primary-foreground transition-all duration-300">
{s.type === 'docker' ? <DockerIcon size={24} /> : <Server size={24} />}
</div>
<div className="flex-1 min-w-0">
<div className="font-bold text-lg truncate">{s.name}</div>
<div className="text-sm text-muted-foreground uppercase tracking-wider font-medium opacity-70">Service Enregistré</div>
</div>
<ChevronRight size={20} className="text-muted-foreground opacity-0 group-hover:opacity-100 -translate-x-2 group-hover:translate-x-0 transition-all" />
</CardContent>
</Card>
))}
{filteredSystem.map((s, idx) => (
<Card
key={`sys-${idx}`}
className="hover:bg-muted/20 border-dashed border-2 hover:border-solid hover:border-secondary/30 transition-all cursor-pointer group shadow-none"
onClick={() => navigate(`/service/ephemeral?type=${s.type}&target=${s.id || s.name}&name=${s.name}`)}
>
<CardContent className="flex items-center p-5 gap-5">
<div className="w-12 h-12 rounded-xl bg-secondary/10 flex items-center justify-center text-secondary group-hover:bg-secondary group-hover:text-secondary-foreground transition-all duration-300">
{s.type === 'docker' ? <DockerIcon size={24} /> : <Server size={24} />}
</div>
<div className="flex-1 min-w-0">
<div className="font-bold text-lg truncate">{s.name}</div>
<div className="text-sm text-muted-foreground truncate opacity-70">
{s.type === 'docker' ? `Image: ${s.image || 'N/A'}` : 'Processus système'}
</div>
</div>
<Badge variant="outline" className="text-secondary border-secondary/30 bg-secondary/5 font-bold uppercase text-[10px] tracking-widest">Éphémère</Badge>
<ChevronRight size={20} className="text-muted-foreground opacity-0 group-hover:opacity-100 -translate-x-2 group-hover:translate-x-0 transition-all" />
</CardContent>
</Card>
))}
{filteredRegistered.length === 0 && filteredSystem.length === 0 && (
<div className="text-center py-20 bg-muted/10 rounded-3xl border border-dashed">
<p className="text-muted-foreground text-lg italic">Aucun service correspondant à votre recherche.</p>
</div>
)}
</div>
</section>
)}
{!searchTerm && (
<div className="space-y-12">
{recentServices.length > 0 && (
<section className="space-y-6">
<div className="flex items-center gap-4">
<Clock className="text-primary" size={18} />
<h3 className="text-lg font-bold tracking-tight uppercase tracking-wider text-muted-foreground">Consultés Récemment</h3>
<Separator className="flex-1" />
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{recentServices.map(s => (
<Card
key={s.id}
className="hover:border-primary/30 transition-all cursor-pointer group shadow-none relative overflow-hidden h-24"
onClick={() => navigate(`/service/${s.id}`)}
>
<CardContent className="flex items-center h-full p-4 gap-4">
<div className="w-10 h-10 rounded-lg bg-muted flex items-center justify-center text-primary group-hover:bg-primary/10 transition-colors">
{s.type === 'docker' ? <DockerIcon size={20} /> : <Server size={20} />}
</div>
<div className="flex-1 min-w-0">
<h4 className="font-bold text-sm truncate">{s.name}</h4>
<span className="text-[10px] text-muted-foreground uppercase font-bold tracking-tighter opacity-60">{s.type === 'docker' ? 'Docker' : 'OS'}</span>
</div>
</CardContent>
</Card>
))}
</div>
</section>
)}
<section className="space-y-6">
<div className="flex items-center gap-4">
<LayoutGrid size={18} className="text-primary" />
<h3 className="text-lg font-bold tracking-tight uppercase tracking-wider text-muted-foreground">Tous les Services ({services.length})</h3>
<Separator className="flex-1" />
</div>
<div className="grid sm:grid-cols-2 gap-4">
{filteredRegistered.map(s => (
<Card
key={s.id}
className="hover:border-primary/50 hover:bg-muted/10 transition-all cursor-pointer shadow-none group"
onClick={() => navigate(`/service/${s.id}`)}
>
<CardHeader className="p-5 pb-3">
<CardTitle className="text-lg flex items-center gap-4">
<div className="p-2 rounded-lg bg-primary/5 text-primary group-hover:bg-primary/10 transition-colors">
{s.type === 'docker' ? <DockerIcon size={20} /> : <Server size={20} />}
</div>
<span className="truncate">{s.name}</span>
</CardTitle>
</CardHeader>
<CardContent className="p-5 pt-0">
<p className="text-xs text-muted-foreground font-mono truncate opacity-60">
{s.pathOrContainerId}
</p>
</CardContent>
</Card>
))}
{filteredRegistered.length === 0 && (
<div className="text-center py-20 bg-muted/10 rounded-3xl border border-dashed col-span-full">
<p className="text-muted-foreground italic text-lg">Aucun service trouvé dans cette catégorie.</p>
</div>
)}
</div>
</section>
</div>
)}
</TabsContent>
</Tabs>
</section>
{isModalOpen && (
<AddServiceModal
+54 -45
View File
@@ -1,7 +1,11 @@
import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { LogIn, Mail, Lock, ShieldCheck } from 'lucide-react';
import { LogIn, Mail, Lock } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
export default function LoginView() {
const [email, setEmail] = useState('');
@@ -40,52 +44,57 @@ export default function LoginView() {
};
return (
<div className="auth-view fade-in">
<div className="glass-panel auth-card">
<div className="auth-header">
<div className="auth-icon-wrapper">
<ShieldCheck size={32} color="var(--accent-color)" />
</div>
<h2>Connexion Sécurisée</h2>
<p>Entrez vos identifiants pour accéder aux logs</p>
</div>
<div className="flex items-center justify-center min-h-[80vh] fade-in">
<Card className="w-full max-w-md">
<CardHeader className="space-y-1">
<CardTitle className="text-2xl text-center">Connexion</CardTitle>
</CardHeader>
<CardContent>
{error && (
<div className="bg-destructive/15 text-destructive text-sm p-3 rounded-md mb-4">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email" className="flex items-center gap-2">
<Mail size={14} /> Email
</Label>
<Input
id="email"
required
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
placeholder="name@example.com"
/>
</div>
{error && <div className="auth-error">{error}</div>}
<div className="space-y-2">
<Label htmlFor="password" title="Password" className="flex items-center gap-2">
<Lock size={14} /> Mot de passe
</Label>
<Input
id="password"
required
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="••••••••"
/>
</div>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label><Mail size={16} /> Email</label>
<input
required
type="email"
className="form-control"
value={email}
onChange={e => setEmail(e.target.value)}
placeholder="votre@email.com"
/>
</div>
<div className="form-group">
<label><Lock size={16} /> Mot de passe</label>
<input
required
type="password"
className="form-control"
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="••••••••"
/>
</div>
<button type="submit" className="btn btn-primary btn-block" disabled={isSubmitting}>
{isSubmitting ? 'Connexion...' : <><LogIn size={18} /> Se connecter</>}
</button>
</form>
<div className="auth-footer">
Nouveau ici ? <Link to="/signup">Créer un compte</Link>
</div>
</div>
<Button type="submit" className="w-full" disabled={isSubmitting}>
{isSubmitting ? 'Connexion...' : <><LogIn size={18} className="mr-2" /> Se connecter</>}
</Button>
</form>
</CardContent>
<CardFooter className="flex justify-center border-t p-4">
<p className="text-sm text-muted-foreground italic">
Nouveau ici ? <Link to="/signup" className="text-primary font-medium hover:underline">Créer un compte</Link>
</p>
</CardFooter>
</Card>
</div>
);
}
+113 -98
View File
@@ -1,27 +1,35 @@
import { useState, useEffect } from 'react';
import { useNavigate, useParams, useLocation } from 'react-router-dom';
import { ArrowLeft, Server, HardDrive, Trash2, Save, Check, Pencil } from 'lucide-react';
import { useNavigate, useParams, useLocation, Link } from 'react-router-dom';
import { ArrowLeft, Server, HardDrive, 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, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { DockerIcon } from '../components/icons/DockerIcon';
function DeleteWithConfirmation({ onDelete, serviceName }: { onDelete: () => void, serviceName: string }) {
const [showConfirm, setShowConfirm] = useState(false);
if (showConfirm) {
return (
<div className="delete-confirm-box">
<span>Supprimer {serviceName} ?</span>
<button className="btn btn-danger btn-sm" onClick={onDelete}>Oui</button>
<button className="btn btn-sm" onClick={() => setShowConfirm(false)}>Non</button>
<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 className="btn btn-danger-outline btn-sm" onClick={() => setShowConfirm(true)}>
<Trash2 size={16} />
<span>Supprimer</span>
</button>
<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>
);
}
@@ -36,11 +44,10 @@ export default function ServiceView() {
const [isSaved, setIsSaved] = useState(false);
const [isEditingName, setIsEditingName] = useState(false);
const [tempName, setTempName] = useState('');
const isTransitioningRef = useState(false); // Pour bloquer les redirects pendant la sauvegarde
const [isTransitioning, setIsTransitioning] = useState(false);
useEffect(() => {
const fetchServiceAndLogs = async () => {
// Si on a déjà les données via la navigation (state), on économise un fetch et on évite les redirects
if (service && (service.id === Number(id) || (id === 'ephemeral' && typeof service.id === 'string'))) {
setLoading(false);
return;
@@ -49,7 +56,6 @@ export default function ServiceView() {
try {
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3001';
// Mode Éphémère
if (id === 'ephemeral') {
const params = new URLSearchParams(window.location.search);
const type = params.get('type') || 'docker';
@@ -61,7 +67,6 @@ export default function ServiceView() {
return;
}
// Fetch des logs via le nouvel endpoint éphémère
const logsRes = await fetch(`${apiUrl}/api/logs/ephemeral?type=${type}&target=${target}&name=${encodeURIComponent(name)}`, {
credentials: 'include'
});
@@ -80,14 +85,9 @@ export default function ServiceView() {
return;
}
// Mode Classique (Base de données)
const [svcRes, logsRes] = await Promise.all([
fetch(`${apiUrl}/api/services`, {
credentials: 'include'
}),
fetch(`${apiUrl}/api/services/${id}/logs`, {
credentials: 'include'
})
fetch(`${apiUrl}/api/services`, { credentials: 'include' }),
fetch(`${apiUrl}/api/services/${id}/logs`, { credentials: 'include' })
]);
const allServices = await svcRes.json();
@@ -98,8 +98,11 @@ export default function ServiceView() {
if (found) {
setService(found);
setInitialLogs(logs);
updateRecentHistory(Number(id));
} else if (!isTransitioningRef[0]) { // Ne pas rediriger si on est en train de sauvegarder
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) {
@@ -112,7 +115,6 @@ export default function ServiceView() {
fetchServiceAndLogs();
return () => {
// Cleanup de l'éphémère si nécessaire
const params = new URLSearchParams(window.location.search);
const target = params.get('target');
if (id === 'ephemeral' && target) {
@@ -125,14 +127,6 @@ export default function ServiceView() {
};
}, [id, window.location.search]);
const updateRecentHistory = (id: number) => {
const recents: number[] = JSON.parse(localStorage.getItem('recentServiceIds') || '[]');
// Filtrer si déjà présent et mettre au début
const filtered = recents.filter(rid => rid !== id);
const updated = [id, ...filtered].slice(0, 5); // Garder les 5 derniers
localStorage.setItem('recentServiceIds', JSON.stringify(updated));
};
const handleSaveName = async () => {
if (!service || !tempName.trim() || tempName === service.name) {
setIsEditingName(false);
@@ -141,8 +135,6 @@ export default function ServiceView() {
try {
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3001';
// Si on est en mode persistant, on sauve en base
if (typeof service.id === 'number') {
const res = await fetch(`${apiUrl}/api/services/${service.id}`, {
method: 'PATCH',
@@ -150,11 +142,9 @@ export default function ServiceView() {
body: JSON.stringify({ name: tempName.trim() }),
credentials: 'include'
});
if (!res.ok) throw new Error('Erreur lors de la mise à jour du nom');
const updated = await res.json();
setService(updated);
if (!res.ok) throw new Error('Erreur');
setService(await res.json());
} else {
// En mode éphémère, on met juste à jour l'état local
setService({ ...service, name: tempName.trim() });
}
setIsEditingName(false);
@@ -167,6 +157,7 @@ export default function ServiceView() {
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`, {
@@ -183,17 +174,14 @@ export default function ServiceView() {
const savedService = await res.json();
setIsSaved(true);
// Navigation propre en passant le service dans le 'state' pour que le prochain render le récupère direct
setTimeout(() => {
setIsSaving(false);
navigate(`/service/${savedService.id}`, {
replace: true,
state: { service: savedService }
});
navigate(`/service/${savedService.id}`, { replace: true, state: { service: savedService } });
}, 1000);
} catch (err) {
console.error(err);
setIsSaving(false);
setIsTransitioning(false);
}
};
@@ -209,76 +197,103 @@ export default function ServiceView() {
}
};
if (loading) return <div className="loading-state">Chargement du service...</div>;
if (!service) return <div className="loading-state">Service introuvable.</div>;
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="service-view fade-in">
<button className="btn btn-back" onClick={() => navigate('/')}>
<ArrowLeft size={18} />
<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>
</Button>
<div className="glass-panel service-view-container" style={{ marginTop: '1rem', padding: 0, overflow: 'hidden' }}>
<div className="service-view-header">
<div className="service-info-main">
<div className="service-icon-wrapper">
{service.type === 'docker' ? <Server size={24} /> : <HardDrive size={24} />}
<Card className="overflow-hidden shadow-sm border-muted/50 rounded-xl">
<CardHeader className="bg-muted/10 p-8 space-y-6 flex flex-col md:flex-row items-start md:items-center justify-between gap-6">
<div className="flex items-center gap-6">
<div className="w-16 h-16 rounded-2xl bg-card border flex items-center justify-center text-primary shadow-sm group-hover:bg-primary/5 transition-colors">
{service.type === 'docker' ? <DockerIcon size={32} /> : <Server size={32} />}
</div>
<div className="service-info-text">
{isEditingName ? (
<input
type="text"
className="inline-edit-input"
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="service-title" onClick={() => { setIsEditingName(true); setTempName(service.name); }}>
{service.name}
<Pencil size={14} className="edit-icon-hint" />
</h3>
)}
<span className="service-subtitle">{service.pathOrContainerId}</span>
<div className="space-y-2">
<div className="flex items-center gap-3 flex-wrap">
{isEditingName ? (
<Input
className="h-10 w-72 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-3xl font-bold tracking-tight cursor-pointer hover:text-primary transition-colors flex items-center gap-3 group" onClick={() => { setIsEditingName(true); setTempName(service.name); }}>
{service.name}
<Pencil size={18} className="opacity-0 group-hover:opacity-40 transition-opacity" />
</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-3 py-1 uppercase tracking-widest text-[10px]">Session Éphémère</Badge>
)}
</div>
<div className="flex items-center gap-3">
<p className="text-sm font-mono text-muted-foreground opacity-70 truncate max-w-[200px] md:max-w-md">
{service.pathOrContainerId}
</p>
<Badge variant="outline" className="text-[10px] font-mono opacity-50 uppercase tracking-tighter">ID: {id}</Badge>
</div>
</div>
</div>
<div className="service-actions">
{/* Si c'est un service réel (ID numérique) ou qu'on vient de l'enregistrer */}
{(typeof service.id === 'number') && (
<DeleteWithConfirmation
onDelete={handleDelete}
serviceName={service.name}
/>
<div className="flex items-center gap-4 shrink-0 w-full md:w-auto justify-end">
{typeof service.id === 'number' && (
<DeleteWithConfirmation onDelete={handleDelete} serviceName={service.name} />
)}
{/* Si on est en mode éphémère ET pas encore enregistré */}
{typeof service.id === 'string' && service.id.startsWith('ephemeral') && (
<>
{!isSaved && <span className="ephemeral-badge-large">Mode Éphémère</span>}
<button
className={`btn ${isSaved ? 'btn-success' : 'btn-primary'} btn-save-action`}
onClick={handleSave}
disabled={isSaving || isSaved}
>
{isSaved ? <Check size={18} className="success-check-anim" /> : <Save size={18} />}
<span>{isSaved ? 'Enregistré !' : 'Enregistrer'}</span>
</button>
</>
<Button
variant={isSaved ? "outline" : "default"}
size="lg"
className={isSaved ? "border-green-500/50 text-green-500 hover:bg-green-500/5 px-8 rounded-2xl" : "bg-blue-700 hover:bg-blue-800 text-white border-none shadow-lg hover:shadow-blue-500/20 transition-all font-semibold px-8 rounded-2xl"}
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>
</div>
</CardHeader>
<div style={{ padding: '1rem' }}>
<Separator />
<CardContent className="p-0 bg-transparent">
<LogTerminal service={service} initialLogs={initialLogs} />
</div>
</div>
</CardContent>
</Card>
</div>
);
}
+71 -77
View File
@@ -1,13 +1,16 @@
import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { UserPlus, Mail, Lock, User, CheckCircle } from 'lucide-react';
import { UserPlus, Mail, Lock, User } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
export default function SignupView() {
const [email, setEmail] = useState('');
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [error, setError] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
@@ -16,10 +19,6 @@ export default function SignupView() {
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (password !== confirmPassword) {
return setError('Les mots de passe ne correspondent pas');
}
setIsSubmitting(true);
setError('');
@@ -27,8 +26,7 @@ export default function SignupView() {
const res = await fetch(`${import.meta.env.VITE_API_URL || 'http://localhost:3001'}/api/auth/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ email, password, name })
body: JSON.stringify({ name, email, password })
});
const data = await res.json();
@@ -36,7 +34,7 @@ export default function SignupView() {
login(data.user);
navigate('/');
} else {
setError(data.error || 'Erreur lors de l’inscription');
setError(data.error || 'Une erreur est survenue');
}
} catch (err) {
setError('Erreur de connexion au serveur');
@@ -46,76 +44,72 @@ export default function SignupView() {
};
return (
<div className="auth-view fade-in">
<div className="glass-panel auth-card">
<div className="auth-header">
<div className="auth-icon-wrapper">
<UserPlus size={32} color="var(--accent-hover)" />
</div>
<h2>Créer un Compte</h2>
<p>Rejoignez la plateforme de monitoring intelligente</p>
</div>
<div className="flex items-center justify-center min-h-[80vh] fade-in">
<Card className="w-full max-w-md">
<CardHeader className="space-y-1">
<CardTitle className="text-2xl text-center">Créer un compte</CardTitle>
</CardHeader>
<CardContent>
{error && (
<div className="bg-destructive/15 text-destructive text-sm p-3 rounded-md mb-4">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name" className="flex items-center gap-2">
<User size={14} /> Nom complet
</Label>
<Input
id="name"
required
type="text"
value={name}
onChange={e => setName(e.target.value)}
placeholder="Jean Dupont"
/>
</div>
{error && <div className="auth-error">{error}</div>}
<div className="space-y-2">
<Label htmlFor="email" className="flex items-center gap-2">
<Mail size={14} /> Email
</Label>
<Input
id="email"
required
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
placeholder="name@example.com"
/>
</div>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label><User size={16} /> Nom complet</label>
<input
required
type="text"
className="form-control"
value={name}
onChange={e => setName(e.target.value)}
placeholder="Goura"
/>
</div>
<div className="space-y-2">
<Label htmlFor="password" title="Password" className="flex items-center gap-2">
<Lock size={14} /> Mot de passe
</Label>
<Input
id="password"
required
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="••••••••"
minLength={6}
/>
</div>
<div className="form-group">
<label><Mail size={16} /> Email</label>
<input
required
type="email"
className="form-control"
value={email}
onChange={e => setEmail(e.target.value)}
placeholder="votre@email.com"
/>
</div>
<div className="form-group">
<label><Lock size={16} /> Mot de passe</label>
<input
required
type="password"
className="form-control"
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="••••••••"
/>
</div>
<div className="form-group">
<label><CheckCircle size={16} /> Confirmer le mot de passe</label>
<input
required
type="password"
className="form-control"
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
placeholder="••••••••"
/>
</div>
<button type="submit" className="btn btn-primary btn-block" disabled={isSubmitting}>
{isSubmitting ? 'Création...' : <><UserPlus size={18} /> S'inscrire</>}
</button>
</form>
<div className="auth-footer">
Déjà un compte ? <Link to="/login">Se connecter</Link>
</div>
</div>
<Button type="submit" className="w-full" disabled={isSubmitting}>
{isSubmitting ? 'Création...' : <><UserPlus size={18} className="mr-2" /> S'inscrire</>}
</Button>
</form>
</CardContent>
<CardFooter className="flex justify-center border-t p-4">
<p className="text-sm text-muted-foreground italic">
Déjà un compte ? <Link to="/login" className="text-primary font-medium hover:underline">Se connecter</Link>
</p>
</CardFooter>
</Card>
</div>
);
}
+52
View File
@@ -0,0 +1,52 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
},
},
plugins: [require("tailwindcss-animate")],
}
+4
View File
@@ -14,6 +14,10 @@
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
/* Linting */
"noUnusedLocals": true,
+6
View File
@@ -1,4 +1,10 @@
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
+10 -3
View File
@@ -1,7 +1,14 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from "path"
import { defineConfig } from "vite"
import react from "@vitejs/plugin-react"
import tailwindcss from "@tailwindcss/vite"
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
})