Initial commit

This commit is contained in:
Jarek Krochmalski
2025-12-28 21:16:03 +01:00
commit 62e3c6439e
552 changed files with 104858 additions and 0 deletions

663
routes/volumes/+page.svelte Normal file
View File

@@ -0,0 +1,663 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { toast } from 'svelte-sonner';
import { Badge } from '$lib/components/ui/badge';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Trash2, Search, Plus, Eye, Check, XCircle, RefreshCw, Icon, AlertTriangle, X, HardDrive, Stamp, FolderOpen, Download, Database, Server, CircleDot, Circle } from 'lucide-svelte';
import { broom } from '@lucide/lab';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import BatchOperationModal from '$lib/components/BatchOperationModal.svelte';
import CreateVolumeModal from './CreateVolumeModal.svelte';
import VolumeInspectModal from './VolumeInspectModal.svelte';
import VolumeBrowserModal from './VolumeBrowserModal.svelte';
import CloneVolumeModal from './CloneVolumeModal.svelte';
import ContainerInspectModal from '../containers/ContainerInspectModal.svelte';
import { appSettings } from '$lib/stores/settings';
import type { VolumeInfo } from '$lib/types';
import { currentEnvironment, environments, appendEnvParam, clearStaleEnvironment } from '$lib/stores/environment';
import MultiSelectFilter from '$lib/components/MultiSelectFilter.svelte';
import PageHeader from '$lib/components/PageHeader.svelte';
import { onDockerEvent, isVolumeListChange } from '$lib/stores/events';
import { canAccess } from '$lib/stores/auth';
import { formatDateTime } from '$lib/stores/settings';
import { EmptyState, NoEnvironment } from '$lib/components/ui/empty-state';
import { DataGrid } from '$lib/components/data-grid';
type SortField = 'name' | 'driver' | 'stack' | 'created';
type SortDirection = 'asc' | 'desc';
let volumes = $state<VolumeInfo[]>([]);
let loading = $state(true);
let envId = $state<number | null>(null);
// Search and sort state - with debounce
let searchInput = $state('');
let searchQuery = $state('');
let sortField = $state<SortField>('name');
let sortDirection = $state<SortDirection>('asc');
// Filter state
let driverFilter = $state<string[]>([]);
let usageFilter = $state<string[]>([]);
// Driver icon mapping
const driverIconMap: Record<string, { icon: any; color: string }> = {
local: { icon: Database, color: 'text-emerald-500' },
nfs: { icon: Server, color: 'text-sky-500' },
cifs: { icon: Server, color: 'text-sky-500' },
tmpfs: { icon: Database, color: 'text-amber-500' }
};
// Available filter options (derived from current volumes)
const driverOptions = $derived(
[...new Set(volumes.map(v => v.driver))].sort().map(d => {
const mapping = driverIconMap[d] || { icon: Database, color: 'text-muted-foreground' };
return { value: d, label: d, icon: mapping.icon, color: mapping.color };
})
);
// Usage filter options (static)
const usageOptions = [
{ value: 'in-use', label: 'In use', icon: CircleDot, color: 'text-emerald-500' },
{ value: 'unused', label: 'Unused', icon: Circle, color: 'text-muted-foreground' }
];
// Confirmation popover state
let confirmDeleteName = $state<string | null>(null);
// Delete error state
let deleteError = $state<{ name: string; message: string } | null>(null);
// Timeout tracking for cleanup
let pendingTimeouts: ReturnType<typeof setTimeout>[] = [];
// Multi-select state
let selectedVolumes = $state<Set<string>>(new Set());
let confirmBulkRemove = $state(false);
// Row highlighting state
let highlightedRowId = $state<string | null>(null);
// Batch operation modal state
let showBatchOpModal = $state(false);
let batchOpTitle = $state('');
let batchOpOperation = $state('');
let batchOpItems = $state<Array<{ id: string; name: string }>>([]);
// Check if all filtered volumes are selected
const allFilteredSelected = $derived(
filteredVolumes.length > 0 && filteredVolumes.every(v => selectedVolumes.has(v.name))
);
const someFilteredSelected = $derived(
filteredVolumes.some(v => selectedVolumes.has(v.name)) && !allFilteredSelected
);
const selectedInFilter = $derived(
filteredVolumes.filter(v => selectedVolumes.has(v.name))
);
function selectNone() {
selectedVolumes = new Set();
}
function bulkRemove() {
batchOpTitle = `Removing ${selectedInFilter.length} volume${selectedInFilter.length !== 1 ? 's' : ''}`;
batchOpOperation = 'remove';
batchOpItems = selectedInFilter.map(v => ({ id: v.name, name: v.name }));
showBatchOpModal = true;
}
function handleBatchComplete() {
selectedVolumes = new Set();
fetchVolumes();
}
// Modal state
let showCreateModal = $state(false);
let showInspectModal = $state(false);
let inspectVolumeName = $state('');
let showBrowserModal = $state(false);
let browseVolumeName = $state('');
let showCloneModal = $state(false);
let cloneVolumeName = $state('');
let exportingVolume = $state<string | null>(null);
// Container inspect modal state
let showContainerInspectModal = $state(false);
let inspectContainerId = $state('');
let inspectContainerName = $state('');
// Prune state
let confirmPrune = $state(false);
let pruneStatus = $state<'idle' | 'pruning' | 'success' | 'error'>('idle');
// Debounce search input
let searchTimeout: ReturnType<typeof setTimeout>;
$effect(() => {
const input = searchInput; // Track dependency
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
searchQuery = input;
}, 200);
return () => clearTimeout(searchTimeout);
});
// Track if initial fetch has been done
let initialFetchDone = $state(false);
// Subscribe to environment changes using $effect
$effect(() => {
const env = $currentEnvironment;
const newEnvId = env?.id ?? null;
// Only fetch if environment actually changed or this is initial load
if (env && (newEnvId !== envId || !initialFetchDone)) {
envId = newEnvId;
initialFetchDone = true;
fetchVolumes();
} else if (!env) {
// No environment - clear data and stop loading
envId = null;
volumes = [];
loading = false;
}
});
// Filtered and sorted volumes - use $derived.by for complex logic
const filteredVolumes = $derived.by(() => {
let result = volumes;
// Filter by driver
if (driverFilter.length > 0) {
result = result.filter(vol => driverFilter.includes(vol.driver));
}
// Filter by usage
if (usageFilter.length > 0) {
result = result.filter(vol => {
const isInUse = vol.usedBy && vol.usedBy.length > 0;
if (usageFilter.includes('in-use') && usageFilter.includes('unused')) {
return true; // Both selected = show all
}
if (usageFilter.includes('in-use')) {
return isInUse;
}
if (usageFilter.includes('unused')) {
return !isInUse;
}
return true;
});
}
// Filter by search query
if (searchQuery.trim()) {
const query = searchQuery.toLowerCase();
result = result.filter(vol =>
vol.name.toLowerCase().includes(query) ||
(vol.labels['com.docker.compose.project'] || '').toLowerCase().includes(query)
);
}
// Sort
result = [...result].sort((a, b) => {
let cmp = 0;
switch (sortField) {
case 'name':
cmp = a.name.localeCompare(b.name);
break;
case 'driver':
cmp = a.driver.localeCompare(b.driver);
break;
case 'stack':
const stackA = a.labels['com.docker.compose.project'] || '';
const stackB = b.labels['com.docker.compose.project'] || '';
cmp = stackA.localeCompare(stackB);
break;
case 'created':
cmp = new Date(a.created).getTime() - new Date(b.created).getTime();
break;
}
// Secondary sort by name for stability when primary values are equal
if (cmp === 0 && sortField !== 'name') {
cmp = a.name.localeCompare(b.name);
}
return sortDirection === 'asc' ? cmp : -cmp;
});
return result;
});
async function fetchVolumes() {
loading = true;
try {
const response = await fetch(appendEnvParam('/api/volumes', envId));
if (!response.ok) {
// Handle stale environment ID (e.g., after database reset)
if (response.status === 404 && envId) {
clearStaleEnvironment(envId);
environments.refresh();
return;
}
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
volumes = await response.json();
} catch (error) {
console.error('Failed to fetch volumes:', error);
toast.error('Failed to load volumes');
} finally {
loading = false;
}
}
async function removeVolume(name: string) {
deleteError = null;
try {
const response = await fetch(appendEnvParam(`/api/volumes/${encodeURIComponent(name)}?force=true`, envId), { method: 'DELETE' });
if (!response.ok) {
const data = await response.json();
deleteError = { name, message: data.details || data.error || 'Failed to remove volume' };
toast.error(`Failed to remove ${name}`);
// Auto-hide error after 5 seconds
pendingTimeouts.push(setTimeout(() => {
if (deleteError?.name === name) deleteError = null;
}, 5000));
return;
}
toast.success(`Removed ${name}`);
await fetchVolumes();
} catch (error) {
console.error('Failed to remove volume:', error);
deleteError = { name, message: 'Failed to remove volume' };
toast.error(`Failed to remove ${name}`);
pendingTimeouts.push(setTimeout(() => {
if (deleteError?.name === name) deleteError = null;
}, 5000));
}
}
function formatDate(dateString: string): string {
if (!dateString) return 'N/A';
return formatDateTime(dateString);
}
function inspectVolume(volumeName: string) {
inspectVolumeName = volumeName;
showInspectModal = true;
}
function browseVolume(volumeName: string) {
browseVolumeName = volumeName;
showBrowserModal = true;
}
function cloneVolume(volumeName: string) {
cloneVolumeName = volumeName;
showCloneModal = true;
}
function openContainerInspect(containerId: string, containerName: string) {
inspectContainerId = containerId;
inspectContainerName = containerName;
showContainerInspectModal = true;
}
async function exportVolume(volumeName: string) {
exportingVolume = volumeName;
try {
const format = $appSettings.downloadFormat || 'tar';
const url = appendEnvParam(
`/api/volumes/${encodeURIComponent(volumeName)}/export?path=/&format=${format}`,
envId
);
const link = document.createElement('a');
link.href = url;
link.download = '';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
toast.success(`Exporting ${volumeName}...`);
} catch (err) {
console.error('Failed to export volume:', err);
toast.error(`Failed to export ${volumeName}`);
} finally {
pendingTimeouts.push(setTimeout(() => {
if (exportingVolume === volumeName) exportingVolume = null;
}, 2000));
}
}
async function pruneVolumes() {
pruneStatus = 'pruning';
confirmPrune = false;
try {
const response = await fetch(appendEnvParam('/api/prune/volumes', envId), {
method: 'POST'
});
if (response.ok) {
pruneStatus = 'success';
toast.success('Unused volumes pruned');
await fetchVolumes();
} else {
pruneStatus = 'error';
toast.error('Failed to prune volumes');
}
} catch (error) {
pruneStatus = 'error';
toast.error('Failed to prune volumes');
}
pendingTimeouts.push(setTimeout(() => {
pruneStatus = 'idle';
}, 3000));
}
// Handle tab visibility changes (e.g., user switches back from another tab)
function handleVisibilityChange() {
if (document.visibilityState === 'visible' && envId) {
fetchVolumes();
}
}
onMount(() => {
// Initial fetch is handled by $effect - no need to duplicate here
// Listen for tab visibility changes to refresh when user returns
document.addEventListener('visibilitychange', handleVisibilityChange);
document.addEventListener('resume', handleVisibilityChange);
// Subscribe to volume events (SSE connection is global in layout)
const unsubscribe = onDockerEvent((event) => {
if (envId && isVolumeListChange(event)) {
fetchVolumes();
}
});
const interval = setInterval(() => {
if (envId) fetchVolumes();
}, 30000);
return () => {
clearInterval(interval);
unsubscribe();
};
});
onDestroy(() => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
document.removeEventListener('resume', handleVisibilityChange);
pendingTimeouts.forEach(id => clearTimeout(id));
pendingTimeouts = [];
});
</script>
<div class="flex-1 min-h-0 flex flex-col gap-3 overflow-hidden">
<div class="shrink-0 flex flex-wrap justify-between items-center gap-3">
<PageHeader icon={HardDrive} title="Volumes" count={volumes.length} />
<div class="flex flex-wrap items-center gap-2">
<div class="relative">
<Search class="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
<Input
type="text"
placeholder="Search volumes..."
bind:value={searchInput}
onkeydown={(e) => e.key === 'Escape' && (searchInput = '')}
class="pl-8 h-8 w-48 text-sm"
/>
</div>
<MultiSelectFilter
bind:value={driverFilter}
options={driverOptions}
placeholder="Driver"
pluralLabel="drivers"
width="w-28"
defaultIcon={Database}
/>
<MultiSelectFilter
bind:value={usageFilter}
options={usageOptions}
placeholder="Usage"
pluralLabel="usages"
width="w-28"
defaultIcon={CircleDot}
/>
{#if $canAccess('volumes', 'remove')}
<ConfirmPopover
open={confirmPrune}
action="Prune"
itemType="unused volumes"
title="Prune volumes"
position="left"
onConfirm={pruneVolumes}
onOpenChange={(open) => confirmPrune = open}
>
{#snippet children({ open })}
<span class="inline-flex items-center gap-1.5 h-8 px-3 rounded-md text-sm bg-background shadow-xs border hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50 {pruneStatus === 'pruning' ? 'opacity-50 pointer-events-none' : ''}">
{#if pruneStatus === 'pruning'}
<RefreshCw class="w-3.5 h-3.5 animate-spin" />
{:else if pruneStatus === 'success'}
<Check class="w-3.5 h-3.5 text-green-600" />
{:else if pruneStatus === 'error'}
<XCircle class="w-3.5 h-3.5 text-destructive" />
{:else}
<Icon iconNode={broom} class="w-3.5 h-3.5" />
{/if}
Prune
</span>
{/snippet}
</ConfirmPopover>
{/if}
<Button size="sm" variant="outline" onclick={fetchVolumes}>Refresh</Button>
{#if $canAccess('volumes', 'create')}
<Button size="sm" variant="secondary" onclick={() => showCreateModal = true}>
<Plus class="w-3.5 h-3.5 mr-1" />
Create
</Button>
{/if}
</div>
</div>
<!-- Selection bar -->
{#if selectedVolumes.size > 0}
<div class="flex items-center gap-2 text-xs text-muted-foreground">
<span>{selectedInFilter.length} selected</span>
<button
type="button"
class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full border border-border shadow-sm hover:border-foreground/30 hover:shadow transition-all"
onclick={selectNone}
>
Clear
</button>
{#if $canAccess('volumes', 'remove')}
<ConfirmPopover
open={confirmBulkRemove}
action="Delete"
itemType="{selectedInFilter.length} volume{selectedInFilter.length !== 1 ? 's' : ''}"
title="Delete {selectedInFilter.length}"
unstyled
onConfirm={bulkRemove}
onOpenChange={(open) => confirmBulkRemove = open}
>
{#snippet children({ open })}
<span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full border border-border shadow-sm hover:text-destructive hover:border-destructive/40 hover:shadow transition-all cursor-pointer">
<Trash2 class="w-3 h-3" />
Delete
</span>
{/snippet}
</ConfirmPopover>
{/if}
</div>
{/if}
{#if !loading && ($environments.length === 0 || !$currentEnvironment)}
<NoEnvironment />
{:else if !loading && volumes.length === 0}
<EmptyState
icon={HardDrive}
title="No volumes found"
description="Create a volume to persist container data"
/>
{:else}
<DataGrid
data={filteredVolumes}
keyField="name"
gridId="volumes"
loading={loading}
selectable
bind:selectedKeys={selectedVolumes}
sortState={{ field: sortField, direction: sortDirection }}
onSortChange={(state) => { sortField = state.field as SortField; sortDirection = state.direction; }}
highlightedKey={highlightedRowId}
onRowClick={(volume) => { highlightedRowId = highlightedRowId === volume.name ? null : volume.name; }}
>
{#snippet cell(column, volume, rowState)}
{@const stack = volume.labels['com.docker.compose.project']}
{#if column.id === 'name'}
<code class="text-xs truncate block" title={volume.name}>{volume.name}</code>
{:else if column.id === 'driver'}
<Badge variant="outline" class="text-xs py-0 px-1.5 shadow-sm rounded-sm">{volume.driver}</Badge>
{:else if column.id === 'scope'}
<span class="text-xs">{volume.scope}</span>
{:else if column.id === 'stack'}
{#if stack}
<Badge variant="secondary" class="text-xs py-0 px-1.5 shadow-sm rounded-sm">{stack}</Badge>
{:else}
<span class="text-muted-foreground text-xs">-</span>
{/if}
{:else if column.id === 'usedBy'}
{#if volume.usedBy && volume.usedBy.length > 0}
<div class="flex flex-wrap gap-1">
{#each volume.usedBy.slice(0, 3) as container}
<button
type="button"
onclick={() => openContainerInspect(container.containerId, container.containerName)}
class="text-xs text-primary hover:underline cursor-pointer truncate max-w-[100px]"
title={container.containerName}
>
{container.containerName}
</button>
{/each}
{#if volume.usedBy.length > 3}
<span class="text-xs text-muted-foreground">+{volume.usedBy.length - 3}</span>
{/if}
</div>
{:else}
<span class="text-muted-foreground text-xs">-</span>
{/if}
{:else if column.id === 'created'}
<span class="text-xs text-muted-foreground">{formatDate(volume.created)}</span>
{:else if column.id === 'actions'}
<div class="flex items-center justify-end gap-1">
{#if $canAccess('volumes', 'inspect')}
<button
type="button"
onclick={() => inspectVolume(volume.name)}
title="View details"
class="p-1 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
>
<Eye class="w-3 h-3 text-muted-foreground hover:text-foreground" />
</button>
<button
type="button"
onclick={() => browseVolume(volume.name)}
title="Browse files"
class="p-1 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
>
<FolderOpen class="w-3 h-3 text-muted-foreground hover:text-foreground" />
</button>
<button
type="button"
onclick={() => exportVolume(volume.name)}
title="Export volume as {$appSettings.downloadFormat || 'tar'}"
class="p-1 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer {exportingVolume === volume.name ? 'animate-pulse' : ''}"
disabled={exportingVolume === volume.name}
>
<Download class="w-3 h-3 text-muted-foreground hover:text-foreground" />
</button>
{/if}
{#if $canAccess('volumes', 'create')}
<button
type="button"
onclick={() => cloneVolume(volume.name)}
title="Clone volume"
class="p-1 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
>
<Stamp class="w-3 h-3 text-muted-foreground hover:text-foreground" />
</button>
{/if}
{#if $canAccess('volumes', 'remove')}
<div class="relative">
<ConfirmPopover
open={confirmDeleteName === volume.name}
action="Delete"
itemType="volume"
itemName={volume.name}
title="Remove"
onConfirm={() => removeVolume(volume.name)}
onOpenChange={(open) => confirmDeleteName = open ? volume.name : null}
>
{#snippet children({ open })}
<Trash2 class="w-3 h-3 {open ? 'text-destructive' : 'text-muted-foreground hover:text-destructive'}" />
{/snippet}
</ConfirmPopover>
{#if deleteError?.name === volume.name}
<div class="absolute bottom-full right-0 mb-1 z-50 bg-destructive text-destructive-foreground rounded-md shadow-lg p-2 text-xs flex items-start gap-2 max-w-lg w-max">
<AlertTriangle class="w-3 h-3 flex-shrink-0 mt-0.5" />
<span class="break-words">{deleteError.message}</span>
<button onclick={() => deleteError = null} class="flex-shrink-0 hover:bg-white/20 rounded p-0.5">
<X class="w-3 h-3" />
</button>
</div>
{/if}
</div>
{/if}
</div>
{/if}
{/snippet}
</DataGrid>
{/if}
</div>
<CreateVolumeModal
bind:open={showCreateModal}
onClose={() => showCreateModal = false}
onSuccess={fetchVolumes}
/>
<VolumeInspectModal
bind:open={showInspectModal}
volumeName={inspectVolumeName}
/>
<VolumeBrowserModal
bind:open={showBrowserModal}
volumeName={browseVolumeName}
{envId}
onclose={() => showBrowserModal = false}
/>
<CloneVolumeModal
bind:open={showCloneModal}
volumeName={cloneVolumeName}
{envId}
onclose={() => showCloneModal = false}
onsuccess={fetchVolumes}
/>
<ContainerInspectModal
bind:open={showContainerInspectModal}
containerId={inspectContainerId}
containerName={inspectContainerName}
/>
<BatchOperationModal
bind:open={showBatchOpModal}
title={batchOpTitle}
operation={batchOpOperation}
entityType="volumes"
items={batchOpItems}
envId={envId ?? undefined}
onClose={() => showBatchOpModal = false}
onComplete={handleBatchComplete}
/>

View File

@@ -0,0 +1,119 @@
<script lang="ts">
import * as Dialog from '$lib/components/ui/dialog';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label';
import { Copy, Loader2 } from 'lucide-svelte';
import { toast } from 'svelte-sonner';
import { appendEnvParam } from '$lib/stores/environment';
import { focusFirstInput } from '$lib/utils';
interface Props {
open: boolean;
volumeName: string;
envId?: number | null;
onclose: () => void;
onsuccess: () => void;
}
let { open = $bindable(), volumeName, envId, onclose, onsuccess }: Props = $props();
let newName = $state('');
let cloning = $state(false);
let error = $state<string | null>(null);
// Generate a default name when opening
$effect(() => {
if (open) {
newName = `${volumeName}-copy`;
error = null;
}
});
function handleOpenChange(isOpen: boolean) {
if (!isOpen) {
onclose();
}
}
async function handleClone() {
if (!newName.trim()) {
error = 'Please enter a name for the new volume';
return;
}
cloning = true;
error = null;
try {
const url = appendEnvParam(`/api/volumes/${encodeURIComponent(volumeName)}/clone`, envId);
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newName.trim() })
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.details || data.error || 'Failed to clone volume');
}
toast.success(`Volume cloned as "${newName}"`);
onsuccess();
open = false;
} catch (e: any) {
error = e.message || 'Failed to clone volume';
} finally {
cloning = false;
}
}
</script>
<Dialog.Root bind:open onOpenChange={(isOpen) => { if (isOpen) focusFirstInput(); handleOpenChange(isOpen); }}>
<Dialog.Content class="max-w-2xl">
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2">
<Copy class="w-5 h-5" />
Clone volume
</Dialog.Title>
<Dialog.Description>
Create a new volume with the same driver and options as "{volumeName}".
</Dialog.Description>
</Dialog.Header>
<div class="space-y-4 py-4">
<div class="space-y-2">
<Label for="new-name">New volume name</Label>
<Input
id="new-name"
bind:value={newName}
placeholder="Enter new volume name"
disabled={cloning}
onkeydown={(e) => e.key === 'Enter' && handleClone()}
/>
</div>
{#if error}
<p class="text-sm text-destructive">{error}</p>
{/if}
<p class="text-xs text-muted-foreground">
Note: This creates an empty volume with the same configuration. To copy data, use the Export feature on the source volume and import into the new volume.
</p>
</div>
<Dialog.Footer>
<Button variant="outline" onclick={() => (open = false)} disabled={cloning}>
Cancel
</Button>
<Button onclick={handleClone} disabled={cloning || !newName.trim()}>
{#if cloning}
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
{:else}
<Copy class="w-4 h-4 mr-2" />
{/if}
Clone
</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>

View File

@@ -0,0 +1,295 @@
<script lang="ts" module>
type KeyValue = { key: string; value: string };
</script>
<script lang="ts">
import * as Dialog from '$lib/components/ui/dialog';
import * as Select from '$lib/components/ui/select';
import { Label } from '$lib/components/ui/label';
import { Input } from '$lib/components/ui/input';
import { Button } from '$lib/components/ui/button';
import { Plus, Trash2, HardDrive, Database, Server } from 'lucide-svelte';
const VOLUME_DRIVERS = [
{ value: 'local', label: 'Local', description: 'Default local driver', icon: HardDrive },
{ value: 'nfs', label: 'NFS', description: 'Network file system', icon: Server },
{ value: 'cifs', label: 'CIFS', description: 'Windows/SMB shares', icon: Database }
];
import { currentEnvironment, appendEnvParam } from '$lib/stores/environment';
import { focusFirstInput } from '$lib/utils';
interface Props {
open: boolean;
onClose?: () => void;
onSuccess?: () => void;
}
let { open = $bindable(), onClose, onSuccess }: Props = $props();
// Form state
let name = $state('');
let driver = $state('local');
let driverOpts = $state<KeyValue[]>([]);
let labels = $state<KeyValue[]>([]);
let creating = $state(false);
let error = $state('');
let errors = $state<{ name?: string }>({});
function addDriverOpt() {
driverOpts = [...driverOpts, { key: '', value: '' }];
}
function removeDriverOpt(index: number) {
driverOpts = driverOpts.filter((_, i) => i !== index);
}
function addLabel() {
labels = [...labels, { key: '', value: '' }];
}
function removeLabel(index: number) {
labels = labels.filter((_, i) => i !== index);
}
function resetForm() {
name = '';
driver = 'local';
driverOpts = [];
labels = [];
error = '';
errors = {};
}
async function handleCreate() {
errors = {};
if (!name.trim()) {
errors.name = 'Volume name is required';
return;
}
creating = true;
error = '';
try {
const envId = $currentEnvironment?.id ?? null;
// Convert key-value arrays to objects
const driverOptsObj: Record<string, string> = {};
driverOpts.forEach(({ key, value }) => {
if (key && value) {
driverOptsObj[key] = value;
}
});
const labelsObj: Record<string, string> = {};
labels.forEach(({ key, value }) => {
if (key && value) {
labelsObj[key] = value;
}
});
const response = await fetch(appendEnvParam('/api/volumes', envId), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: name.trim(),
driver,
driverOpts: driverOptsObj,
labels: labelsObj
})
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.details || data.error || 'Failed to create volume');
}
resetForm();
open = false;
onSuccess?.();
} catch (err: any) {
error = err.message || 'Failed to create volume';
console.error('Failed to create volume:', err);
} finally {
creating = false;
}
}
function handleOpenChange(newOpen: boolean) {
if (!newOpen && !creating) {
resetForm();
}
open = newOpen;
}
</script>
<Dialog.Root bind:open onOpenChange={(isOpen) => { if (isOpen) focusFirstInput(); handleOpenChange(isOpen); }}>
<Dialog.Content class="max-w-2xl">
<Dialog.Header>
<Dialog.Title>Create volume</Dialog.Title>
</Dialog.Header>
<div class="space-y-4">
{#if error}
<div class="text-sm text-red-600 dark:text-red-400 p-2 bg-red-50 dark:bg-red-950 rounded">
{error}
</div>
{/if}
<!-- Volume Name -->
<div class="space-y-2">
<Label for="volume-name">Volume name *</Label>
<Input
id="volume-name"
bind:value={name}
placeholder="my-volume"
disabled={creating}
class={errors.name ? 'border-destructive focus-visible:ring-destructive' : ''}
oninput={() => errors.name = undefined}
/>
{#if errors.name}
<p class="text-xs text-destructive">{errors.name}</p>
{/if}
</div>
<!-- Driver -->
<div class="space-y-2">
<Label for="driver">Driver</Label>
<Select.Root type="single" bind:value={driver} disabled={creating}>
<Select.Trigger class="w-full h-9">
{@const selectedDriver = VOLUME_DRIVERS.find(d => d.value === driver)}
<span class="flex items-center">
{#if selectedDriver}
<svelte:component this={selectedDriver.icon} class="w-4 h-4 mr-2 text-muted-foreground" />
{selectedDriver.label}
{:else}
Select driver
{/if}
</span>
</Select.Trigger>
<Select.Content>
{#each VOLUME_DRIVERS as d}
<Select.Item value={d.value} label={d.label}>
<svelte:component this={d.icon} class="w-4 h-4 mr-2 text-muted-foreground" />
<div class="flex flex-col">
<span>{d.label}</span>
<span class="text-xs text-muted-foreground">{d.description}</span>
</div>
</Select.Item>
{/each}
</Select.Content>
</Select.Root>
<p class="text-xs text-muted-foreground">
Volume driver to use (local is default)
</p>
</div>
<!-- Driver Options -->
<div class="space-y-2">
<div class="flex items-center justify-between">
<Label>Driver options</Label>
<Button
type="button"
size="sm"
variant="outline"
onclick={addDriverOpt}
disabled={creating}
>
<Plus class="w-3 h-3 mr-1" />
Add option
</Button>
</div>
{#if driverOpts.length > 0}
<div class="space-y-2">
{#each driverOpts as opt, i}
<div class="flex gap-2">
<Input
bind:value={opt.key}
placeholder="Key"
disabled={creating}
class="flex-1"
/>
<Input
bind:value={opt.value}
placeholder="Value"
disabled={creating}
class="flex-1"
/>
<Button
type="button"
size="icon"
variant="ghost"
onclick={() => removeDriverOpt(i)}
disabled={creating}
>
<Trash2 class="w-4 h-4" />
</Button>
</div>
{/each}
</div>
{:else}
<p class="text-xs text-muted-foreground">No driver options configured</p>
{/if}
</div>
<!-- Labels -->
<div class="space-y-2">
<div class="flex items-center justify-between">
<Label>Labels</Label>
<Button
type="button"
size="sm"
variant="outline"
onclick={addLabel}
disabled={creating}
>
<Plus class="w-3 h-3 mr-1" />
Add label
</Button>
</div>
{#if labels.length > 0}
<div class="space-y-2">
{#each labels as label, i}
<div class="flex gap-2">
<Input
bind:value={label.key}
placeholder="Key"
disabled={creating}
class="flex-1"
/>
<Input
bind:value={label.value}
placeholder="Value"
disabled={creating}
class="flex-1"
/>
<Button
type="button"
size="icon"
variant="ghost"
onclick={() => removeLabel(i)}
disabled={creating}
>
<Trash2 class="w-4 h-4" />
</Button>
</div>
{/each}
</div>
{:else}
<p class="text-xs text-muted-foreground">No labels configured</p>
{/if}
</div>
<Dialog.Footer class="pt-4">
<Button variant="outline" onclick={() => (open = false)} disabled={creating}>
Cancel
</Button>
<Button onclick={handleCreate} disabled={creating}>
{creating ? 'Creating...' : 'Create volume'}
</Button>
</Dialog.Footer>
</div>
</Dialog.Content>
</Dialog.Root>

View File

@@ -0,0 +1,93 @@
<script lang="ts">
import * as Dialog from '$lib/components/ui/dialog';
import { HardDrive, Lock, Container } from 'lucide-svelte';
import { Badge } from '$lib/components/ui/badge';
import FileBrowserPanel from '../containers/FileBrowserPanel.svelte';
interface VolumeUsageInfo {
containerId: string;
containerName: string;
state: string;
}
interface Props {
open: boolean;
volumeName: string;
envId?: number | null;
onclose: () => void;
}
let { open = $bindable(), volumeName, envId, onclose }: Props = $props();
// Track volume usage from FileBrowserPanel
let volumeUsage = $state<VolumeUsageInfo[]>([]);
let isInUse = $state(false);
function handleUsageChange(usage: VolumeUsageInfo[], inUse: boolean) {
volumeUsage = usage;
isInUse = inUse;
}
async function releaseHelperContainer() {
try {
const params = new URLSearchParams();
if (envId) params.set('env', String(envId));
await fetch(`/api/volumes/${encodeURIComponent(volumeName)}/browse/release?${params}`, {
method: 'POST'
});
} catch {
// Silently ignore - cleanup is best-effort
}
}
function handleOpenChange(isOpen: boolean) {
if (!isOpen) {
// Release the helper container when modal closes
releaseHelperContainer();
onclose();
}
}
</script>
<Dialog.Root bind:open onOpenChange={handleOpenChange}>
<Dialog.Content class="max-w-4xl h-[80vh] flex flex-col">
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2">
<HardDrive class="w-5 h-5" />
<span>Browse volume - {volumeName}</span>
{#if isInUse}
<Badge variant="secondary" class="flex items-center gap-1 ml-2">
<Lock class="w-3 h-3" />
<span>Read-only</span>
</Badge>
{/if}
</Dialog.Title>
<Dialog.Description>
{#if isInUse}
<span class="flex items-center gap-1.5 flex-wrap">
<Lock class="w-3.5 h-3.5 text-muted-foreground inline" />
<span>Volume is in use by:</span>
{#each volumeUsage as container, i}
<span class="inline-flex items-center gap-1 text-foreground font-medium">
<Container class="w-3 h-3" />
{container.containerName}
<span class="text-muted-foreground">({container.state})</span>{#if i < volumeUsage.length - 1}<span>,</span>{/if}
</span>
{/each}
<span class="text-muted-foreground">- editing disabled</span>
</span>
{:else}
Browse, edit, and manage files in the volume.
{/if}
</Dialog.Description>
</Dialog.Header>
<div class="flex-1 overflow-hidden border rounded-lg">
<FileBrowserPanel
{volumeName}
envId={envId ?? undefined}
canEdit={true}
onUsageChange={handleUsageChange}
/>
</div>
</Dialog.Content>
</Dialog.Root>

View File

@@ -0,0 +1,167 @@
<script lang="ts">
import * as Dialog from '$lib/components/ui/dialog';
import { Button } from '$lib/components/ui/button';
import { Badge } from '$lib/components/ui/badge';
import { Loader2, HardDrive } from 'lucide-svelte';
import { currentEnvironment, appendEnvParam } from '$lib/stores/environment';
import { formatDateTime } from '$lib/stores/settings';
interface Props {
open: boolean;
volumeName: string;
}
let { open = $bindable(), volumeName }: Props = $props();
let loading = $state(true);
let error = $state('');
let volumeData = $state<any>(null);
$effect(() => {
if (open && volumeName) {
fetchVolumeInspect();
}
});
async function fetchVolumeInspect() {
loading = true;
error = '';
try {
const envId = $currentEnvironment?.id ?? null;
const response = await fetch(appendEnvParam(`/api/volumes/${encodeURIComponent(volumeName)}/inspect`, envId));
if (!response.ok) {
throw new Error('Failed to fetch volume details');
}
volumeData = await response.json();
} catch (err: any) {
error = err.message || 'Failed to load volume details';
console.error('Failed to fetch volume inspect:', err);
} finally {
loading = false;
}
}
function formatDate(dateString: string): string {
if (!dateString) return 'N/A';
return formatDateTime(dateString);
}
</script>
<Dialog.Root bind:open>
<Dialog.Content class="max-w-4xl h-[90vh] flex flex-col">
<Dialog.Header class="shrink-0">
<Dialog.Title class="flex items-center gap-2">
<HardDrive class="w-5 h-5" />
Volume details: <span class="text-muted-foreground font-normal break-all">{volumeName}</span>
</Dialog.Title>
</Dialog.Header>
<div class="flex-1 overflow-auto space-y-4 min-h-0">
{#if loading}
<div class="flex items-center justify-center py-8">
<Loader2 class="w-6 h-6 animate-spin text-muted-foreground" />
</div>
{:else if error}
<div class="text-sm text-red-600 dark:text-red-400 p-3 bg-red-50 dark:bg-red-950 rounded">
{error}
</div>
{:else if volumeData}
<!-- Basic Info -->
<div class="space-y-3">
<h3 class="text-sm font-semibold">Basic information</h3>
<div class="grid grid-cols-2 gap-3 text-sm">
<div>
<p class="text-muted-foreground">Name</p>
<code class="text-xs break-all">{volumeData.Name}</code>
</div>
<div>
<p class="text-muted-foreground">Driver</p>
<Badge variant="outline">{volumeData.Driver}</Badge>
</div>
<div>
<p class="text-muted-foreground">Scope</p>
<Badge variant="secondary">{volumeData.Scope}</Badge>
</div>
<div>
<p class="text-muted-foreground">Created</p>
<p class="text-xs">{formatDate(volumeData.CreatedAt)}</p>
</div>
</div>
</div>
<!-- Mountpoint -->
<div class="space-y-2">
<h3 class="text-sm font-semibold">Mountpoint</h3>
<div class="p-2 bg-muted rounded">
<code class="text-xs break-all">{volumeData.Mountpoint}</code>
</div>
<p class="text-xs text-muted-foreground">
The location on the host where the volume data is stored
</p>
</div>
<!-- Driver Options -->
{#if volumeData.Options && Object.keys(volumeData.Options).length > 0}
<div class="space-y-3">
<h3 class="text-sm font-semibold">Driver options</h3>
<div class="space-y-1">
{#each Object.entries(volumeData.Options) as [key, value]}
<div class="flex justify-between text-sm p-2 bg-muted rounded">
<code class="text-muted-foreground">{key}</code>
<code class="break-all ml-2">{value}</code>
</div>
{/each}
</div>
</div>
{:else}
<div class="space-y-2">
<h3 class="text-sm font-semibold">Driver options</h3>
<p class="text-sm text-muted-foreground">No driver options configured</p>
</div>
{/if}
<!-- Labels -->
{#if volumeData.Labels && Object.keys(volumeData.Labels).length > 0}
<div class="space-y-3">
<h3 class="text-sm font-semibold">Labels</h3>
<div class="space-y-1">
{#each Object.entries(volumeData.Labels) as [key, value]}
<div class="flex justify-between text-sm p-2 bg-muted rounded">
<code class="text-muted-foreground">{key}</code>
<code class="break-all ml-2">{value}</code>
</div>
{/each}
</div>
</div>
{/if}
<!-- Status -->
{#if volumeData.Status}
<div class="space-y-3">
<h3 class="text-sm font-semibold">Status</h3>
<div class="space-y-1">
{#each Object.entries(volumeData.Status) as [key, value]}
<div class="flex justify-between text-sm p-2 bg-muted rounded">
<span class="text-muted-foreground">{key}</span>
<span>{value}</span>
</div>
{/each}
</div>
</div>
{/if}
<!-- Usage Warning -->
<div class="p-3 bg-yellow-50 dark:bg-yellow-950/30 border border-yellow-200 dark:border-yellow-800 rounded">
<p class="text-xs text-yellow-800 dark:text-yellow-200">
<strong>Note:</strong> Removing this volume will permanently delete all data stored in it.
Make sure no containers are using this volume before removal.
</p>
</div>
{/if}
</div>
<Dialog.Footer class="shrink-0">
<Button variant="outline" onclick={() => (open = false)}>Close</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>