mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-10-29 08:07:37 +09:00
refactor(frontend): Phase 4 §7.3 — split Docker.jsx monolith into per-tab files
Per docs/plans/FRONTEND_UX_TAILWIND_CLEANUP_PLAN.md §7.3. Pure refactor (move + imports only, no logic change). Docker.jsx goes from 2521 → 334 lines (a thin shell: status/server/stats/tab state + layout). Extracted to components/docker/: - dockerHelpers.js — ServerContext/useServer + the pure container helpers/constants - dockerShared.jsx — IconAction, TrashIcon, ContainerResourceBars, DownloadIcon - ContainersTab.jsx — ContainersTab + ContainerInspector + Run button/modal + logs/exec modals - ComposeTab.jsx, ImagesTab.jsx, NetworksTab.jsx, VolumesTab.jsx, PruneButton.jsx The tabs were already decoupled (shared ServerContext + onStatsChange prop, no closures over the shell), so the split is mechanical. Verified: npm run build passes, 0 lint errors, and drove ALL FIVE tabs (Containers/Compose/Images/Networks/Volumes) open under Playwright with mock data — each renders correctly (tables, status/port pills, resource bars, row actions, toolbar buttons) identical to pre-split. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
bf21504358
commit
019fdb2cfe
9 files changed
+2289
-2177
No files matched your search
@@ -0,0 +1,329 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/ToastContext';
|
||||
import { useConfirm } from '../../hooks/useConfirm';
|
||||
import EmptyState from '../EmptyState';
|
||||
import Modal from '@/components/Modal';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Package, Play, Square, RotateCw, FileText } from 'lucide-react';
|
||||
import {
|
||||
useServer,
|
||||
unwrapRemoteData,
|
||||
normalizeListResponse,
|
||||
} from './dockerHelpers';
|
||||
import { IconAction, DownloadIcon } from './dockerShared';
|
||||
|
||||
// Compose Tab
|
||||
const ComposeTab = ({ onStatsChange }) => {
|
||||
const toast = useToast();
|
||||
const { serverId, isRemote } = useServer();
|
||||
const { confirm: confirmCompose } = useConfirm();
|
||||
const [projects, setProjects] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [logsProject, setLogsProject] = useState(null);
|
||||
const [actionLoading, setActionLoading] = useState({});
|
||||
|
||||
useEffect(() => {
|
||||
loadProjects();
|
||||
}, [serverId]);
|
||||
|
||||
async function loadProjects() {
|
||||
setLoading(true);
|
||||
try {
|
||||
let data;
|
||||
if (isRemote) {
|
||||
data = await api.getRemoteComposeProjects(serverId);
|
||||
} else {
|
||||
data = await api.composeList();
|
||||
}
|
||||
setProjects(normalizeListResponse(data, 'projects'));
|
||||
} catch (err) {
|
||||
console.error('Failed to load compose projects:', err);
|
||||
setProjects([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAction(project, action) {
|
||||
const projectPath = project.ConfigFiles || project.config_files;
|
||||
if (!projectPath) {
|
||||
toast.error('Project path not found');
|
||||
return;
|
||||
}
|
||||
|
||||
setActionLoading(prev => ({ ...prev, [project.Name || project.name]: true }));
|
||||
|
||||
try {
|
||||
if (action === 'up') {
|
||||
if (isRemote) {
|
||||
await api.remoteComposeUp(serverId, projectPath);
|
||||
} else {
|
||||
await api.composeUp(projectPath, true, false);
|
||||
}
|
||||
toast.success('Project started');
|
||||
} else if (action === 'down') {
|
||||
const downConfirmed = await confirmCompose({ title: 'Stop Compose Project', message: 'Stop this compose project? Containers will be removed.' });
|
||||
if (!downConfirmed) {
|
||||
setActionLoading(prev => ({ ...prev, [project.Name || project.name]: false }));
|
||||
return;
|
||||
}
|
||||
if (isRemote) {
|
||||
await api.remoteComposeDown(serverId, projectPath);
|
||||
} else {
|
||||
await api.composeDown(projectPath, false, true);
|
||||
}
|
||||
toast.success('Project stopped');
|
||||
} else if (action === 'restart') {
|
||||
if (isRemote) {
|
||||
await api.remoteComposeRestart(serverId, projectPath);
|
||||
} else {
|
||||
await api.composeRestart(projectPath);
|
||||
}
|
||||
toast.success('Project restarted');
|
||||
} else if (action === 'pull') {
|
||||
if (isRemote) {
|
||||
await api.remoteComposePull(serverId, projectPath);
|
||||
} else {
|
||||
await api.composePull(projectPath);
|
||||
}
|
||||
toast.success('Images pulled');
|
||||
}
|
||||
loadProjects();
|
||||
onStatsChange?.();
|
||||
} catch (err) {
|
||||
console.error(`Failed to ${action} project:`, err);
|
||||
toast.error(err.message || `Failed to ${action} project`);
|
||||
} finally {
|
||||
setActionLoading(prev => ({ ...prev, [project.Name || project.name]: false }));
|
||||
}
|
||||
}
|
||||
|
||||
function getProjectStatus(project) {
|
||||
const status = project.Status || project.status || '';
|
||||
if (status.includes('running')) return 'running';
|
||||
if (status.includes('exited') || status.includes('stopped')) return 'exited';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function parseRunningCount(status) {
|
||||
// Parse status like "running(3)" or "exited(2), running(1)"
|
||||
const match = status.match(/running\((\d+)\)/);
|
||||
return match ? parseInt(match[1], 10) : 0;
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <div className="docker-loading">Loading compose projects...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="docker-table-header">
|
||||
<div className="docker-table-info">
|
||||
{projects.length} project{projects.length !== 1 ? 's' : ''} found
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={loadProjects}>
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{projects.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Package}
|
||||
title="No Compose projects"
|
||||
description="No Docker Compose projects are running on this server."
|
||||
action={<code>docker compose up -d</code>}
|
||||
/>
|
||||
) : (
|
||||
<table className="docker-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Project</th>
|
||||
<th>Status</th>
|
||||
<th>Config File</th>
|
||||
<th className="text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{projects.map(project => {
|
||||
const name = project.Name || project.name;
|
||||
const status = project.Status || project.status || 'unknown';
|
||||
const configFiles = project.ConfigFiles || project.config_files || '';
|
||||
const isRunning = getProjectStatus(project) === 'running';
|
||||
const runningCount = parseRunningCount(status);
|
||||
const isLoading = actionLoading[name];
|
||||
|
||||
return (
|
||||
<tr key={name}>
|
||||
<td>
|
||||
<span className="docker-container-name">{name}</span>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`docker-status-pill ${isRunning ? 'running' : 'exited'}`}>
|
||||
<span className="docker-status-dot" />
|
||||
{isRunning ? `Running (${runningCount})` : 'Stopped'}
|
||||
</span>
|
||||
<div className="docker-status-detail">{status}</div>
|
||||
</td>
|
||||
<td>
|
||||
<span className="docker-container-id truncate inline-block" style={{ maxWidth: '300px' }}>
|
||||
{configFiles}
|
||||
</span>
|
||||
</td>
|
||||
<td className="docker-actions-cell">
|
||||
<IconAction
|
||||
title="Logs"
|
||||
onClick={() => setLogsProject(project)}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<FileText size={14} />
|
||||
</IconAction>
|
||||
{isRunning ? (
|
||||
<>
|
||||
<IconAction
|
||||
title="Restart"
|
||||
onClick={() => handleAction(project, 'restart')}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<RotateCw size={14} />
|
||||
</IconAction>
|
||||
<IconAction
|
||||
title="Stop"
|
||||
onClick={() => handleAction(project, 'down')}
|
||||
disabled={isLoading}
|
||||
color="#EF4444"
|
||||
>
|
||||
<Square size={14} />
|
||||
</IconAction>
|
||||
</>
|
||||
) : (
|
||||
<IconAction
|
||||
title="Start"
|
||||
onClick={() => handleAction(project, 'up')}
|
||||
disabled={isLoading}
|
||||
color="#10B981"
|
||||
>
|
||||
<Play size={14} />
|
||||
</IconAction>
|
||||
)}
|
||||
<IconAction
|
||||
title="Pull Images"
|
||||
onClick={() => handleAction(project, 'pull')}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<DownloadIcon />
|
||||
</IconAction>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
|
||||
{logsProject && (
|
||||
<ComposeLogsModal
|
||||
project={logsProject}
|
||||
onClose={() => setLogsProject(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Compose Logs Modal
|
||||
const ComposeLogsModal = ({ project, onClose }) => {
|
||||
const { serverId, isRemote } = useServer();
|
||||
const [logs, setLogs] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [tail, setTail] = useState(200);
|
||||
const [selectedService, setSelectedService] = useState('');
|
||||
const [services, setServices] = useState([]);
|
||||
|
||||
const projectName = project.Name || project.name;
|
||||
const projectPath = project.ConfigFiles || project.config_files || '';
|
||||
|
||||
useEffect(() => {
|
||||
loadServices();
|
||||
loadLogs();
|
||||
}, [project, tail, selectedService]);
|
||||
|
||||
async function loadServices() {
|
||||
try {
|
||||
let containers;
|
||||
if (isRemote) {
|
||||
containers = normalizeListResponse(
|
||||
await api.getRemoteComposePs(serverId, projectPath),
|
||||
'containers'
|
||||
);
|
||||
} else {
|
||||
const result = await api.composePs(projectPath);
|
||||
containers = result.containers || result || [];
|
||||
}
|
||||
|
||||
// Extract unique service names
|
||||
const serviceNames = [...new Set(
|
||||
(Array.isArray(containers) ? containers : [])
|
||||
.map(c => c.Service || c.service)
|
||||
.filter(Boolean)
|
||||
)];
|
||||
setServices(serviceNames);
|
||||
} catch (err) {
|
||||
console.error('Failed to load services:', err);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadLogs() {
|
||||
setLoading(true);
|
||||
try {
|
||||
let data;
|
||||
if (isRemote) {
|
||||
data = unwrapRemoteData(await api.remoteComposeLogs(serverId, projectPath, selectedService || null, tail));
|
||||
} else {
|
||||
data = await api.composeLogs(projectPath, selectedService || null, tail);
|
||||
}
|
||||
setLogs(data.logs || 'No logs available');
|
||||
} catch (err) {
|
||||
setLogs('Failed to load logs: ' + (err.message || 'Unknown error'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open onClose={onClose} title={`Logs: ${projectName}`} size="lg">
|
||||
<div className="modal-body">
|
||||
<div className="logs-controls flex flex-wrap items-center gap-2 mb-2">
|
||||
<label>Service:</label>
|
||||
<select
|
||||
value={selectedService}
|
||||
onChange={(e) => setSelectedService(e.target.value)}
|
||||
className="py-2 px-2"
|
||||
>
|
||||
<option value="">All Services</option>
|
||||
{services.map(service => (
|
||||
<option key={service} value={service}>{service}</option>
|
||||
))}
|
||||
</select>
|
||||
<label>Lines:</label>
|
||||
<select value={tail} onChange={(e) => setTail(Number(e.target.value))} className="py-2 px-2">
|
||||
<option value={50}>50</option>
|
||||
<option value={100}>100</option>
|
||||
<option value={200}>200</option>
|
||||
<option value={500}>500</option>
|
||||
<option value={1000}>1000</option>
|
||||
</select>
|
||||
</div>
|
||||
<pre className="log-viewer">{loading ? 'Loading...' : logs}</pre>
|
||||
</div>
|
||||
<div className="modal-actions">
|
||||
<Button variant="outline" onClick={loadLogs} disabled={loading}>
|
||||
{loading ? 'Loading...' : 'Refresh'}
|
||||
</Button>
|
||||
<Button onClick={onClose}>Close</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default ComposeTab;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,216 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/ToastContext';
|
||||
import { useConfirm } from '../../hooks/useConfirm';
|
||||
import EmptyState from '../EmptyState';
|
||||
import Modal from '@/components/Modal';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Layers } from 'lucide-react';
|
||||
import {
|
||||
useServer,
|
||||
normalizeListResponse,
|
||||
} from './dockerHelpers';
|
||||
import { IconAction, TrashIcon } from './dockerShared';
|
||||
|
||||
export const PullImageButton = () => {
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<Button onClick={() => setShowModal(true)}>
|
||||
<span>+</span> Pull Image
|
||||
</Button>
|
||||
{showModal && <PullImageModal onClose={() => setShowModal(false)} onPulled={() => window.location.reload()} />}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Images Tab
|
||||
const ImagesTab = ({ onStatsChange }) => {
|
||||
const toast = useToast();
|
||||
const { serverId, isRemote } = useServer();
|
||||
const { confirm: confirmImage } = useConfirm();
|
||||
const [images, setImages] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
loadImages();
|
||||
}, [serverId]);
|
||||
|
||||
async function loadImages() {
|
||||
setLoading(true);
|
||||
try {
|
||||
let data;
|
||||
if (isRemote) {
|
||||
const result = await api.getRemoteImages(serverId);
|
||||
data = { images: normalizeListResponse(result, 'images') };
|
||||
} else {
|
||||
data = await api.getImages();
|
||||
}
|
||||
setImages(data.images || []);
|
||||
} catch (err) {
|
||||
console.error('Failed to load images:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemove(imageId) {
|
||||
const confirmed = await confirmImage({ title: 'Remove Image', message: 'Remove this image?' });
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
if (isRemote) {
|
||||
await api.removeRemoteImage(serverId, imageId, true);
|
||||
} else {
|
||||
await api.removeImage(imageId, true);
|
||||
}
|
||||
toast.success('Image removed successfully');
|
||||
loadImages();
|
||||
onStatsChange?.();
|
||||
} catch (err) {
|
||||
console.error('Failed to remove image:', err);
|
||||
toast.error('Failed to remove image. It may be in use by a container.');
|
||||
}
|
||||
}
|
||||
|
||||
const filteredImages = images.filter(img => {
|
||||
if (!searchTerm) return true;
|
||||
const search = searchTerm.toLowerCase();
|
||||
return img.repository?.toLowerCase().includes(search) ||
|
||||
img.tag?.toLowerCase().includes(search) ||
|
||||
img.id?.toLowerCase().includes(search);
|
||||
});
|
||||
|
||||
if (loading) {
|
||||
return <div className="docker-loading">Loading images...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="docker-table-header">
|
||||
<div />
|
||||
<Input
|
||||
type="text"
|
||||
className="docker-search"
|
||||
placeholder="Search images..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{filteredImages.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Layers}
|
||||
title="No images"
|
||||
description="Pull an image to see it here."
|
||||
/>
|
||||
) : (
|
||||
<table className="docker-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Repository</th>
|
||||
<th>Tag</th>
|
||||
<th>Image ID</th>
|
||||
<th>Size</th>
|
||||
<th>Created</th>
|
||||
<th className="text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filteredImages.map(image => (
|
||||
<tr key={image.id}>
|
||||
<td>
|
||||
<span className="docker-container-name">{image.repository || '<none>'}</span>
|
||||
</td>
|
||||
<td>
|
||||
<span className="docker-image-tag">{image.tag || '<none>'}</span>
|
||||
</td>
|
||||
<td>
|
||||
<span className="docker-container-id">{image.id?.substring(0, 12)}</span>
|
||||
</td>
|
||||
<td>{image.size}</td>
|
||||
<td>{image.created}</td>
|
||||
<td className="docker-actions-cell">
|
||||
<IconAction title="Delete" onClick={() => handleRemove(image.id)} color="#EF4444">
|
||||
<TrashIcon />
|
||||
</IconAction>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const PullImageModal = ({ onClose, onPulled }) => {
|
||||
const { serverId, isRemote } = useServer();
|
||||
const [image, setImage] = useState('');
|
||||
const [tag, setTag] = useState('latest');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function handleSubmit(e) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
if (isRemote) {
|
||||
const fullImage = tag ? `${image}:${tag}` : image;
|
||||
await api.pullRemoteImage(serverId, fullImage);
|
||||
} else {
|
||||
await api.pullImage(image, tag);
|
||||
}
|
||||
onPulled();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err.message || 'Failed to pull image');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open onClose={onClose} title="Pull Image" size="md">
|
||||
{error && <div className="error-message">{error}</div>}
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label>Image Name *</label>
|
||||
<Input
|
||||
type="text"
|
||||
value={image}
|
||||
onChange={(e) => setImage(e.target.value)}
|
||||
placeholder="nginx, mysql, redis"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Tag</label>
|
||||
<Input
|
||||
type="text"
|
||||
value={tag}
|
||||
onChange={(e) => setTag(e.target.value)}
|
||||
placeholder="latest"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="modal-actions">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? 'Pulling...' : 'Pull Image'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default ImagesTab;
|
||||
@@ -0,0 +1,194 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/ToastContext';
|
||||
import { useConfirm } from '../../hooks/useConfirm';
|
||||
import EmptyState from '../EmptyState';
|
||||
import Modal from '@/components/Modal';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Network as NetworkIcon } from 'lucide-react';
|
||||
import {
|
||||
useServer,
|
||||
normalizeListResponse,
|
||||
} from './dockerHelpers';
|
||||
import { IconAction, TrashIcon } from './dockerShared';
|
||||
|
||||
export const CreateNetworkButton = () => {
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const { isRemote } = useServer();
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={() => setShowModal(true)}
|
||||
disabled={isRemote}
|
||||
title={isRemote ? 'Creating networks is only available on the local Docker target right now' : 'Create network'}
|
||||
>
|
||||
<span>+</span> Create Network
|
||||
</Button>
|
||||
{showModal && <CreateNetworkModal onClose={() => setShowModal(false)} onCreated={() => window.location.reload()} />}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Networks Tab
|
||||
const NetworksTab = ({ onStatsChange }) => {
|
||||
const toast = useToast();
|
||||
const { serverId, isRemote } = useServer();
|
||||
const { confirm: confirmNetwork } = useConfirm();
|
||||
const [networks, setNetworks] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
loadNetworks();
|
||||
}, [serverId]);
|
||||
|
||||
async function loadNetworks() {
|
||||
setLoading(true);
|
||||
try {
|
||||
let data;
|
||||
if (isRemote) {
|
||||
const result = await api.getRemoteNetworks(serverId);
|
||||
data = { networks: normalizeListResponse(result, 'networks') };
|
||||
} else {
|
||||
data = await api.getNetworks();
|
||||
}
|
||||
setNetworks(data.networks || []);
|
||||
} catch (err) {
|
||||
console.error('Failed to load networks:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemove(networkId) {
|
||||
const confirmed = await confirmNetwork({ title: 'Remove Network', message: 'Remove this network?' });
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
if (isRemote) {
|
||||
await api.removeRemoteNetwork(serverId, networkId);
|
||||
} else {
|
||||
await api.removeNetwork(networkId);
|
||||
}
|
||||
toast.success('Network removed successfully');
|
||||
loadNetworks();
|
||||
onStatsChange?.();
|
||||
} catch (err) {
|
||||
console.error('Failed to remove network:', err);
|
||||
toast.error('Failed to remove network. It may be in use.');
|
||||
}
|
||||
}
|
||||
|
||||
const systemNetworks = ['bridge', 'host', 'none'];
|
||||
|
||||
if (loading) {
|
||||
return <div className="docker-loading">Loading networks...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{networks.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={NetworkIcon}
|
||||
title="No networks"
|
||||
description="Create a network to connect containers."
|
||||
/>
|
||||
) : (
|
||||
<table className="docker-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Network ID</th>
|
||||
<th>Driver</th>
|
||||
<th>Scope</th>
|
||||
<th className="text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{networks.map(network => (
|
||||
<tr key={network.id}>
|
||||
<td>
|
||||
<span className="docker-container-name">{network.name}</span>
|
||||
</td>
|
||||
<td>
|
||||
<span className="docker-container-id">{network.id?.substring(0, 12)}</span>
|
||||
</td>
|
||||
<td>{network.driver}</td>
|
||||
<td>{network.scope}</td>
|
||||
<td className="docker-actions-cell">
|
||||
{!systemNetworks.includes(network.name) && (
|
||||
<IconAction title="Delete" onClick={() => handleRemove(network.id)} color="#EF4444">
|
||||
<TrashIcon />
|
||||
</IconAction>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const CreateNetworkModal = ({ onClose, onCreated }) => {
|
||||
const [name, setName] = useState('');
|
||||
const [driver, setDriver] = useState('bridge');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function handleSubmit(e) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
await api.createNetwork(name, driver);
|
||||
onCreated();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err.message || 'Failed to create network');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open onClose={onClose} title="Create Network" size="md">
|
||||
{error && <div className="error-message">{error}</div>}
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label>Network Name *</label>
|
||||
<Input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="my-network"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Driver</label>
|
||||
<select value={driver} onChange={(e) => setDriver(e.target.value)}>
|
||||
<option value="bridge">bridge</option>
|
||||
<option value="overlay">overlay</option>
|
||||
<option value="macvlan">macvlan</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="modal-actions">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? 'Creating...' : 'Create Network'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default NetworksTab;
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useState } from 'react';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/ToastContext';
|
||||
import { useConfirm } from '../../hooks/useConfirm';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useServer } from './dockerHelpers';
|
||||
|
||||
const PruneButton = ({ onPruned }) => {
|
||||
const toast = useToast();
|
||||
const { isRemote } = useServer();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { confirm } = useConfirm();
|
||||
|
||||
async function handlePrune() {
|
||||
if (isRemote) {
|
||||
toast.error('Prune is only available on the local Docker target right now');
|
||||
return;
|
||||
}
|
||||
const confirmed = await confirm({ title: 'Docker Cleanup', message: 'Remove unused Docker resources? This will remove stopped containers, unused images, and unused networks.' });
|
||||
if (!confirmed) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
await api.request('/docker/cleanup', { method: 'POST', body: {} });
|
||||
toast.success('Docker cleanup completed');
|
||||
onPruned?.();
|
||||
} catch {
|
||||
toast.error('Failed to cleanup Docker resources');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handlePrune}
|
||||
disabled={loading || isRemote}
|
||||
title={isRemote ? 'Prune is only available on the local Docker target right now' : 'Prune unused Docker resources'}
|
||||
>
|
||||
{loading ? 'Cleaning...' : 'Prune Unused'}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default PruneButton;
|
||||
@@ -0,0 +1,180 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import api from '../../services/api';
|
||||
import { useToast } from '../../contexts/ToastContext';
|
||||
import { useConfirm } from '../../hooks/useConfirm';
|
||||
import EmptyState from '../EmptyState';
|
||||
import Modal from '@/components/Modal';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { HardDrive } from 'lucide-react';
|
||||
import {
|
||||
useServer,
|
||||
normalizeListResponse,
|
||||
} from './dockerHelpers';
|
||||
import { IconAction, TrashIcon } from './dockerShared';
|
||||
|
||||
export const CreateVolumeButton = () => {
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const { isRemote } = useServer();
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={() => setShowModal(true)}
|
||||
disabled={isRemote}
|
||||
title={isRemote ? 'Creating volumes is only available on the local Docker target right now' : 'Create volume'}
|
||||
>
|
||||
<span>+</span> Create Volume
|
||||
</Button>
|
||||
{showModal && <CreateVolumeModal onClose={() => setShowModal(false)} onCreated={() => window.location.reload()} />}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Volumes Tab
|
||||
const VolumesTab = ({ onStatsChange }) => {
|
||||
const toast = useToast();
|
||||
const { serverId, isRemote } = useServer();
|
||||
const { confirm: confirmVolume } = useConfirm();
|
||||
const [volumes, setVolumes] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
loadVolumes();
|
||||
}, [serverId]);
|
||||
|
||||
async function loadVolumes() {
|
||||
setLoading(true);
|
||||
try {
|
||||
let data;
|
||||
if (isRemote) {
|
||||
const result = await api.getRemoteVolumes(serverId);
|
||||
data = { volumes: normalizeListResponse(result, 'volumes') };
|
||||
} else {
|
||||
data = await api.getVolumes();
|
||||
}
|
||||
setVolumes(data.volumes || []);
|
||||
} catch (err) {
|
||||
console.error('Failed to load volumes:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemove(volumeName) {
|
||||
const confirmed = await confirmVolume({ title: 'Remove Volume', message: 'Remove this volume? All data will be lost.' });
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
if (isRemote) {
|
||||
await api.removeRemoteVolume(serverId, volumeName, true);
|
||||
} else {
|
||||
await api.removeVolume(volumeName, true);
|
||||
}
|
||||
toast.success('Volume removed successfully');
|
||||
loadVolumes();
|
||||
onStatsChange?.();
|
||||
} catch (err) {
|
||||
console.error('Failed to remove volume:', err);
|
||||
toast.error('Failed to remove volume. It may be in use.');
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <div className="docker-loading">Loading volumes...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{volumes.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={HardDrive}
|
||||
title="No volumes"
|
||||
description="Create a volume for persistent data storage."
|
||||
/>
|
||||
) : (
|
||||
<table className="docker-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Driver</th>
|
||||
<th>Mountpoint</th>
|
||||
<th className="text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{volumes.map(volume => (
|
||||
<tr key={volume.name}>
|
||||
<td>
|
||||
<span className="docker-container-name">{volume.name}</span>
|
||||
</td>
|
||||
<td>{volume.driver}</td>
|
||||
<td>
|
||||
<span className="docker-container-id truncate inline-block" style={{ maxWidth: '300px' }}>
|
||||
{volume.mountpoint || '-'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="docker-actions-cell">
|
||||
<IconAction title="Delete" onClick={() => handleRemove(volume.name)} color="#EF4444">
|
||||
<TrashIcon />
|
||||
</IconAction>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const CreateVolumeModal = ({ onClose, onCreated }) => {
|
||||
const [name, setName] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function handleSubmit(e) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
await api.createVolume(name);
|
||||
onCreated();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err.message || 'Failed to create volume');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open onClose={onClose} title="Create Volume" size="md">
|
||||
{error && <div className="error-message">{error}</div>}
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label>Volume Name *</label>
|
||||
<Input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="my-volume"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="modal-actions">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? 'Creating...' : 'Create Volume'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default VolumesTab;
|
||||
@@ -0,0 +1,108 @@
|
||||
import { createContext, useContext } from 'react';
|
||||
|
||||
// Server context for Docker operations
|
||||
export const ServerContext = createContext({ serverId: 'local', serverName: 'Local' });
|
||||
export const useServer = () => useContext(ServerContext);
|
||||
|
||||
export const VALID_TABS = ['containers', 'compose', 'images', 'volumes', 'networks'];
|
||||
export const LOCAL_DOCKER_TARGET = { id: 'local', name: 'Local (this server)', status: 'online', is_local: true };
|
||||
|
||||
export const unwrapRemoteData = (response) => {
|
||||
if (response?.success && response.data !== undefined) {
|
||||
return response.data;
|
||||
}
|
||||
return response;
|
||||
};
|
||||
|
||||
// formatPorts normalises Docker port data from the two shapes the agent
|
||||
// returns: a comma-separated string (legacy `docker ps`-style output)
|
||||
// or an array of `{ip, private_port, public_port, type}` objects from
|
||||
// `docker inspect`. Always returns an array of human-readable strings,
|
||||
// or `['-']` when there are no ports — both call sites (the container
|
||||
// list grid and the inspector drawer) want array semantics. Rendering
|
||||
// the raw inspect array directly triggered React error #31.
|
||||
export function formatPorts(ports) {
|
||||
if (!ports) return ['-'];
|
||||
if (Array.isArray(ports)) {
|
||||
const formatted = ports
|
||||
.map((p) => {
|
||||
if (!p || typeof p !== 'object') return null;
|
||||
const proto = p.type || p.protocol || 'tcp';
|
||||
const priv = p.private_port ?? p.PrivatePort;
|
||||
const pub = p.public_port ?? p.PublicPort;
|
||||
const ip = p.ip || p.IP;
|
||||
if (pub) {
|
||||
return `${ip ? `${ip}:` : ''}${pub}->${priv}/${proto}`;
|
||||
}
|
||||
return priv ? `${priv}/${proto}` : null;
|
||||
})
|
||||
.filter(Boolean);
|
||||
return formatted.length > 0 ? formatted : ['-'];
|
||||
}
|
||||
if (typeof ports !== 'string') return ['-'];
|
||||
const parts = ports.split(',').map((p) => p.trim()).filter(Boolean);
|
||||
return parts.length > 0 ? parts : ['-'];
|
||||
}
|
||||
|
||||
export const normalizeListResponse = (response, key) => {
|
||||
const data = unwrapRemoteData(response);
|
||||
if (Array.isArray(data)) return data;
|
||||
if (Array.isArray(data?.[key])) return data[key];
|
||||
return [];
|
||||
};
|
||||
|
||||
export const shortId = (value) => value ? value.substring(0, 12) : '-';
|
||||
|
||||
export const getContainerId = (container) => (
|
||||
container?.id || container?.ID || container?.Id || ''
|
||||
);
|
||||
|
||||
export const getContainerName = (container) => (
|
||||
container?.name || container?.Names || container?.Name || 'unnamed'
|
||||
);
|
||||
|
||||
export const getContainerImage = (container) => (
|
||||
container?.image || container?.Image || container?.Config?.Image || '-'
|
||||
);
|
||||
|
||||
export const getContainerStatus = (container) => (
|
||||
container?.status || container?.Status || container?.State?.Status || '-'
|
||||
);
|
||||
|
||||
export const getContainerState = (container) => {
|
||||
const state = container?.state || container?.State?.Status || container?.State || '';
|
||||
return typeof state === 'string' ? state.toLowerCase() : '';
|
||||
};
|
||||
|
||||
export const isContainerRunning = (container) => getContainerState(container) === 'running';
|
||||
|
||||
// ServerKit's own infrastructure containers run the panel itself, so we don't
|
||||
// expose lifecycle controls (start/stop/restart/remove) for them — the backend
|
||||
// rejects those calls anyway. Trust the backend `protected` flag when present;
|
||||
// fall back to a name check for shapes (e.g. remote agents) that omit it.
|
||||
export const SELF_CONTAINER_HINTS = ['serverkit-frontend', 'serverkit_frontend', 'serverkit-backend', 'serverkit_backend'];
|
||||
export const isProtectedContainer = (container) => {
|
||||
if (container?.protected === true) return true;
|
||||
const name = getContainerName(container).toLowerCase().replace(/\//g, '');
|
||||
return SELF_CONTAINER_HINTS.some(hint => name.includes(hint));
|
||||
};
|
||||
|
||||
export const getContainerStatusLabel = (container) => {
|
||||
if (isContainerRunning(container)) return 'Running';
|
||||
const state = getContainerState(container);
|
||||
if (state === 'exited') return 'Exited';
|
||||
if (state === 'created') return 'Created';
|
||||
return state || 'Unknown';
|
||||
};
|
||||
|
||||
// Deterministic hue from a container name (demo's per-container accent color).
|
||||
export const containerHue = (name = '') => {
|
||||
let h = 0;
|
||||
for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) % 360;
|
||||
return h;
|
||||
};
|
||||
|
||||
export const getContainerProjectName = (container, details) => {
|
||||
const labels = details?.Config?.Labels || container?.Labels || {};
|
||||
return labels['com.docker.compose.project'] || labels['com.docker.compose.service'] || '-';
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Trash2 } from 'lucide-react';
|
||||
|
||||
// Icon Action button used by remaining (legacy) tabs (Images, Networks, Volumes).
|
||||
// Containers tab now renders cards with full action buttons inline.
|
||||
export const IconAction = ({ title, onClick, color, children, disabled }) => (
|
||||
<button
|
||||
className="docker-icon-action"
|
||||
title={title}
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
style={color ? { color } : {}}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
|
||||
export const TrashIcon = () => <Trash2 size={14} />;
|
||||
|
||||
export const ContainerResourceBars = ({ stats, muted = false }) => (
|
||||
<div className={`dx-mini-resources ${muted || !stats.available ? 'is-muted' : ''}`}>
|
||||
<div className="dx-mini-resource">
|
||||
<span>CPU</span>
|
||||
<div className="dx-res-track">
|
||||
<div className="dx-res-fill cpu" style={{ width: `${stats.available ? Math.min(stats.cpu, 100) : 0}%` }} />
|
||||
</div>
|
||||
<strong>{stats.available ? `${stats.cpu.toFixed(1)}%` : '--'}</strong>
|
||||
</div>
|
||||
<div className="dx-mini-resource">
|
||||
<span>RAM</span>
|
||||
<div className="dx-res-track">
|
||||
<div className="dx-res-fill mem" style={{ width: `${stats.available ? Math.min(stats.memory, 100) : 0}%` }} />
|
||||
</div>
|
||||
<strong>{stats.available ? `${stats.memory.toFixed(1)}%` : '--'}</strong>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Download Icon for Compose Pull
|
||||
export const DownloadIcon = () => (
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
|
||||
<polyline points="7 10 12 15 17 10"/>
|
||||
<line x1="12" y1="15" x2="12" y2="3"/>
|
||||
</svg>
|
||||
);
|
||||
+15
-2177
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user