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

+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 }