This commit is contained in:
Orionis312050 committed 2026-04-16 21:34:50 +02:00
1 parent dcbea5799a
commit e8a92bf87b
6 files changed
+874 -114

No files matched your search

+1 -1
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
<title>LogAI</title>
</head>
<body>
<div id="root"></div>
+2 -2
View File
@@ -39,13 +39,13 @@ function AppContent() {
<div className={`app-container ${theme}`}>
<header>
<h1 onClick={() => window.location.href = '/'} style={{ cursor: 'pointer' }}>
<span style={{ color: 'var(--accent-color)' }}>Log</span>Manager
Log<span className="ai-gradient-text">AI</span>
</h1>
<div style={{ display: 'flex', gap: '0.75rem' }}>
{user && (
<>
<button
className={`btn ${isChatOpen ? 'btn-primary' : 'btn-outline'}`}
className="btn btn-ai"
onClick={() => setIsChatOpen(!isChatOpen)}
title="Assistant IA"
>
+40 -1
View File
@@ -29,7 +29,7 @@ export default function LogTerminal({ service, initialLogs = [] }: {
setLogs(initialLogs);
pendingLogsRef.current = [];
const handleLogLine = (data: { serviceId: number, line: string }) => {
const handleLogLine = (data: { serviceId: number | string, line: string }) => {
if (data.serviceId === service.id) {
const isError = service.alertKeyword
? data.line.includes(service.alertKeyword)
@@ -103,6 +103,37 @@ export default function LogTerminal({ service, initialLogs = [] }: {
}));
};
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 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 chunkedLogs = [];
// Chunk starting from the end so latest logs are strictly grouped by 5
for (let i = logs.length; i > 0; i -= 5) {
@@ -123,6 +154,14 @@ export default function LogTerminal({ service, initialLogs = [] }: {
<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"
>
<Sparkles size={14} /> Diagnostic Complet
</button>
</div>
<span className="live-indicator">
<span className={`status-dot ${isPaused ? 'dot-red' : 'dot-green'}`}></span>
+453 -38
View File
@@ -6,13 +6,28 @@
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.ai-gradient-text {
background: linear-gradient(74deg, #4285f4 0%, #9b72cb 46%, #d96570 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
color: transparent;
}
:root {
/* Thème Sombre par défaut (Adouci / Slate) */
--bg-primary: #0f172a;
--bg-primary: #0f172a;
--bg-secondary: #1e293b;
--bg-elevated: #334155;
--border-color: rgba(255, 255, 255, 0.1);
@@ -22,7 +37,8 @@
--accent-hover: #2563eb;
--danger-color: #ef4444;
--success-color: #10b981;
--terminal-bg: #020617; /* Console reste toujours très noire */
--terminal-bg: #020617;
--terminal-text: #f8fafc;
}
/* Mode Clair */
@@ -33,6 +49,8 @@
--border-color: rgba(0, 0, 0, 0.1);
--text-main: #0f172a;
--text-muted: #475569;
--terminal-bg: #1e293b; /* Gris anthracite mat plus dense */
--terminal-text: #ffffff;
}
/* Custom Scrollbar Globale */
@@ -40,14 +58,17 @@
width: 10px;
height: 10px;
}
::-webkit-scrollbar-track {
background: var(--bg-primary);
}
::-webkit-scrollbar-thumb {
background: var(--bg-elevated);
border-radius: 5px;
border: 2px solid var(--bg-primary);
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-muted);
}
@@ -143,23 +164,75 @@ header h1 {
box-shadow: 0 0 12px rgba(59, 130, 246, 0.4);
}
@keyframes gradientMove {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
.btn-ai {
background-image: linear-gradient(135deg, #4285f4, #9b72cb, #d96570, #4285f4) !important;
background-size: 180% 100% !important;
background-position: 0% 50%;
color: white !important;
border: none !important;
font-weight: 600;
transition: all 0.5s ease;
position: relative;
overflow: hidden;
}
.btn-ai:hover {
animation: gradientMove 3s linear infinite !important;
box-shadow: 0 0 20px rgba(155, 114, 203, 0.5) !important;
transform: translateY(-1px);
}
.btn-ai:active {
transform: scale(0.94) !important;
filter: brightness(0.9);
}
.btn-ai-outline {
background: rgba(155, 114, 203, 0.1);
border: 1px solid rgba(155, 114, 203, 0.4);
color: #dcb3ff;
transition: all 0.2s ease;
}
.btn-ai-outline:hover {
background: rgba(155, 114, 203, 0.2);
border-color: rgba(155, 114, 203, 0.6);
color: #f3e8ff;
transform: translateY(-1px);
}
/* Modal styles */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.6);
background: rgba(0, 0, 0, 0.75); /* Un peu plus sombre pour le premium */
backdrop-filter: blur(4px); /* Petit effet de flou pour le look premium */
display: flex;
align-items: center;
justify-content: center;
z-index: 50;
animation: fadeIn 0.2s ease;
z-index: 2000;
animation: backdropFade 0.4s ease-out; /* Plus doux */
}
.modal-content {
width: 100%;
max-width: 500px;
padding: 2rem;
animation: slideUp 0.3s cubic-bezier(0.16, 1, 0.3, 1);
padding: 2.5rem;
animation: modalEntry 0.5s cubic-bezier(0.16, 1, 0.3, 1);
}
.form-group {
@@ -246,6 +319,22 @@ header h1 {
border-color: rgba(0, 255, 127, 0.3);
}
/* Overrides pour le mode clair */
.light-theme .btn-terminal {
border-color: rgba(0, 0, 0, 0.1);
}
.light-theme .btn-pause {
background: rgba(0, 0, 0, 0.05);
color: #1e293b;
}
.light-theme .btn-resume {
background: rgba(16, 185, 129, 0.1);
color: #059669;
border-color: rgba(16, 185, 129, 0.2);
}
.btn-terminal:hover {
transform: translateY(-1px);
background: rgba(255, 255, 255, 0.15);
@@ -298,17 +387,33 @@ header h1 {
font-family: 'Fira Code', 'Courier New', monospace;
font-size: 0.9rem;
line-height: 1.5;
color: var(--terminal-text);
}
@keyframes pulse {
0% { opacity: 0.4; }
50% { opacity: 1; }
100% { opacity: 0.4; }
0% {
opacity: 0.4;
}
50% {
opacity: 1;
}
100% {
opacity: 0.4;
}
}
@keyframes bounce {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.2); }
0%,
100% {
transform: scale(1);
}
50% {
transform: scale(1.2);
}
}
.log-line {
@@ -320,7 +425,7 @@ header h1 {
}
.log-line:hover {
background: rgba(255,255,255,0.02);
background: rgba(255, 255, 255, 0.02);
}
.log-error {
@@ -328,13 +433,25 @@ header h1 {
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes slideUp {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.service-grid {
@@ -451,6 +568,10 @@ header h1 {
color: white;
}
.light-theme .btn-back:hover {
color: var(--text-main);
}
.loading-state {
display: flex;
justify-content: center;
@@ -552,8 +673,15 @@ header h1 {
}
@keyframes fadeIn {
from { opacity: 0; transform: scale(0.95); }
to { opacity: 1; transform: scale(1); }
from {
opacity: 0;
transform: scale(0.95);
}
to {
opacity: 1;
transform: scale(1);
}
}
/* Auth Views */
@@ -652,6 +780,24 @@ header h1 {
transform: translateY(-1px);
}
.btn-icon {
background: transparent;
border: none;
color: var(--text-muted);
display: flex;
align-items: center;
justify-content: center;
padding: 0.4rem;
border-radius: 8px;
cursor: pointer;
transition: all 0.2s ease;
}
.btn-icon:hover {
background: rgba(255, 255, 255, 0.1);
color: var(--text-main);
}
.loading-state {
display: flex;
height: 50vh;
@@ -891,29 +1037,35 @@ header h1 {
background: rgba(59, 130, 246, 0.1);
}
/* Layout adjust when sidebar open */
.main-content.sidebar-open {
/* Layout adjust when sidebar open - Removed to make sidebar an overlay */
/* .main-content.sidebar-open {
margin-right: 400px;
}
@media (max-width: 1000px) {
.main-content.sidebar-open {
margin-right: 0;
}
}
} */
.spin {
animation: spin 1s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@keyframes slideUp {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Multi-Chat History Styles */
@@ -1017,16 +1169,18 @@ header h1 {
/* La fameuse fine barre continue */
.chunk-sidebar {
width: 24px;
width: 24px;
flex-shrink: 0;
border-left: 1px solid rgba(255, 255, 255, 0.05); /* Ligne subtile pour marquer la droite */
border-left: 1px solid rgba(255, 255, 255, 0.05);
/* Ligne subtile pour marquer la droite */
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
background: transparent;
transition: all 0.2s;
margin-right: -1rem; /* S'étend jusqu'au bord du padding */
margin-right: -1rem;
/* S'étend jusqu'au bord du padding */
}
.chunk-sidebar-icon {
@@ -1048,10 +1202,271 @@ header h1 {
/* Surbrillance visuelle automatique des logs dans cette zone (utilise le sélecteur :has pour Chrome/Safari modernes) */
.log-chunk:has(.chunk-sidebar:hover) .chunk-lines {
background: rgba(45, 120, 255, 0.08); /* Highlight de la zone de texte */
background: rgba(45, 120, 255, 0.08);
/* Highlight de la zone de texte */
}
/* Garder l'apparition du bouton sparkle au survol sur une ligne individuelle */
.log-line-wrapper {
position: relative;
}
/* Search & Ephemeral Styles */
.search-section {
margin: 1.5rem 0 2rem;
}
.search-bar-container {
display: flex;
align-items: center;
gap: 1rem;
padding: 0.85rem 1.5rem;
border-radius: 14px;
background: var(--bg-secondary);
border: 1.5px solid var(--border-color);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
.search-bar-container:focus-within {
border-color: var(--accent-color);
box-shadow: 0 8px 30px rgba(59, 130, 246, 0.15);
transform: translateY(-1px);
}
.search-icon {
color: var(--accent-color);
opacity: 0.8;
}
.search-bar-container input {
flex: 1;
background: transparent !important;
border: none !important;
color: var(--text-main) !important;
font-size: 1.05rem !important;
outline: none !important;
box-shadow: none !important;
}
.btn-clear-search {
background: rgba(255, 255, 255, 0.05);
border: none;
color: var(--text-muted);
width: 28px;
height: 28px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s;
}
.btn-clear-search:hover {
background: rgba(239, 68, 68, 0.1);
color: var(--danger-color);
}
.search-results-list {
display: grid;
grid-template-columns: 1fr;
gap: 0.75rem;
animation: slideUp 0.3s ease-out;
}
.search-result-item {
display: flex;
align-items: center;
gap: 1.25rem;
padding: 1.15rem 1.5rem;
border-radius: 12px;
cursor: pointer;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
border: 1px solid var(--border-color);
}
.search-result-item:hover {
background: rgba(255, 255, 255, 0.03);
border-color: var(--accent-color);
transform: scale(1.005) translateX(4px);
}
.res-icon {
width: 44px;
height: 44px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.res-icon.registered {
background: rgba(59, 130, 246, 0.1);
color: var(--accent-color);
box-shadow: 0 0 15px rgba(59, 130, 246, 0.1);
}
.res-icon.system {
background: rgba(148, 163, 184, 0.1);
color: var(--text-muted);
}
.res-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 0.2rem;
}
.res-name {
font-weight: 600;
font-size: 1.05rem;
color: var(--text-main);
}
.res-meta {
font-size: 0.8rem;
color: var(--text-muted);
opacity: 0.7;
}
.res-badge {
font-size: 0.65rem;
font-weight: 800;
text-transform: uppercase;
background: linear-gradient(135deg, #a78bfa 0%, #8b5cf6 100%);
color: white;
padding: 0.25rem 0.6rem;
border-radius: 6px;
letter-spacing: 0.05em;
box-shadow: 0 2px 8px rgba(139, 92, 246, 0.3);
}
.ephemeral-badge-large {
display: inline-flex;
align-items: center;
padding: 0.4rem 0.8rem;
border-radius: 8px;
background: rgba(139, 92, 246, 0.1);
color: #a78bfa;
font-size: 0.85rem;
font-weight: 600;
border: 1px solid rgba(139, 92, 246, 0.2);
margin-right: 0.5rem;
}
.no-search-results {
text-align: center;
padding: 3rem;
color: var(--text-muted);
background: rgba(255, 255, 255, 0.02);
border-radius: 12px;
border: 1px dashed var(--border-color);
}
/* Save Button & Success Anim */
.btn-save-action {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.5rem 1.2rem;
border-radius: 8px;
font-weight: 600;
transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.btn-save-action:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}
.btn-save-action:active {
transform: scale(0.95);
}
.success-check-anim {
animation: successScale 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
}
@keyframes successScale {
0% {
transform: scale(0) rotate(-45deg);
opacity: 0;
}
70% {
transform: scale(1.4) rotate(10deg);
}
100% {
transform: scale(1) rotate(0deg);
opacity: 1;
}
}
.btn-success {
background: #10b981 !important;
border-color: #10b981 !important;
color: white !important;
}
/* Inline Edit */
.service-info-text {
display: flex;
flex-direction: column;
}
.service-title {
display: flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
margin: 0;
font-size: 1.4rem;
}
.edit-icon-hint {
opacity: 0;
color: var(--accent-color);
transition: opacity 0.2s, transform 0.2s;
}
.service-title:hover .edit-icon-hint {
opacity: 0.6;
transform: translateX(2px);
}
.inline-edit-input {
background: rgba(255, 255, 255, 0.05);
border: 1px solid var(--accent-color);
border-radius: 4px;
color: var(--text-main);
font-size: 1.4rem;
font-weight: 600;
padding: 2px 8px;
margin: -3px -9px; /* Offset for alignment */
width: auto;
min-width: 200px;
outline: none;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.inline-edit-input:focus {
background: rgba(255, 255, 255, 0.08);
}
@keyframes backdropFade {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes modalEntry {
from {
opacity: 0;
transform: translateY(30px) scale(0.95);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
+207 -59
View File
@@ -1,13 +1,24 @@
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { PlusCircle, Clock, Server, HardDrive, LayoutGrid } from 'lucide-react';
import { PlusCircle, Clock, Server, HardDrive, LayoutGrid, Search, SearchX, Globe, Cpu, ChevronRight } from 'lucide-react';
import AddServiceModal from '../components/AddServiceModal';
import type { LogService } from '../types';
interface SystemService {
name: string;
id?: string; // Docker ID
image?: string; // Docker Image
type: 'docker' | 'os';
state: string;
}
export default function HomeView() {
const [services, setServices] = useState<LogService[]>([]);
const [recentServices, setRecentServices] = useState<LogService[]>([]);
const [isModalOpen, setIsModalOpen] = useState(false);
const [searchTerm, setSearchTerm] = useState('');
const [systemServices, setSystemServices] = useState<SystemService[]>([]);
const [isSearchingSystem, setIsSearchingSystem] = useState(false);
const navigate = useNavigate();
const fetchServices = async () => {
@@ -17,27 +28,85 @@ 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))
.sort((a: LogService, b: LogService) => recentIds.indexOf(a.id) - recentIds.indexOf(b.id));
.sort((a: LogService, b: LogService) => recentIds.indexOf(a.id) - recentIds.indexOf(b.id));
setRecentServices(recents);
} catch (e) {
console.error('API non joignable', e);
}
};
const fetchSystemServices = async () => {
if (systemServices.length > 0) return; // Only fetch once or when forced
setIsSearchingSystem(true);
try {
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3001';
const [dockerRes, osRes] = await Promise.allSettled([
fetch(`${apiUrl}/api/docker/containers`, { credentials: 'include' }),
fetch(`${apiUrl}/api/os/services`, { credentials: 'include' })
]);
let dockerData: any[] = [];
let osData: any[] = [];
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 })),
...osData.map((s: any) => ({ name: s.name, type: 'os' as const, state: s.state }))
];
setSystemServices(combined);
} catch (e) {
console.error('Erreur lors du fetch des services système', e);
} finally {
setIsSearchingSystem(false);
}
};
useEffect(() => {
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 filteredSystem = systemServices.filter(s => {
const term = searchTerm.toLowerCase();
const matchesSearch = s.name.toLowerCase().includes(term) ||
(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 handleSearchFocus = () => {
fetchSystemServices();
};
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 Manager</h2>
<p style={{ color: 'var(--text-muted)', marginTop: '0.5rem' }}>Visualisez et analysez vos logs en temps réel avec l'IA.</p>
<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} />
@@ -45,65 +114,144 @@ export default function HomeView() {
</button>
</section>
{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>
)}
<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>
</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>
{/* 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>
<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>
))}
{/* 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}`)}
>
<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>
)}
</div>
</section>
)}
{!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>
)}
<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>
</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>
</>
)}
{isModalOpen && (
<AddServiceModal
onClose={() => setIsModalOpen(false)}
onAdded={() => { setIsModalOpen(false); fetchServices(); }}
<AddServiceModal
onClose={() => setIsModalOpen(false)}
onAdded={() => { setIsModalOpen(false); fetchServices(); }}
/>
)}
</div>
+171 -13
View File
@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { ArrowLeft, Server, HardDrive, Trash2 } from 'lucide-react';
import { useNavigate, useParams, useLocation } from 'react-router-dom';
import { ArrowLeft, Server, HardDrive, Trash2, Save, Check, Pencil } from 'lucide-react';
import type { LogService } from '../types';
import LogTerminal from '../components/LogTerminal';
@@ -28,18 +28,63 @@ function DeleteWithConfirmation({ onDelete, serviceName }: { onDelete: () => voi
export default function ServiceView() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [service, setService] = useState<LogService | null>(null);
const location = useLocation();
const [service, setService] = useState<LogService | null>(location.state?.service || null);
const [initialLogs, setInitialLogs] = useState<{ id: string, line: string, isError: boolean }[]>([]);
const [loading, setLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [isSaved, setIsSaved] = useState(false);
const [isEditingName, setIsEditingName] = useState(false);
const [tempName, setTempName] = useState('');
const isTransitioningRef = useState(false); // Pour bloquer les redirects pendant la sauvegarde
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;
}
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';
const target = params.get('target') || '';
const name = params.get('name') || 'Service Éphémère';
if (!target) {
navigate('/');
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'
});
const logs = await logsRes.json();
setService({
id: `ephemeral-${target}` as any, // On triche avec le type pour le passer au terminal
name,
type: type as any,
pathOrContainerId: target,
createdAt: new Date().toISOString()
});
setInitialLogs(logs);
setLoading(false);
return;
}
// Mode Classique (Base de données)
const [svcRes, logsRes] = await Promise.all([
fetch(`${import.meta.env.VITE_API_URL || 'http://localhost:3001'}/api/services`, {
fetch(`${apiUrl}/api/services`, {
credentials: 'include'
}),
fetch(`${import.meta.env.VITE_API_URL || 'http://localhost:3001'}/api/services/${id}/logs`, {
fetch(`${apiUrl}/api/services/${id}/logs`, {
credentials: 'include'
})
]);
@@ -53,7 +98,7 @@ export default function ServiceView() {
setService(found);
setInitialLogs(logs);
updateRecentHistory(Number(id));
} else {
} else if (!isTransitioningRef[0]) { // Ne pas rediriger si on est en train de sauvegarder
navigate('/');
}
} catch (e) {
@@ -64,7 +109,20 @@ export default function ServiceView() {
};
fetchServiceAndLogs();
}, [id]);
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) {
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3001';
fetch(`${apiUrl}/api/logs/ephemeral?target=${target}`, {
method: 'DELETE',
credentials: 'include'
}).catch(err => console.error('Erreur cleanup éphémère:', err));
}
};
}, [id, window.location.search]);
const updateRecentHistory = (id: number) => {
const recents: number[] = JSON.parse(localStorage.getItem('recentServiceIds') || '[]');
@@ -74,6 +132,70 @@ export default function ServiceView() {
localStorage.setItem('recentServiceIds', JSON.stringify(updated));
};
const handleSaveName = async () => {
if (!service || !tempName.trim() || tempName === service.name) {
setIsEditingName(false);
return;
}
try {
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3001';
// 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',
headers: { 'Content-Type': 'application/json' },
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);
} else {
// En mode éphémère, on met juste à jour l'état local
setService({ ...service, name: tempName.trim() });
}
setIsEditingName(false);
} catch (err) {
console.error(err);
setIsEditingName(false);
}
};
const handleSave = async () => {
if (!service || isSaving) return;
setIsSaving(true);
try {
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3001';
const res = await fetch(`${apiUrl}/api/services`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: service.name,
type: service.type,
pathOrContainerId: service.pathOrContainerId,
alertKeyword: service.alertKeyword
}),
credentials: 'include'
});
const savedService = await res.json();
setIsSaved(true);
// 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 }
});
}, 1000);
} catch (err) {
console.error(err);
setIsSaving(false);
}
};
const handleDelete = async () => {
try {
await fetch(`${import.meta.env.VITE_API_URL || 'http://localhost:3001'}/api/services/${id}`, {
@@ -102,17 +224,53 @@ export default function ServiceView() {
<div className="service-icon-wrapper">
{service.type === 'docker' ? <Server size={24} /> : <HardDrive size={24} />}
</div>
<div>
<h3 className="service-title">{service.name}</h3>
<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>
</div>
<div className="service-actions">
<DeleteWithConfirmation
onDelete={handleDelete}
serviceName={service.name}
/>
{/* 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}
/>
)}
{/* 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>
</>
)}
</div>
</div>