Initial commit: Sencho V1 complete with Auth and Dockerization

This commit is contained in:
unknown
2026-02-20 18:39:32 -05:00
commit 293f9cef26
51 changed files with 11547 additions and 0 deletions
+176
View File
@@ -0,0 +1,176 @@
import { useEffect, useRef, useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from './ui/dialog';
import { Button } from './ui/button';
import { Terminal as TerminalIcon, X } from 'lucide-react';
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import '@xterm/xterm/css/xterm.css';
interface BashExecModalProps {
isOpen: boolean;
onClose: () => void;
containerId: string;
containerName: string;
}
export default function BashExecModal({ isOpen, onClose, containerId, containerName }: BashExecModalProps) {
const terminalRef = useRef<HTMLDivElement>(null);
const xtermRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const [isConnected, setIsConnected] = useState(false);
useEffect(() => {
if (isOpen && terminalRef.current && !xtermRef.current) {
// Initialize xterm.js
const term = new Terminal({
theme: {
background: '#1e1e1e',
foreground: '#d4d4d4',
cursor: '#ffffff',
cursorAccent: '#000000',
selectionBackground: 'rgba(255, 255, 255, 0.3)',
},
fontFamily: 'Consolas, "Courier New", monospace',
fontSize: 14,
cursorBlink: true,
});
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);
term.open(terminalRef.current);
setTimeout(() => {
fitAddon.fit();
}, 100);
xtermRef.current = term;
fitAddonRef.current = fitAddon;
// Connect to WebSocket for bash exec
const ws = new WebSocket('ws://localhost:3000');
wsRef.current = ws;
ws.onopen = () => {
ws.send(JSON.stringify({
action: 'execContainer',
containerId: containerId,
}));
setIsConnected(true);
};
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.type === 'output') {
term.write(data.data);
} else if (data.type === 'error') {
term.write(`\r\n\x1b[31mError: ${data.message}\x1b[0m\r\n`);
} else if (data.type === 'exit') {
term.write('\r\n\x1b[33mSession ended\x1b[0m\r\n');
setIsConnected(false);
}
} catch {
// Raw output
term.write(event.data);
}
};
ws.onerror = () => {
term.write('\r\n\x1b[31mConnection error\x1b[0m\r\n');
setIsConnected(false);
};
ws.onclose = () => {
setIsConnected(false);
};
// Handle user input
term.onData((data) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
action: 'input',
data: data,
}));
}
});
// Handle resize
const handleResize = () => {
if (fitAddonRef.current) {
fitAddonRef.current.fit();
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
action: 'resize',
cols: term.cols,
rows: term.rows,
}));
}
}
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}
return () => {
// Cleanup on close
if (!isOpen) {
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
if (xtermRef.current) {
xtermRef.current.dispose();
xtermRef.current = null;
}
if (fitAddonRef.current) {
fitAddonRef.current = null;
}
setIsConnected(false);
}
};
}, [isOpen, containerId]);
const handleClose = () => {
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
if (xtermRef.current) {
xtermRef.current.dispose();
xtermRef.current = null;
}
setIsConnected(false);
onClose();
};
return (
<Dialog open={isOpen} onOpenChange={handleClose}>
<DialogContent className="max-w-4xl h-[600px] flex flex-col">
<DialogHeader className="flex flex-row items-center justify-between">
<DialogTitle className="flex items-center gap-2">
<TerminalIcon className="w-5 h-5" />
Bash: {containerName}
{isConnected && (
<span className="ml-2 text-xs bg-green-500/20 text-green-500 px-2 py-0.5 rounded-full">
Connected
</span>
)}
</DialogTitle>
<Button variant="ghost" size="sm" onClick={handleClose}>
<X className="w-4 h-4" />
</Button>
</DialogHeader>
<div
ref={terminalRef}
className="flex-1 rounded-lg overflow-hidden bg-[#1e1e1e] p-2"
style={{ minHeight: '500px' }}
/>
</DialogContent>
</Dialog>
);
}
+769
View File
@@ -0,0 +1,769 @@
import { useState, useEffect } from 'react';
import Editor from '@monaco-editor/react';
import TerminalComponent from './Terminal';
import ErrorBoundary from './ErrorBoundary';
import HomeDashboard from './HomeDashboard';
import BashExecModal from './BashExecModal';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription, DialogTrigger } from './ui/dialog';
import { Tabs, TabsList, TabsTrigger } from './ui/tabs';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Badge } from './ui/badge';
import { Plus, Trash2, Play, Square, Save, RefreshCw, Terminal, Sun, Moon, RotateCw, CloudDownload, Pencil, X, Search, Home, LogOut } from 'lucide-react';
import { useAuth } from '@/context/AuthContext';
import { apiFetch } from '@/lib/api';
interface ContainerInfo {
Id: string;
Names: string[];
State: string;
}
interface StackStatus {
[key: string]: 'running' | 'exited' | 'unknown';
}
export default function EditorLayout() {
const { logout } = useAuth();
const [files, setFiles] = useState<string[]>([]);
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [content, setContent] = useState<string>('');
const [originalContent, setOriginalContent] = useState<string>('');
const [envContent, setEnvContent] = useState<string>('');
const [originalEnvContent, setOriginalEnvContent] = useState<string>('');
const [envExists, setEnvExists] = useState<boolean>(false);
const [containers, setContainers] = useState<ContainerInfo[]>([]);
const [containerStats, setContainerStats] = useState<Record<string, {cpu: string, ram: string}>>({});
const [activeTab, setActiveTab] = useState<'compose' | 'env'>('compose');
const [createDialogOpen, setCreateDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [newStackName, setNewStackName] = useState('');
const [stackToDelete, setStackToDelete] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [isDarkMode, setIsDarkMode] = useState(true);
const [showConsole, setShowConsole] = useState(true);
const [isEditing, setIsEditing] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [stackStatuses, setStackStatuses] = useState<StackStatus>({});
// Bash exec modal state
const [bashModalOpen, setBashModalOpen] = useState(false);
const [selectedContainer, setSelectedContainer] = useState<{ id: string; name: string } | null>(null);
// Theme toggle effect
useEffect(() => {
const html = document.documentElement;
if (isDarkMode) {
html.classList.add('dark');
} else {
html.classList.remove('dark');
}
}, [isDarkMode]);
const refreshStacks = async () => {
setIsLoading(true);
try {
const res = await apiFetch('/stacks');
const stacks = await res.json();
setFiles(Array.isArray(stacks) ? stacks : []);
// Fetch status for each stack
const statuses: StackStatus = {};
for (const file of stacks) {
try {
const containersRes = await apiFetch(`/stacks/${file}/containers`);
const containers = await containersRes.json();
const hasRunning = Array.isArray(containers) && containers.some((c: ContainerInfo) => c.State === 'running');
statuses[file] = hasRunning ? 'running' : (Array.isArray(containers) && containers.length > 0 ? 'exited' : 'unknown');
} catch {
statuses[file] = 'unknown';
}
}
setStackStatuses(statuses);
} catch (error) {
console.error('Failed to refresh stacks:', error);
setFiles([]);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
refreshStacks();
}, []);
useEffect(() => {
const wsMap: Record<string, WebSocket> = {};
(containers || []).forEach(container => {
if (!container?.Id) return;
try {
const ws = new WebSocket('ws://localhost:3000');
wsMap[container.Id] = ws;
ws.onopen = () => ws.send(JSON.stringify({ action: 'streamStats', containerId: container.Id }));
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.cpu_stats && data.precpu_stats && data.memory_stats) {
const cpuDelta = data.cpu_stats.cpu_usage.total_usage - data.precpu_stats.cpu_usage.total_usage;
const systemDelta = data.cpu_stats.system_cpu_usage - data.precpu_stats.system_cpu_usage;
const cpuPercent = systemDelta > 0 ? ((cpuDelta / systemDelta) * data.cpu_stats.online_cpus * 100).toFixed(2) : '0.00';
const ramUsage = (data.memory_stats.usage / (1024 * 1024)).toFixed(2) + ' MB';
setContainerStats(prev => ({ ...prev, [container.Id]: { cpu: cpuPercent + '%', ram: ramUsage } }));
}
} catch {
// Ignore parse errors
}
};
} catch {
// Ignore WebSocket errors
}
});
return () => {
Object.values(wsMap).forEach(ws => {
try {
ws.close();
} catch {
// Ignore close errors
}
});
};
}, [containers]);
const loadFile = async (filename: string) => {
if (!filename) return;
setIsFileLoading(true);
setIsEditing(false); // Reset to view mode when loading a new file
try {
const res = await apiFetch(`/stacks/${filename}`);
const text = await res.text();
setSelectedFile(filename);
setContent(text || '');
setOriginalContent(text || '');
// Load env file
try {
const envRes = await apiFetch(`/stacks/${filename}/env`);
if (envRes.ok) {
const envText = await envRes.text();
setEnvContent(envText || '');
setOriginalEnvContent(envText || '');
setEnvExists(true);
} else {
setEnvContent('');
setOriginalEnvContent('');
setEnvExists(false);
}
} catch {
setEnvContent('');
setOriginalEnvContent('');
setEnvExists(false);
}
// Load containers
try {
const containersRes = await apiFetch(`/stacks/${filename}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
} catch (error) {
console.error('Failed to load containers:', error);
setContainers([]);
}
} catch (error) {
console.error('Failed to load file:', error);
setSelectedFile(null);
setContent('');
setOriginalContent('');
setEnvContent('');
setOriginalEnvContent('');
setContainers([]);
} finally {
setIsFileLoading(false);
}
};
const saveFile = async () => {
if (!selectedFile) return;
const currentContent = activeTab === 'compose' ? (content || '') : (envContent || '');
const endpoint = activeTab === 'compose' ? `/stacks/${selectedFile}` : `/stacks/${selectedFile}/env`;
try {
const response = await apiFetch(endpoint, {
method: 'PUT',
body: JSON.stringify({ content: currentContent }),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
// Update original content after save
if (activeTab === 'compose') {
setOriginalContent(content);
} else {
setOriginalEnvContent(envContent);
}
setIsEditing(false);
alert('File saved successfully!');
} catch (error) {
console.error('Failed to save file:', error);
alert(`Failed to save file: ${(error as Error).message}`);
}
};
const discardChanges = () => {
if (activeTab === 'compose') {
setContent(originalContent);
} else {
setEnvContent(originalEnvContent);
}
setIsEditing(false);
};
const enterEditMode = () => {
setIsEditing(true);
};
const deployStack = async () => {
if (!selectedFile) return;
try {
await apiFetch(`/stacks/${selectedFile}/up`, {
method: 'POST',
});
// Refresh containers after deploy
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to deploy:', error);
}
};
const stopStack = async () => {
if (!selectedFile) return;
try {
await apiFetch(`/stacks/${selectedFile}/down`, {
method: 'POST',
});
// Refresh containers after stop
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to stop:', error);
}
};
const restartStack = async () => {
if (!selectedFile) return;
try {
await apiFetch(`/stacks/${selectedFile}/down`, {
method: 'POST',
});
await apiFetch(`/stacks/${selectedFile}/up`, {
method: 'POST',
});
// Refresh containers after restart
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to restart:', error);
}
};
const updateStack = async () => {
if (!selectedFile) return;
try {
await apiFetch(`/stacks/${selectedFile}/update`, {
method: 'POST',
});
// Refresh containers after update
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to update:', error);
}
};
const deleteStack = async () => {
if (!stackToDelete) return;
try {
const response = await apiFetch(`/stacks/${stackToDelete}`, {
method: 'DELETE',
});
if (!response.ok) throw new Error('Failed to delete stack');
setDeleteDialogOpen(false);
setStackToDelete(null);
if (selectedFile === stackToDelete) {
setSelectedFile(null);
setContent('');
setOriginalContent('');
setEnvContent('');
setOriginalEnvContent('');
setEnvExists(false);
setContainers([]);
setIsEditing(false);
}
await refreshStacks();
} catch (error) {
console.error('Failed to delete stack:', error);
alert('Failed to delete stack');
}
};
const startContainer = async (id: string) => {
if (!id || !selectedFile) return;
try {
await apiFetch(`/containers/${id}/start`, { method: 'POST' });
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to start container:', error);
}
};
const stopContainer = async (id: string) => {
if (!id || !selectedFile) return;
try {
await apiFetch(`/containers/${id}/stop`, { method: 'POST' });
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to stop container:', error);
}
};
const restartContainer = async (id: string) => {
if (!id || !selectedFile) return;
try {
await apiFetch(`/containers/${id}/restart`, { method: 'POST' });
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to restart container:', error);
}
};
const handleCreateStack = async () => {
if (!newStackName.trim()) return;
const filename = newStackName.endsWith('.yml') ? newStackName : newStackName + '.yml';
try {
const response = await apiFetch('/stacks', {
method: 'POST',
body: JSON.stringify({ filename }),
});
if (!response.ok) throw new Error('Failed to create stack');
setCreateDialogOpen(false);
setNewStackName('');
await refreshStacks();
} catch (error) {
console.error('Failed to create stack:', error);
alert('Failed to create stack');
}
};
const openBashModal = (containerId: string, containerName: string) => {
setSelectedContainer({ id: containerId, name: containerName });
setBashModalOpen(true);
};
const closeBashModal = () => {
setBashModalOpen(false);
setSelectedContainer(null);
};
// Safe container list with fallback
const safeContainers = containers || [];
// Safe content strings with fallback
const safeContent = content || '';
const safeEnvContent = envContent || '';
// Get stack name without extension
const stackName = selectedFile ? selectedFile.replace('.yml', '').replace('.yaml', '') : '';
// Filter files based on search query
const filteredFiles = files.filter(file => {
const nameWithoutExt = file.replace('.yml', '').replace('.yaml', '').toLowerCase();
return nameWithoutExt.includes(searchQuery.toLowerCase());
});
// Get display name for stack (without extension)
const getDisplayName = (filename: string) => {
return filename.replace('.yml', '').replace('.yaml', '');
};
return (
<div className="flex h-screen w-screen overflow-hidden bg-background text-foreground">
{/* Left Sidebar (Stacks) */}
<div className="w-64 border-r border-border bg-card flex flex-col">
{/* Branding Header */}
<div className="h-16 flex items-center justify-between px-4 border-b border-border">
<h1 className="text-2xl font-bold tracking-tight">Sencho</h1>
<Button
variant="ghost"
size="icon"
onClick={logout}
title="Logout"
className="text-muted-foreground hover:text-foreground"
>
<LogOut className="w-5 h-5" />
</Button>
</div>
{/* Create Stack Button */}
<div className="p-4">
<Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
<DialogTrigger asChild>
<Button className="w-full rounded-lg">
<Plus className="w-4 h-4 mr-2" />
Create Stack
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New Stack</DialogTitle>
</DialogHeader>
<div className="py-4">
<Input
placeholder="Stack name (e.g., myapp)"
value={newStackName}
onChange={(e) => setNewStackName(e.target.value)}
/>
</div>
<DialogFooter>
<Button onClick={handleCreateStack}>Create</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
{/* Search Input */}
<div className="px-4 pb-2">
<div className="relative">
<Search className="absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
placeholder="Search stacks..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-8 rounded-lg"
/>
</div>
</div>
{/* Stack List */}
<div className="flex flex-col gap-1 px-2 flex-1 overflow-y-auto">
<h3 className="text-sm font-semibold text-muted-foreground mb-2 px-2">STACKS</h3>
{isLoading ? (
<div className="text-muted-foreground px-2 py-4">Loading...</div>
) : (
(filteredFiles || []).map(file => (
<Button
key={file}
variant="ghost"
className={`justify-start rounded-lg ${selectedFile === file ? 'bg-accent text-accent-foreground' : ''}`}
onClick={() => loadFile(file)}
>
<span className="flex items-center gap-2">
<span
className={`w-2 h-2 rounded-full ${
stackStatuses[file] === 'running' ? 'bg-green-500' :
stackStatuses[file] === 'exited' ? 'bg-red-500' : 'bg-gray-400'
}`}
/>
{getDisplayName(file)}
</span>
</Button>
))
)}
</div>
</div>
{/* Main Content Area */}
<div className="flex-1 flex flex-col overflow-hidden">
{/* Top Header Bar */}
<div className="h-16 flex items-center justify-end px-6 border-b border-border gap-4">
{/* Home Button */}
<Button
variant="outline"
size="sm"
className="rounded-lg"
onClick={() => {
setSelectedFile(null);
setContent('');
setOriginalContent('');
setEnvContent('');
setOriginalEnvContent('');
setEnvExists(false);
setContainers([]);
setIsEditing(false);
}}
title="Go to Home Dashboard"
>
<Home className="w-4 h-4 mr-2" />
Home
</Button>
{/* Console Toggle */}
<Button
variant="outline"
size="sm"
className="rounded-lg"
onClick={() => setShowConsole(!showConsole)}
>
<Terminal className="w-4 h-4 mr-2" />
Console
</Button>
{/* Theme Toggle */}
<Button
variant="outline"
size="sm"
className="rounded-lg"
onClick={() => setIsDarkMode(!isDarkMode)}
>
{isDarkMode ? (
<>
<Sun className="w-4 h-4 mr-2" />
Light
</>
) : (
<>
<Moon className="w-4 h-4 mr-2" />
Dark
</>
)}
</Button>
</div>
{/* Main Workspace */}
<div className="flex-1 overflow-y-auto p-6">
{!isLoading && selectedFile ? (
<ErrorBoundary>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Left Column (Command Center & Terminal) */}
<div className="flex flex-col gap-6">
{/* Command Center Card */}
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="p-4 pb-2">
<div className="flex flex-col gap-3">
{/* Stack Name */}
<CardTitle className="text-2xl font-bold">{stackName}</CardTitle>
{/* Action Bar */}
<div className="flex items-center gap-2 flex-wrap">
<Button size="sm" className="rounded-lg" onClick={deployStack}>
<Play className="w-4 h-4 mr-2" />
Deploy
</Button>
<Button size="sm" variant="outline" className="rounded-lg" onClick={restartStack}>
<RotateCw className="w-4 h-4 mr-2" />
Restart
</Button>
<Button size="sm" variant="outline" className="rounded-lg" onClick={updateStack}>
<CloudDownload className="w-4 h-4 mr-2" />
Update
</Button>
<Button size="sm" variant="outline" className="rounded-lg" onClick={stopStack}>
<Square className="w-4 h-4 mr-2" />
Stop
</Button>
<Button
size="sm"
variant="destructive"
className="rounded-lg"
onClick={() => {
setStackToDelete(selectedFile);
setDeleteDialogOpen(true);
}}
>
<Trash2 className="w-4 h-4 mr-2" />
Delete
</Button>
</div>
</div>
</CardHeader>
<CardContent className="p-4 pt-2">
{/* Containers List */}
<div className="mt-4">
<h4 className="text-sm font-semibold text-muted-foreground mb-3">CONTAINERS</h4>
{safeContainers.length === 0 ? (
<div className="text-muted-foreground text-sm">No containers running for this stack.</div>
) : (
<div className="flex flex-col gap-3">
{safeContainers.map(container => (
<div key={container?.Id || Math.random()} className="flex items-center justify-between p-3 rounded-lg bg-muted/50">
<div className="flex flex-col gap-1">
<span className="font-medium text-sm">{container?.Names?.[0]?.replace('/', '') || 'Unknown'}</span>
<div className="flex items-center gap-2">
<Badge variant={container?.State === 'running' ? 'default' : 'destructive'} className="text-xs">
{container?.State || 'unknown'}
</Badge>
<span className="text-xs text-muted-foreground">
CPU: {containerStats[container?.Id]?.cpu || 'N/A'} | RAM: {containerStats[container?.Id]?.ram || 'N/A'}
</span>
</div>
</div>
<div className="flex gap-1">
<Button
size="sm"
variant="ghost"
className="rounded-lg h-8 w-8 p-0"
onClick={() => startContainer(container?.Id)}
title="Start"
>
<Play className="w-3 h-3" />
</Button>
<Button
size="sm"
variant="ghost"
className="rounded-lg h-8 w-8 p-0"
onClick={() => stopContainer(container?.Id)}
title="Stop"
>
<Square className="w-3 h-3" />
</Button>
<Button
size="sm"
variant="ghost"
className="rounded-lg h-8 w-8 p-0"
onClick={() => restartContainer(container?.Id)}
title="Restart"
>
<RefreshCw className="w-3 h-3" />
</Button>
<Button
size="sm"
variant="outline"
className="rounded-lg h-8 px-2"
onClick={() => openBashModal(container?.Id, container?.Names?.[0]?.replace('/', '') || 'container')}
disabled={container?.State !== 'running'}
title="Open Bash"
>
<Terminal className="w-3 h-3 mr-1" />
Bash
</Button>
</div>
</div>
))}
</div>
)}
</div>
</CardContent>
</Card>
{/* Terminal Section */}
{showConsole && (
<div className="rounded-xl overflow-hidden border border-muted bg-black p-3 h-[400px]">
<h3 className="text-sm font-semibold text-muted-foreground mb-2">Terminal</h3>
<div className="h-[calc(100%-24px)]">
<ErrorBoundary>
<TerminalComponent />
</ErrorBoundary>
</div>
</div>
)}
</div>
{/* Right Column (The Editor) */}
<Card className="rounded-xl border-muted overflow-hidden flex flex-col h-[700px] bg-card">
<div className="p-4 border-b border-muted flex items-center justify-between">
<Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'compose' | 'env')}>
<TabsList className="bg-muted">
<TabsTrigger value="compose" className="rounded-lg">compose.yaml</TabsTrigger>
<TabsTrigger value="env" disabled={!envExists} className="rounded-lg">.env</TabsTrigger>
</TabsList>
</Tabs>
<div className="flex gap-2">
{!isEditing ? (
<Button size="sm" variant="default" className="rounded-lg" onClick={enterEditMode}>
<Pencil className="w-4 h-4 mr-2" />
Edit
</Button>
) : (
<>
<Button size="sm" variant="outline" className="rounded-lg" onClick={discardChanges}>
<X className="w-4 h-4 mr-2" />
Discard
</Button>
<Button size="sm" variant="default" className="rounded-lg" onClick={saveFile}>
<Save className="w-4 h-4 mr-2" />
Save
</Button>
</>
)}
</div>
</div>
<div className="flex-1 min-h-0">
{!isFileLoading && (
<Editor
height="100%"
language={activeTab === 'compose' ? 'yaml' : 'plaintext'}
theme={isDarkMode ? 'vs-dark' : 'vs'}
value={activeTab === 'compose' ? safeContent : safeEnvContent}
onChange={(value) => {
if (!isEditing) return; // Prevent changes in view mode
if (activeTab === 'compose') {
setContent(value || '');
} else {
setEnvContent(value || '');
}
}}
options={{
minimap: { enabled: false },
fontSize: 14,
padding: { top: 10 },
scrollBeyondLastLine: false,
readOnly: !isEditing,
}}
/>
)}
{isFileLoading && (
<div className="flex items-center justify-center h-full text-muted-foreground">
Loading...
</div>
)}
</div>
</Card>
</div>
</ErrorBoundary>
) : (
<HomeDashboard />
)}
</div>
</div>
{/* Delete Confirmation Dialog */}
<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Delete Stack</DialogTitle>
<DialogDescription>
Are you sure you want to delete {stackToDelete}? This action cannot be undone.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>Cancel</Button>
<Button variant="destructive" onClick={deleteStack}>Delete</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Bash Exec Modal */}
{selectedContainer && (
<BashExecModal
isOpen={bashModalOpen}
onClose={closeBashModal}
containerId={selectedContainer.id}
containerName={selectedContainer.name}
/>
)}
</div>
);
}
+47
View File
@@ -0,0 +1,47 @@
import React, { Component } from 'react';
import type { ErrorInfo, ReactNode } from 'react';
interface Props {
children: ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
}
class ErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false,
error: null,
};
public static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('ErrorBoundary caught an error:', error, errorInfo);
}
public render() {
if (this.state.hasError) {
return (
<div className="p-6 bg-red-900/20 border border-red-500 rounded-xl m-4">
<h2 className="text-lg font-bold text-red-500 mb-2">Something went wrong</h2>
<p className="text-red-300 text-sm mb-4">{this.state.error?.message || 'Unknown error'}</p>
<button
className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600"
onClick={() => this.setState({ hasError: false, error: null })}
>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
+289
View File
@@ -0,0 +1,289 @@
import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from './ui/dialog';
import { Activity, Square, PauseCircle, ArrowRight, Plus, Cpu, HardDrive, MemoryStick } from 'lucide-react';
import { apiFetch } from '@/lib/api';
interface Stats {
active: number;
exited: number;
total: number;
inactive: number;
}
interface SystemStats {
cpu: {
usage: string;
cores: number;
};
memory: {
total: number;
used: number;
free: number;
usagePercent: string;
};
disk: {
fs: string;
mount: string;
total: number;
used: number;
free: number;
usagePercent: string;
} | null;
}
function formatBytes(bytes: number): string {
const gb = bytes / (1024 * 1024 * 1024);
if (gb >= 1024) {
return (gb / 1024).toFixed(1) + ' TB';
}
return gb.toFixed(1) + ' GB';
}
export default function HomeDashboard() {
const [dockerRunInput, setDockerRunInput] = useState('');
const [isConverting, setIsConverting] = useState(false);
const [convertedYaml, setConvertedYaml] = useState('');
const [createDialogOpen, setCreateDialogOpen] = useState(false);
const [newStackName, setNewStackName] = useState('');
const [stats, setStats] = useState<Stats>({ active: 0, exited: 0, total: 0, inactive: 0 });
const [systemStats, setSystemStats] = useState<SystemStats | null>(null);
// Fetch stats from backend
useEffect(() => {
const fetchStats = async () => {
try {
const res = await apiFetch('/stats');
const data = await res.json();
setStats(data);
} catch (error) {
console.error('Failed to fetch stats:', error);
}
};
fetchStats();
const interval = setInterval(fetchStats, 5000);
return () => clearInterval(interval);
}, []);
// Fetch system stats from backend
useEffect(() => {
const fetchSystemStats = async () => {
try {
const res = await apiFetch('/system/stats');
const data = await res.json();
setSystemStats(data);
} catch (error) {
console.error('Failed to fetch system stats:', error);
}
};
fetchSystemStats();
const interval = setInterval(fetchSystemStats, 5000);
return () => clearInterval(interval);
}, []);
const handleConvert = async () => {
if (!dockerRunInput.trim()) return;
setIsConverting(true);
try {
const response = await apiFetch('/convert', {
method: 'POST',
body: JSON.stringify({ dockerRun: dockerRunInput }),
});
if (!response.ok) throw new Error('Conversion failed');
const data = await response.json();
setConvertedYaml(data.yaml);
} catch (error) {
console.error('Conversion error:', error);
alert('Failed to convert docker run command');
} finally {
setIsConverting(false);
}
};
const handleCreateStack = async () => {
if (!newStackName.trim() || !convertedYaml) return;
const filename = newStackName.endsWith('.yml') ? newStackName : newStackName + '.yml';
try {
// Create the stack
const createResponse = await apiFetch('/stacks', {
method: 'POST',
body: JSON.stringify({ filename }),
});
if (!createResponse.ok) throw new Error('Failed to create stack');
// Save the converted YAML content
const saveResponse = await apiFetch(`/stacks/${filename}`, {
method: 'PUT',
body: JSON.stringify({ content: convertedYaml }),
});
if (!saveResponse.ok) throw new Error('Failed to save stack content');
setCreateDialogOpen(false);
setNewStackName('');
setConvertedYaml('');
setDockerRunInput('');
window.location.reload(); // Refresh to show new stack
} catch (error) {
console.error('Failed to create stack:', error);
alert('Failed to create stack');
}
};
const handleUseConvertedYaml = () => {
setCreateDialogOpen(true);
};
return (
<div className="flex-1 p-6 space-y-6">
{/* Container Stats Row */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Active Containers</CardTitle>
<Activity className="h-4 w-4 text-green-500" />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-green-500">{stats.active}</div>
<p className="text-xs text-muted-foreground mt-1">Currently running</p>
</CardContent>
</Card>
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Exited Containers</CardTitle>
<Square className="h-4 w-4 text-red-500" />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-red-500">{stats.exited}</div>
<p className="text-xs text-muted-foreground mt-1">Stopped or crashed</p>
</CardContent>
</Card>
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Inactive Stacks</CardTitle>
<PauseCircle className="h-4 w-4 text-yellow-500" />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-yellow-500">{Math.max(0, stats.inactive)}</div>
<p className="text-xs text-muted-foreground mt-1">Not deployed</p>
</CardContent>
</Card>
</div>
{/* Host System Stats Row */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Host CPU</CardTitle>
<Cpu className="h-4 w-4 text-blue-500" />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-blue-500">
{systemStats ? `${systemStats.cpu.usage}%` : '...'}
</div>
<p className="text-xs text-muted-foreground mt-1">
{systemStats ? `${systemStats.cpu.cores} cores` : 'Loading...'}
</p>
</CardContent>
</Card>
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Host RAM</CardTitle>
<MemoryStick className="h-4 w-4 text-purple-500" />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-purple-500">
{systemStats ? `${systemStats.memory.usagePercent}%` : '...'}
</div>
<p className="text-xs text-muted-foreground mt-1">
{systemStats
? `${formatBytes(systemStats.memory.used)} / ${formatBytes(systemStats.memory.total)}`
: 'Loading...'}
</p>
</CardContent>
</Card>
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Host Disk</CardTitle>
<HardDrive className="h-4 w-4 text-orange-500" />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-orange-500">
{systemStats?.disk ? `${systemStats.disk.usagePercent}%` : '...'}
</div>
<p className="text-xs text-muted-foreground mt-1">
{systemStats?.disk
? `${formatBytes(systemStats.disk.used)} / ${formatBytes(systemStats.disk.total)}`
: 'Loading...'}
</p>
</CardContent>
</Card>
</div>
{/* Docker Run Converter */}
<Card className="rounded-xl border-muted bg-card">
<CardHeader>
<CardTitle className="text-lg">Convert Docker Run to Compose</CardTitle>
<p className="text-sm text-muted-foreground">
Paste your <code className="bg-muted px-1 rounded">docker run</code> command below to convert it to a Docker Compose YAML file.
</p>
</CardHeader>
<CardContent className="space-y-4">
<textarea
className="w-full h-32 p-3 rounded-lg border border-muted bg-background text-foreground font-mono text-sm resize-none focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="docker run -d --name my-app -p 8080:80 -e TZ=UTC nginx:latest"
value={dockerRunInput}
onChange={(e) => setDockerRunInput(e.target.value)}
/>
<div className="flex gap-2">
<Button onClick={handleConvert} disabled={isConverting || !dockerRunInput.trim()}>
{isConverting ? 'Converting...' : 'Convert'}
<ArrowRight className="w-4 h-4 ml-2" />
</Button>
</div>
{convertedYaml && (
<div className="space-y-3">
<div className="p-3 rounded-lg bg-muted/50 font-mono text-sm whitespace-pre-wrap overflow-auto max-h-64">
{convertedYaml}
</div>
<Button onClick={handleUseConvertedYaml}>
<Plus className="w-4 h-4 mr-2" />
Create Stack from YAML
</Button>
</div>
)}
</CardContent>
</Card>
{/* Create Stack Dialog */}
<Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New Stack</DialogTitle>
</DialogHeader>
<div className="py-4 space-y-4">
<Input
placeholder="Stack name (e.g., myapp)"
value={newStackName}
onChange={(e) => setNewStackName(e.target.value)}
/>
<div className="p-3 rounded-lg bg-muted/50 font-mono text-sm whitespace-pre-wrap overflow-auto max-h-48">
{convertedYaml}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setCreateDialogOpen(false)}>Cancel</Button>
<Button onClick={handleCreateStack} disabled={!newStackName.trim()}>Create Stack</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
import { useState } from 'react';
import { useAuth } from '@/context/AuthContext';
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
export function Login({
className,
...props
}: React.ComponentPropsWithoutRef<"div">) {
const { login } = useAuth();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setIsLoading(true);
const result = await login(username, password);
if (!result.success) {
setError(result.error || 'Login failed');
}
setIsLoading(false);
};
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card>
<CardHeader>
<CardTitle className="text-2xl">Sencho</CardTitle>
<CardDescription>
Enter your credentials to access the dashboard
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit}>
<div className="flex flex-col gap-6">
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<Input
id="username"
type="text"
placeholder="admin"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
{error && (
<div className="text-sm text-red-500 text-center">
{error}
</div>
)}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? 'Logging in...' : 'Login'}
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
);
}
+132
View File
@@ -0,0 +1,132 @@
import { useState } from 'react';
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
interface SetupProps {
onComplete: () => void;
}
export function Setup({
onComplete,
className,
...props
}: SetupProps & React.ComponentPropsWithoutRef<"div">) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [error, setError] = useState('');
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
// Client-side validation
if (password !== confirmPassword) {
setError('Passwords do not match');
return;
}
if (username.length < 3) {
setError('Username must be at least 3 characters');
return;
}
if (password.length < 6) {
setError('Password must be at least 6 characters');
return;
}
setIsLoading(true);
try {
const response = await fetch('/api/auth/setup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({ username, password, confirmPassword }),
});
const data = await response.json();
if (response.ok && data.success) {
onComplete();
} else {
setError(data.error || 'Setup failed');
}
} catch {
setError('Network error. Please try again.');
} finally {
setIsLoading(false);
}
};
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card>
<CardHeader>
<CardTitle className="text-2xl">Welcome to Sencho</CardTitle>
<CardDescription>
Create your admin account to get started
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit}>
<div className="flex flex-col gap-6">
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<Input
id="username"
type="text"
placeholder="admin"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="confirmPassword">Confirm Password</Label>
<Input
id="confirmPassword"
type="password"
required
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
/>
</div>
{error && (
<div className="text-sm text-red-500 text-center">
{error}
</div>
)}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? 'Setting up...' : 'Complete Setup'}
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
);
}
+136
View File
@@ -0,0 +1,136 @@
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import { useEffect, useRef } from 'react';
import '@xterm/xterm/css/xterm.css';
export default function TerminalComponent() {
const terminalRef = useRef<HTMLDivElement>(null);
const terminalInstance = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const wsRef = useRef<WebSocket | null>(null);
useEffect(() => {
if (!terminalRef.current) {
console.error('Terminal ref not ready');
return;
}
// Clean up any existing terminal
if (terminalInstance.current) {
try {
terminalInstance.current.dispose();
} catch {
// Ignore dispose errors
}
}
if (wsRef.current) {
try {
wsRef.current.close();
} catch {
// Ignore close errors
}
}
let mounted = true;
const initTerminal = () => {
if (!mounted || !terminalRef.current) return;
try {
const term = new Terminal({
cursorBlink: true,
convertEol: true,
theme: {
background: '#000000',
foreground: '#ffffff',
cursor: '#ffffff',
},
fontFamily: 'Consolas, Monaco, monospace',
fontSize: 13,
});
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);
fitAddonRef.current = fitAddon;
term.open(terminalRef.current);
terminalInstance.current = term;
// Fit after DOM paint using requestAnimationFrame
requestAnimationFrame(() => {
if (!mounted || !fitAddonRef.current || !terminalRef.current) return;
try {
fitAddonRef.current.fit();
} catch (err) {
console.error('Error fitting terminal:', err);
}
});
const ws = new WebSocket('ws://localhost:3000');
wsRef.current = ws;
ws.onopen = () => {
if (mounted) {
ws.send(JSON.stringify({ action: 'connectTerminal' }));
}
};
ws.onmessage = (event) => {
if (mounted && terminalInstance.current) {
terminalInstance.current.write(event.data);
}
};
ws.onerror = (err) => {
console.error('WebSocket error:', err);
};
} catch (err) {
console.error('Error initializing terminal:', err);
}
};
// Initialize terminal after a small delay to ensure container is rendered
const timeoutId = setTimeout(initTerminal, 50);
// Attach ResizeObserver to the terminal's parent container
const resizeObserver = new ResizeObserver(() => {
if (fitAddonRef.current && terminalRef.current && mounted) {
try {
fitAddonRef.current.fit();
} catch {
// Ignore fit errors during resize
}
}
});
if (terminalRef.current.parentElement) {
resizeObserver.observe(terminalRef.current.parentElement);
}
return () => {
mounted = false;
clearTimeout(timeoutId);
resizeObserver.disconnect();
if (wsRef.current) {
try {
wsRef.current.close();
} catch {
// Ignore close errors
}
wsRef.current = null;
}
if (terminalInstance.current) {
try {
terminalInstance.current.dispose();
} catch {
// Ignore dispose errors
}
terminalInstance.current = null;
}
fitAddonRef.current = null;
};
}, []);
return <div ref={terminalRef} className="h-full w-full" />;
}
+68
View File
@@ -0,0 +1,68 @@
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
export function LoginForm({
className,
...props
}: React.ComponentPropsWithoutRef<"div">) {
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card>
<CardHeader>
<CardTitle className="text-2xl">Login</CardTitle>
<CardDescription>
Enter your email below to login to your account
</CardDescription>
</CardHeader>
<CardContent>
<form>
<div className="flex flex-col gap-6">
<div className="grid gap-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="m@example.com"
required
/>
</div>
<div className="grid gap-2">
<div className="flex items-center">
<Label htmlFor="password">Password</Label>
<a
href="#"
className="ml-auto inline-block text-sm underline-offset-4 hover:underline"
>
Forgot your password?
</a>
</div>
<Input id="password" type="password" required />
</div>
<Button type="submit" className="w-full">
Login
</Button>
<Button variant="outline" className="w-full">
Login with Google
</Button>
</div>
<div className="mt-4 text-center text-sm">
Don&apos;t have an account?{" "}
<a href="#" className="underline underline-offset-4">
Sign up
</a>
</div>
</form>
</CardContent>
</Card>
</div>
)
}
+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 }
+57
View File
@@ -0,0 +1,57 @@
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 transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring 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 shadow hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
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 }
+76
View File
@@ -0,0 +1,76 @@
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-xl border bg-card text-card-foreground shadow",
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("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-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors 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-1 focus-visible:ring-ring 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 }
@@ -0,0 +1,48 @@
"use client"
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
export { ScrollArea, ScrollBar }
+55
View File
@@ -0,0 +1,55 @@
"use client"
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 }