Skip to content

Modern Docker Management, Designed for Everyone

feat: mass-delete images, volumes, and networks (#69)

Kyle Mendellb56303e60e6d
diff --git a/package.json b/package.json
index 537fb51fd..7d9c860c9 100644
--- a/package.json
+++ b/package.json
@@ -39,7 +39,7 @@
"tailwind-variants": "^1.0.0",
"tailwindcss": "^4.0.0",
"tailwindcss-animate": "^1.0.7",
- "typescript": "^5.0.0",
+ "typescript": "^5.5.0",
"typescript-eslint": "^8.31.0",
"vite": "^6.3.3",
"zod": "^3.24.3"
diff --git a/src/app.css b/src/app.css
index 4bb0c01e6..5cd5a96b4 100644
--- a/src/app.css
+++ b/src/app.css
@@ -3,6 +3,52 @@
@config '../tailwind.config.ts';
@layer base {
+ :root {
+ --background: 0 0% 100%;
+ --foreground: 224 71.4% 4.1%;
+ --card: 0 0% 100%;
+ --card-foreground: 224 71.4% 4.1%;
+ --popover: 0 0% 100%;
+ --popover-foreground: 224 71.4% 4.1%;
+ --primary: 262.1 83.3% 57.8%;
+ --primary-foreground: 210 20% 98%;
+ --secondary: 220 14.3% 95.9%;
+ --secondary-foreground: 220.9 39.3% 11%;
+ --muted: 220 14.3% 95.9%;
+ --muted-foreground: 220 8.9% 46.1%;
+ --accent: 220 14.3% 95.9%;
+ --accent-foreground: 220.9 39.3% 11%;
+ --destructive: 0 72.22% 50.59%;
+ --destructive-foreground: 210 20% 98%;
+ --border: 220 13% 91%;
+ --input: 220 13% 91%;
+ --ring: 262.1 83.3% 57.8%;
+ --radius: 1rem;
+ }
+ .dark {
+ --background: 224 71.4% 4.1%;
+ --foreground: 210 20% 98%;
+ --card: 224 71.4% 4.1%;
+ --card-foreground: 210 20% 98%;
+ --popover: 224 71.4% 4.1%;
+ --popover-foreground: 210 20% 98%;
+ --primary: 263.4 70% 50.4%;
+ --primary-foreground: 210 20% 98%;
+ --secondary: 215 27.9% 16.9%;
+ --secondary-foreground: 210 20% 98%;
+ --muted: 215 27.9% 16.9%;
+ --muted-foreground: 217.9 10.6% 64.9%;
+ --accent: 215 27.9% 16.9%;
+ --accent-foreground: 210 20% 98%;
+ --destructive: 0 62.8% 30.6%;
+ --destructive-foreground: 210 20% 98%;
+ --border: 215 27.9% 16.9%;
+ --input: 215 27.9% 16.9%;
+ --ring: 263.4 70% 50.4%;
+ }
+}
+
+/* @layer base {
:root {
--background: 0 0% 100%;
--foreground: 0 0% 3.9%;
@@ -46,7 +92,7 @@
--input: 0 0% 14.9%;
--ring: 0 0% 83.1%;
}
-}
+} */
@layer base {
* {
diff --git a/src/app.html b/src/app.html
index 78dd7db3b..72f28e23d 100644
--- a/src/app.html
+++ b/src/app.html
@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="utf-8" />
- <link rel="icon" href="%sveltekit.assets%/img/nautix_logo_new.png" />
+ <link rel="icon" href="%sveltekit.assets%/img/arcane.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
diff --git a/src/lib/components/action-buttons.svelte b/src/lib/components/action-buttons.svelte
index a6aaf7ac9..90bb170da 100644
--- a/src/lib/components/action-buttons.svelte
+++ b/src/lib/components/action-buttons.svelte
@@ -47,8 +47,7 @@
type="submit"
variant="default"
disabled={loading.start}
- size="sm"
- class="font-medium h-9"
+ class="font-medium "
formaction={formAction || "?/start"}
>
{#if loading.start}
@@ -63,14 +62,13 @@
type="submit"
variant="secondary"
disabled={loading.stop}
- size="sm"
- class="font-medium h-9"
+ class="font-medium "
formaction={formAction || "?/stop"}
>
{#if loading.stop}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ <Loader2 class="w-4 h-4 animate-spin" />
{:else}
- <StopCircle class="w-4 h-4 mr-2" />
+ <StopCircle class="w-4 h-4" />
{/if}
Stop
</Button>
@@ -79,16 +77,15 @@
type="submit"
variant="outline"
disabled={loading.restart}
- size="sm"
- class="font-medium h-9"
+ class="font-medium "
formaction={formAction || "?/restart"}
name="action"
value="restart"
>
{#if loading.restart}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ <Loader2 class="w-4 h-4 animate-spin" />
{:else}
- <RotateCcw class="w-4 h-4 mr-2" />
+ <RotateCcw class="w-4 h-4" />
{/if}
Restart
</Button>
@@ -99,8 +96,7 @@
type="submit"
variant="destructive"
disabled={loading.remove}
- size="sm"
- class="font-medium h-9"
+ class="font-medium "
formaction={formAction || "?/remove"}
onclick={(e) => {
if (!confirm(`Are you sure you want to remove this ${type}?`)) {
@@ -110,9 +106,9 @@
}}
>
{#if loading.remove}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ <Loader2 class="w-4 h-4 animate-spin" />
{:else}
- <Trash2 class="w-4 h-4 mr-2" />
+ <Trash2 class="w-4 h-4" />
{/if}
Remove
</Button>
@@ -122,14 +118,13 @@
type="submit"
variant="outline"
disabled={loading.pull}
- size="sm"
- class="font-medium h-9"
+ class="font-medium"
formaction={formAction || "?/pull"}
>
{#if loading.pull}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ <Loader2 class="w-4 h-4 animate-spin" />
{:else}
- <Download class="w-4 h-4 mr-2" />
+ <Download class="w-4 h-4" />
{/if}
Pull
</Button>
@@ -138,8 +133,7 @@
type="submit"
variant="destructive"
disabled={loading.remove}
- size="sm"
- class="font-medium h-9"
+ class="font-medium "
formaction={formAction || "?/remove"}
onclick={(e) => {
if (!confirm(`Are you sure you want to remove this ${type}?`)) {
@@ -149,9 +143,9 @@
}}
>
{#if loading.remove}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ <Loader2 class="w-4 h-4 animate-spin" />
{:else}
- <Trash2 class="w-4 h-4 mr-2" />
+ <Trash2 class="w-4 h-4" />
{/if}
Remove
</Button>
diff --git a/src/lib/components/badges/unused-text-badge.svelte b/src/lib/components/badges/unused-text-badge.svelte
index 4e9b6f6b9..8d7cf5460 100644
--- a/src/lib/components/badges/unused-text-badge.svelte
+++ b/src/lib/components/badges/unused-text-badge.svelte
@@ -1,8 +1,12 @@
<script lang="ts">
import StatusBadge from "./status-badge.svelte";
- export let name: string;
- export let inUse: boolean | undefined;
+ interface Props {
+ name: string;
+ inUse: boolean | undefined;
+ }
+
+ let { name, inUse }: Props = $props();
</script>
<div class="flex items-center gap-2">
diff --git a/src/lib/components/docker/ImageRow.svelte b/src/lib/components/docker/ImageRow.svelte
index e261c4fbc..a20118437 100644
--- a/src/lib/components/docker/ImageRow.svelte
+++ b/src/lib/components/docker/ImageRow.svelte
@@ -2,13 +2,17 @@
import { Button } from "$lib/components/ui/button/index.js";
import { Trash2, Info } from "@lucide/svelte";
- export let image: {
+ interface Props {
+ image: {
id: string;
repo: string;
tag: string;
size: string;
created?: string;
};
+ }
+
+ let { image }: Props = $props();
</script>
<tr class="border-b">
diff --git a/src/lib/components/navbar.svelte b/src/lib/components/navbar.svelte
index a982cfe5a..d5bc2e0e7 100644
--- a/src/lib/components/navbar.svelte
+++ b/src/lib/components/navbar.svelte
@@ -14,7 +14,7 @@
ExternalLink, // Add this for the update link icon
type Icon as IconType,
} from "@lucide/svelte";
- import { page } from "$app/stores";
+ import { page } from "$app/state";
import { fly } from "svelte/transition";
import { Button } from "$lib/components/ui/button/index.js";
import { Separator } from "$lib/components/ui/separator/index.js";
@@ -104,7 +104,7 @@
>
<div class="flex-shrink-0">
<img
- src="/img/nautix_logo_new.png"
+ src="/img/arcane.png"
alt="Arcane"
class="h-15 w-15"
width="30"
@@ -150,8 +150,8 @@
>
{#each items as item}
{@const isActive =
- $page.url.pathname === item.href ||
- ($page.url.pathname.startsWith(item.href) && item.href !== "/")}
+ page.url.pathname === item.href ||
+ (page.url.pathname.startsWith(item.href) && item.href !== "/")}
{@const Icon = item.icon}
<a
diff --git a/src/lib/components/ui/radio-group/index.ts b/src/lib/components/ui/radio-group/index.ts
new file mode 100644
index 000000000..90b33fe5b
--- /dev/null
+++ b/src/lib/components/ui/radio-group/index.ts
@@ -0,0 +1,10 @@
+import Root from "./radio-group.svelte";
+import Item from "./radio-group-item.svelte";
+
+export {
+ Root,
+ Item,
+ //
+ Root as RadioGroup,
+ Item as RadioGroupItem,
+};
diff --git a/src/lib/components/ui/radio-group/radio-group-item.svelte b/src/lib/components/ui/radio-group/radio-group-item.svelte
new file mode 100644
index 000000000..bab22c0f1
--- /dev/null
+++ b/src/lib/components/ui/radio-group/radio-group-item.svelte
@@ -0,0 +1,28 @@
+<script lang="ts">
+ import { RadioGroup as RadioGroupPrimitive, type WithoutChildrenOrChild } from "bits-ui";
+ import Circle from "@lucide/svelte/icons/circle";
+ import { cn } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ ...restProps
+ }: WithoutChildrenOrChild<RadioGroupPrimitive.ItemProps> = $props();
+</script>
+
+<RadioGroupPrimitive.Item
+ bind:ref
+ class={cn(
+ "border-primary text-primary ring-offset-background focus-visible:ring-ring aspect-square size-4 rounded-full border focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
+ className
+ )}
+ {...restProps}
+>
+ {#snippet children({ checked })}
+ <div class="flex items-center justify-center">
+ {#if checked}
+ <Circle class="size-2.5 fill-current text-current" />
+ {/if}
+ </div>
+ {/snippet}
+</RadioGroupPrimitive.Item>
diff --git a/src/lib/components/ui/radio-group/radio-group.svelte b/src/lib/components/ui/radio-group/radio-group.svelte
new file mode 100644
index 000000000..5180b313c
--- /dev/null
+++ b/src/lib/components/ui/radio-group/radio-group.svelte
@@ -0,0 +1,13 @@
+<script lang="ts">
+ import { RadioGroup as RadioGroupPrimitive } from "bits-ui";
+ import { cn } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ value = $bindable(""),
+ ...restProps
+ }: RadioGroupPrimitive.RootProps = $props();
+</script>
+
+<RadioGroupPrimitive.Root bind:ref bind:value class={cn("grid gap-2", className)} {...restProps} />
diff --git a/src/lib/components/universal-table.svelte b/src/lib/components/universal-table.svelte
index 5582f0f1e..8323bd2ce 100644
--- a/src/lib/components/universal-table.svelte
+++ b/src/lib/components/universal-table.svelte
@@ -6,6 +6,7 @@
type SortingState,
getFilteredRowModel,
type ColumnFiltersState,
+ type RowData,
} from "@tanstack/table-core";
import {
createSvelteTable,
@@ -25,12 +26,13 @@
let {
data,
columns,
+ idKey,
features = {},
display = {},
pagination = {},
sort = {},
selectedIds = $bindable<string[]>([]),
- }: UniversalTableProps<TData> = $props();
+ }: UniversalTableProps<TData> & { idKey?: keyof TData } = $props();
let {
sorting: enableSorting = true,
@@ -92,6 +94,11 @@
return data;
},
columns,
+ getRowId: idKey
+ ? (originalRow: TData, index: number, parent?: RowData) => {
+ return String(originalRow[idKey]);
+ }
+ : undefined,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: enableSorting ? getSortedRowModel() : undefined,
diff --git a/src/lib/components/yaml-editor.svelte b/src/lib/components/yaml-editor.svelte
index 5ea5f8c6d..900be4e50 100644
--- a/src/lib/components/yaml-editor.svelte
+++ b/src/lib/components/yaml-editor.svelte
@@ -14,6 +14,7 @@
height = "400px",
placeholder = "Enter YAML content",
forceDarkTheme = true,
+ readOnly = false,
} = $props();
let darkMode = $state(forceDarkTheme || false);
@@ -55,6 +56,8 @@
]);
function handleChange(e: Event) {
+ // No need to dispatch if readOnly
+ if (readOnly) return;
const target = e.target as HTMLInputElement;
value = target.value;
dispatch("change", { value });
@@ -73,8 +76,17 @@
fontSize: "14px",
fontFamily: "JetBrains Mono, Menlo, Monaco, Consolas, monospace",
},
+ // Optionally add styles for read-only state
+ "&.cm-editor[contenteditable=false]": {
+ backgroundColor: "#f8f8f8", // Example: slightly different background
+ cursor: "not-allowed",
+ },
+ ".cm-content[contenteditable=false]": {
+ cursor: "not-allowed",
+ },
}}
{placeholder}
+ readonly={readOnly}
/>
</div>
{/if}
diff --git a/src/lib/services/compose.ts b/src/lib/services/compose.ts
index 4bbec96cc..af6d3ba28 100644
--- a/src/lib/services/compose.ts
+++ b/src/lib/services/compose.ts
@@ -310,7 +310,8 @@ export async function createStack(
name: string,
composeContent: string
): Promise<Stack> {
- const stackDir = await getStackDir(nanoid());
+ const stackId = nanoid(); // Generate ID here
+ const stackDir = await getStackDir(stackId); // Use the generated ID
const composePath = join(stackDir, "docker-compose.yml");
const metaPath = join(stackDir, "meta.json");
@@ -327,18 +328,42 @@ export async function createStack(
fs.writeFile(metaPath, JSON.stringify(meta, null, 2), "utf8"),
]);
+ // Parse the compose content to estimate service count initially
+ let serviceCount = 0;
+ try {
+ const composeData = yaml.load(composeContent) as any;
+ if (composeData && composeData.services) {
+ serviceCount = Object.keys(composeData.services).length;
+ }
+ } catch (parseErr) {
+ console.warn(
+ `Could not parse compose file during creation for stack ${stackId}:`,
+ parseErr
+ );
+ }
+
return {
- id: nanoid(),
+ id: stackId, // Return the generated ID
name: meta.name,
- serviceCount: 0,
+ serviceCount: serviceCount, // Initial estimate
runningCount: 0,
status: "stopped",
createdAt: meta.createdAt,
updatedAt: meta.updatedAt,
+ composeContent: composeContent, // Include content for immediate use if needed
};
} catch (err) {
console.error("Error creating stack:", err);
- throw new Error("Failed to create stack");
+ // Attempt to clean up if creation failed partially
+ try {
+ await fs.rm(stackDir, { recursive: true, force: true });
+ } catch (cleanupErr) {
+ console.error(
+ `Failed to cleanup partially created stack directory ${stackDir}:`,
+ cleanupErr
+ );
+ }
+ throw new Error("Failed to create stack files");
}
}
diff --git a/src/lib/services/docker-service.ts b/src/lib/services/docker-service.ts
index f7aa4ce17..36bfc61be 100644
--- a/src/lib/services/docker-service.ts
+++ b/src/lib/services/docker-service.ts
@@ -1,5 +1,6 @@
import Docker from "dockerode";
import type { VolumeInspectInfo, VolumeCreateOptions } from "dockerode";
+import type { NetworkInspectInfo, NetworkCreateOptions } from "dockerode"; // Add NetworkCreateOptions
import { getSettings } from "$lib/services/settings-service";
import type {
DockerConnectionOptions,
@@ -612,6 +613,45 @@ export async function isImageInUse(imageId: string): Promise<boolean> {
}
}
+/**
+ * Prunes unused Docker images.
+ * @param mode - Mode of pruning ('all' or 'dangling').
+ * @returns Information about reclaimed space.
+ */
+export async function pruneImages(mode: "all" | "dangling" = "all"): Promise<{
+ ImagesDeleted: Docker.ImageRemoveInfo[] | null;
+ SpaceReclaimed: number;
+}> {
+ try {
+ const docker = getDockerClient();
+ const filterValue = mode === "all" ? "false" : "true";
+ const logMessage =
+ mode === "all"
+ ? "Pruning all unused images (docker image prune -a)..."
+ : "Pruning dangling images (docker image prune)...";
+
+ console.log(`Docker Service: ${logMessage}`);
+
+ const pruneOptions = {
+ filters: { dangling: [filterValue] },
+ };
+
+ const result = await docker.pruneImages(pruneOptions); // Use the options object
+
+ console.log(
+ `Docker Service: Image prune complete. Space reclaimed: ${result.SpaceReclaimed}`
+ );
+ return result;
+ } catch (error: any) {
+ console.error("Docker Service: Error pruning images:", error);
+ throw new Error(
+ `Failed to prune images using host "${dockerHost}". ${
+ error.message || error.reason || ""
+ }`
+ );
+ }
+}
+
// Define and export the type returned by listNetworks
export type ServiceNetwork = {
id: string;
@@ -649,6 +689,86 @@ export async function listNetworks(): Promise<ServiceNetwork[]> {
}
}
+/**
+ * Removes a Docker network.
+ * @param networkId - The ID or name of the network to remove.
+ */
+export async function removeNetwork(networkId: string): Promise<void> {
+ try {
++ const DEFAULT_NETWORKS = new Set(["host", "bridge", "none", "ingress"]);
++ if (DEFAULT_NETWORKS.has(networkId)) {
++ throw new Error(`Network "${networkId}" is managed by Docker and cannot be removed.`);
++ }
+ const docker = getDockerClient();
+ const network = docker.getNetwork(networkId);
+ await network.remove();
+ console.log(`Docker Service: Network "${networkId}" removed successfully.`);
+ } catch (error: any) {
+ console.error(
+ `Docker Service: Error removing network "${networkId}":`,
+ error
+ );
+ if (error.statusCode === 404) {
+ throw new Error(`Network "${networkId}" not found.`);
+ }
+ if (error.statusCode === 409) {
+ // 409 Conflict usually means it's in use or predefined
+ throw new Error(
+ `Network "${networkId}" cannot be removed (possibly in use or predefined).`
+ );
+ }
+ throw new Error(
+ `Failed to remove network "${networkId}" using host "${dockerHost}". ${
+ error.message || error.reason || ""
+ }`
+ );
+ }
+}
+
+/**
+ * Creates a Docker network.
+ * @param options - Options for creating the network (e.g., Name, Driver, Labels, CheckDuplicate, Internal, IPAM).
+ */
+export async function createNetwork(
+ options: NetworkCreateOptions
+): Promise<NetworkInspectInfo> {
+ try {
+ const docker = getDockerClient();
+ console.log(
+ `Docker Service: Creating network "${options.Name}"...`,
+ options
+ );
+
+ // Dockerode's createNetwork returns the Network object, we need to inspect it after creation
+ const network = await docker.createNetwork(options);
+
+ // Inspect the newly created network to get full details
+ const inspectInfo = await network.inspect();
+
+ console.log(
+ `Docker Service: Network "${options.Name}" (ID: ${inspectInfo.Id}) created successfully.`
+ );
+ return inspectInfo; // Return the detailed inspect info
+ } catch (error: any) {
+ console.error(
+ `Docker Service: Error creating network "${options.Name}":`,
+ error
+ );
+ // Check for specific Docker errors
+ if (error.statusCode === 409) {
+ // Could be duplicate name if CheckDuplicate was true, or other conflicts
+ throw new Error(
+ `Network "${options.Name}" may already exist or conflict with an existing configuration.`
+ );
+ }
+ throw new Error(
+ `Failed to create network "${options.Name}" using host "${dockerHost}". ${
+ error.message || error.reason || ""
+ }`
+ );
+ }
+}
+
// Define and export the type returned by listVolumes
export type ServiceVolume = {
name: string;
diff --git a/src/lib/services/settings-service.ts b/src/lib/services/settings-service.ts
index 99cb2919c..17b2d22a4 100644
--- a/src/lib/services/settings-service.ts
+++ b/src/lib/services/settings-service.ts
@@ -24,6 +24,7 @@ export const DEFAULT_SETTINGS: SettingsData = {
autoUpdate: false,
pollingEnabled: true,
pollingInterval: 10,
+ pruneMode: "all",
stacksDirectory: path.resolve(BASE_PATH, "stacks"),
externalServices: {
valkey: {
diff --git a/src/lib/types/image.ts b/src/lib/types/image.ts
new file mode 100644
index 000000000..802c7c599
--- /dev/null
+++ b/src/lib/types/image.ts
@@ -0,0 +1,5 @@
+import type { ServiceImage } from "$lib/services/docker-service";
+
+export type EnhancedImageInfo = ServiceImage & {
+ inUse: boolean;
+};
diff --git a/src/lib/types/settings.ts b/src/lib/types/settings.ts
index d7b968522..0314c872d 100644
--- a/src/lib/types/settings.ts
+++ b/src/lib/types/settings.ts
@@ -4,6 +4,7 @@ export interface SettingsData {
pollingEnabled: boolean;
pollingInterval: number;
stacksDirectory: string;
+ pruneMode: "all" | "dangling";
registryCredentials?: Array<{
url: string;
username: string;
diff --git a/src/lib/utils/form.utils.ts b/src/lib/utils/form.utils.ts
new file mode 100644
index 000000000..0be79594a
--- /dev/null
+++ b/src/lib/utils/form.utils.ts
@@ -0,0 +1,6 @@
+export function preventDefault(fn: (event: Event) => any) {
+ return function (this: any, event: Event) {
+ event.preventDefault();
+ fn.call(this, event);
+ };
+}
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index 3f1346023..fcd3f165e 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -1,15 +1,16 @@
+<!-- @migration task: review uses of `navigating` -->
<script lang="ts">
import "../app.css";
import { ModeWatcher } from "mode-watcher";
import Nav from "$lib/components/navbar.svelte";
import { Toaster } from "$lib/components/ui/sonner/index.js";
- import { navigating } from "$app/stores";
+ import { navigating } from "$app/state";
let { children, data } = $props();
const versionInformation = data.versionInformation;
- const isNavigating = $derived($navigating !== null);
+ const isNavigating = $derived(navigating !== null);
</script>
<svelte:head><title>Arcane</title></svelte:head>
diff --git a/src/routes/api/containers/+server.ts b/src/routes/api/containers/+server.ts
index 5b691b954..30fe82bbd 100644
--- a/src/routes/api/containers/+server.ts
+++ b/src/routes/api/containers/+server.ts
@@ -1,4 +1,4 @@
-import { json, redirect } from "@sveltejs/kit";
+import { json } from "@sveltejs/kit";
import type { RequestHandler } from "./$types";
import { createContainer } from "$lib/services/docker-service";
import type { ContainerConfig } from "$lib/types/docker";
diff --git a/src/routes/api/images/prune/+server.ts b/src/routes/api/images/prune/+server.ts
new file mode 100644
index 000000000..954f3de46
--- /dev/null
+++ b/src/routes/api/images/prune/+server.ts
@@ -0,0 +1,29 @@
+import { json, error } from "@sveltejs/kit";
+import type { RequestHandler } from "./$types";
+import { pruneImages } from "$lib/services/docker-service";
+import { getSettings } from "$lib/services/settings-service";
+import { formatBytes } from "$lib/utils";
+
+export const POST: RequestHandler = async () => {
+ try {
+ const settings = await getSettings();
+ const pruneMode = settings.pruneMode;
+
+ const result = await pruneImages(pruneMode); // Pass the mode
+ const spaceReclaimedFormatted = formatBytes(result.SpaceReclaimed || 0);
+ const message =
+ result.ImagesDeleted && result.ImagesDeleted.length > 0
+ ? `Successfully pruned ${result.ImagesDeleted.length} image(s). Space reclaimed: ${spaceReclaimedFormatted}.`
+ : `No unused images found to prune. Space reclaimed: ${spaceReclaimedFormatted}.`;
+
+ return json({
+ success: true,
+ message: message,
+ spaceReclaimed: result.SpaceReclaimed,
+ imagesDeletedCount: result.ImagesDeleted?.length || 0,
+ });
+ } catch (err: any) {
+ console.error("API Error pruning images:", err);
+ throw error(500, err.message || "Failed to prune images");
+ }
+};
diff --git a/src/routes/api/networks/[id]/+server.ts b/src/routes/api/networks/[id]/+server.ts
new file mode 100644
index 000000000..1a8a19fa6
--- /dev/null
+++ b/src/routes/api/networks/[id]/+server.ts
@@ -0,0 +1,26 @@
+import { json, error } from "@sveltejs/kit";
+import type { RequestHandler } from "./$types";
+import { removeNetwork } from "$lib/services/docker-service";
+
+export const DELETE: RequestHandler = async ({ params }) => {
+ const networkId = params.id;
+
+ if (!networkId) {
+ throw error(400, "Network ID is required");
+ }
+
+ try {
+ await removeNetwork(networkId);
+ return json({ success: true, message: `Network ${networkId} deleted.` });
+ } catch (err: any) {
+ console.error(`API Error removing network ${networkId}:`, err);
+ // Pass specific error messages from the service
+ if (err.message.includes("not found")) {
+ throw error(404, err.message);
+ }
+ if (err.message.includes("cannot be removed")) {
+ throw error(409, err.message); // 409 Conflict
+ }
+ throw error(500, err.message || "Failed to remove network");
+ }
+};
diff --git a/src/routes/api/networks/create/+server.ts b/src/routes/api/networks/create/+server.ts
new file mode 100644
index 000000000..f20f6e7ab
--- /dev/null
+++ b/src/routes/api/networks/create/+server.ts
@@ -0,0 +1,47 @@
+import { json, error } from "@sveltejs/kit";
+import type { RequestHandler } from "./$types";
+import { createNetwork } from "$lib/services/docker-service";
+import type { NetworkCreateOptions } from "dockerode";
+
+export const POST: RequestHandler = async ({ request }) => {
+ try {
+ const options: NetworkCreateOptions = await request.json();
+
+ if (!options.Name) {
+ throw error(400, "Network name (Name) is required");
+ }
+
+ // Add default CheckDuplicate if not provided, common use case
+ if (options.CheckDuplicate === undefined) {
+ options.CheckDuplicate = true;
+ }
+
+ // Call the service function
+ const networkInfo = await createNetwork(options);
+
+ // Return the details of the created network
+ return json({
+ success: true,
+ network: {
+ // Map inspectInfo to ServiceNetwork shape if needed, or return full info
+ id: networkInfo.Id,
+ name: networkInfo.Name,
+ driver: networkInfo.Driver,
+ scope: networkInfo.Scope,
+ subnet: networkInfo.IPAM?.Config?.[0]?.Subnet ?? null,
+ gateway: networkInfo.IPAM?.Config?.[0]?.Gateway ?? null,
+ created: networkInfo.Created,
+ // Add other relevant fields from NetworkInspectInfo if desired
+ },
+ message: `Network "${networkInfo.Name}" created successfully.`,
+ });
+ } catch (err: any) {
+ // Handle specific SvelteKit errors or re-throw them
+ if (err.status >= 400 && err.status < 600) {
+ throw err;
+ }
+ // Handle errors from createNetwork
+ console.error("API Error creating network:", err);
+ throw error(500, err.message || "Failed to create network");
+ }
+};
diff --git a/src/routes/api/stacks/create/+server.ts b/src/routes/api/stacks/create/+server.ts
new file mode 100644
index 000000000..a8c06628f
--- /dev/null
+++ b/src/routes/api/stacks/create/+server.ts
@@ -0,0 +1,35 @@
+import { json, error } from "@sveltejs/kit";
+import type { RequestHandler } from "./$types";
+import { createStack } from "$lib/services/compose";
+
+export const POST: RequestHandler = async ({ request }) => {
+ try {
+ const body = await request.json();
+ const name = body.name?.toString();
+ const composeContent = body.composeContent?.toString();
+
+ if (!name) {
+ throw error(400, "Stack name is required");
+ }
+
+ if (!composeContent) {
+ throw error(400, "Compose file content is required");
+ }
+
+ const newStack = await createStack(name, composeContent);
+
+ return json({
+ success: true,
+ stack: newStack,
+ message: `Stack "${newStack.name}" created successfully.`,
+ });
+ } catch (err: any) {
+ // Handle specific SvelteKit errors or re-throw them
+ if (err.status >= 400 && err.status < 600) {
+ throw err;
+ }
+ // Handle errors from createStack
+ console.error("API Error creating stack:", err);
+ throw error(500, err.message || "Failed to create stack");
+ }
+};
diff --git a/src/routes/containers/+page.svelte b/src/routes/containers/+page.svelte
index c277464db..450c50bf9 100644
--- a/src/routes/containers/+page.svelte
+++ b/src/routes/containers/+page.svelte
@@ -10,17 +10,13 @@
import type { ContainerConfig } from "$lib/types/docker";
import { enhance } from "$app/forms";
- // Server data from load function
let { data, form } = $props();
- const { containers } = data;
-
+ let containers = $state(data.containers);
let isRefreshing = $state(false);
let selectedIds = $state([]);
let isCreateDialogOpen = $state(false);
let isCreatingContainer = $state(false);
let containerData = $state<ContainerConfig | null>(null);
-
- // Add a form reference
let formRef: HTMLFormElement;
// Calculate running containers
@@ -50,13 +46,16 @@
}
});
- // Simple refresh now - this just triggers a new SSR call
async function refreshData() {
isRefreshing = true;
- await invalidateAll();
- setTimeout(() => {
- isRefreshing = false;
- }, 500);
+ try {
+ await invalidateAll();
+ containers = data.containers;
+ } finally {
+ setTimeout(() => {
+ isRefreshing = false;
+ }, 300);
+ }
}
function openCreateDialog() {
@@ -138,7 +137,7 @@
>
</div>
<div class="flex items-center gap-2">
- <Button variant="outline" size="sm" onclick={openCreateDialog}>
+ <Button variant="secondary" onclick={openCreateDialog}>
<Plus class="w-4 h-4" />
Create Container
</Button>
@@ -169,11 +168,11 @@
the Docker CLI
</p>
<div class="flex gap-3 mt-4">
- <Button variant="outline" size="sm" onclick={refreshData}>
+ <Button variant="secondary" onclick={refreshData}>
<RefreshCw class="h-4 w-4" />
Refresh
</Button>
- <Button variant="outline" size="sm" onclick={openCreateDialog}>
+ <Button variant="secondary" onclick={openCreateDialog}>
<Plus class="h-4 w-4" />
Create Container
</Button>
@@ -190,7 +189,7 @@
isCreatingContainer = false;
if (result.type === "success") {
isCreateDialogOpen = false;
- await invalidateAll();
+ await refreshData();
}
};
}}
diff --git a/src/routes/images/+page.server.ts b/src/routes/images/+page.server.ts
index 86d029f70..2a0431ecb 100644
--- a/src/routes/images/+page.server.ts
+++ b/src/routes/images/+page.server.ts
@@ -1,11 +1,6 @@
import type { PageServerLoad } from "./$types";
import { listImages, isImageInUse } from "$lib/services/docker-service";
-import type { ServiceImage } from "$lib/services/docker-service";
-
-// Enhanced type with usage info
-type EnhancedImageInfo = ServiceImage & {
- inUse: boolean;
-};
+import type { EnhancedImageInfo } from "$lib/types/image";
type ImageData = {
images: EnhancedImageInfo[];
diff --git a/src/routes/images/+page.svelte b/src/routes/images/+page.svelte
index 3358f5383..97baa7a85 100644
--- a/src/routes/images/+page.svelte
+++ b/src/routes/images/+page.svelte
@@ -1,27 +1,50 @@
<script lang="ts">
import type { PageData } from "./$types";
+ import type { EnhancedImageInfo } from "$lib/types/image";
import UniversalTable from "$lib/components/universal-table.svelte";
import { columns } from "./columns";
import { Button } from "$lib/components/ui/button/index.js";
- import { Download, AlertCircle, RefreshCw, HardDrive } from "@lucide/svelte";
+ import {
+ Download,
+ AlertCircle,
+ RefreshCw,
+ HardDrive,
+ Trash2,
+ Loader2,
+ ChevronDown,
+ CopyX,
+ } from "@lucide/svelte";
import * as Alert from "$lib/components/ui/alert/index.js";
import * as Card from "$lib/components/ui/card/index.js";
import { invalidateAll } from "$app/navigation";
import { toast } from "svelte-sonner";
import PullImageDialog from "./pull-image-dialog.svelte";
- import { formatBytes } from "$lib/utils";
+ import { formatBytes, cn } from "$lib/utils";
+ import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js";
+ import * as Dialog from "$lib/components/ui/dialog/index.js";
let { data }: { data: PageData } = $props();
- const { images, error } = data;
- let selectedIds = $state([]);
+ let images = $state<EnhancedImageInfo[]>(data.images || []);
+ let error = $state(data.error);
+ let selectedIds = $state<string[]>([]);
let isRefreshing = $state(false);
let isPullDialogOpen = $state(false);
let isPullingImage = $state(false);
let pullProgress = $state(0);
- const totalImages = $derived(images?.length || 0);
+ let isDeletingSelected = $state(false);
+ let isConfirmDeleteDialogOpen = $state(false);
+
+ let isPruning = $state(false);
+ let isConfirmPruneDialogOpen = $state(false);
+
+ $effect(() => {
+ images = data.images || [];
+ error = data.error;
+ });
+ const totalImages = $derived(images?.length || 0);
const totalSize = $derived(
images?.reduce((acc, img) => acc + (img.size || 0), 0) || 0
);
@@ -34,12 +57,13 @@
const { imageRef, tag = "latest", platform } = event;
isPullingImage = true;
- let currentPullProgress = $state(0);
try {
const encodedImageRef = encodeURIComponent(imageRef);
const eventSource = new EventSource(
- `/api/images/pull-stream/${encodedImageRef}?tag=${tag}${platform ? `&platform=${platform}` : ""}`
+ `/api/images/pull-stream/${encodedImageRef}?tag=${tag}${
+ platform ? `&platform=${platform}` : ""
+ }`
);
eventSource.onmessage = (event) => {
@@ -53,8 +77,6 @@
}
if (data.progress !== undefined) {
- console.log("Progress update:", data.progress);
- currentPullProgress = data.progress;
pullProgress = data.progress;
}
@@ -64,7 +86,10 @@
toast.success(`Image "${fullImageRef}" pulled successfully.`);
isPullDialogOpen = false;
- window.location.href = `${window.location.pathname}?t=${Date.now()}`;
+ setTimeout(async () => {
+ await refreshData();
+ }, 500);
+ isPullingImage = false;
}
};
@@ -81,12 +106,112 @@
}
}
+ async function handleDeleteSelected() {
+ isDeletingSelected = true;
+ const deletePromises = selectedIds.map(async (id) => {
+ try {
+ const image = images.find((img) => img.id === id);
+ if (image?.inUse) {
+ toast.error(
+ `Image "${image.repo}:${image.tag}" (${id.substring(
+ 0,
+ 12
+ )}) is in use and cannot be deleted.`
+ );
+ return { id, success: false, error: "Image in use" };
+ }
+
+ const response = await fetch(`/api/images/${encodeURIComponent(id)}`, {
+ method: "DELETE",
+ });
+ const result = await response.json();
+ if (!response.ok) {
+ throw new Error(
+ result.error || `HTTP error! status: ${response.status}`
+ );
+ }
+ return {
+ id,
+ success: true,
+ repoTag: image?.repoTags?.[0] || id.substring(0, 12),
+ };
+ } catch (err: any) {
+ console.error(`Failed to delete image "${id}":`, err);
+ const image = images.find((img) => img.id === id);
+ return {
+ id,
+ success: false,
+ error: err.message,
+ repoTag: image?.repoTags?.[0] || id.substring(0, 12),
+ };
+ }
+ });
+
+ const results = await Promise.all(deletePromises);
+ const successfulDeletes = results.filter((r) => r.success);
+ const failedDeletes = results.filter((r) => !r.success);
+
+ if (successfulDeletes.length > 0) {
+ toast.success(
+ `Successfully deleted ${successfulDeletes.length} image(s).`
+ );
+ setTimeout(async () => {
+ await refreshData();
+ selectedIds = [];
+ }, 500);
+ }
+
+ failedDeletes.forEach((r) => {
+ if (r.error !== "Image in use") {
+ toast.error(`Failed to delete image "${r.repoTag}": ${r.error}`);
+ }
+ });
+
+ isDeletingSelected = false;
+ isConfirmDeleteDialogOpen = false;
+ }
+
+ async function handlePruneImages() {
+ isPruning = true;
+ try {
+ const response = await fetch("/api/images/prune", {
+ method: "POST",
+ });
+ const result = await response.json();
+
+ if (!response.ok) {
+ throw new Error(
+ result.error || `HTTP error! status: ${response.status}`
+ );
+ }
+
+ toast.success(result.message || "Image prune completed.");
+ setTimeout(async () => {
+ await refreshData();
+ }, 500);
+ } catch (err: any) {
+ console.error("Failed to prune images:", err);
+ toast.error(`Failed to prune images: ${err.message}`);
+ } finally {
+ isPruning = false;
+ isConfirmPruneDialogOpen = false;
+ }
+ }
+
async function refreshData() {
+ if (isRefreshing) return;
isRefreshing = true;
- await invalidateAll();
- setTimeout(() => {
- isRefreshing = false;
- }, 500);
+ try {
+ await invalidateAll();
+ images = data.images;
+ } catch (err) {
+ console.error("Error refreshing images:", err);
+ toast.error("Failed to refresh image list.");
+ } finally {
+ setTimeout(() => {
+ isRefreshing = false;
+ }, 300);
+ }
}
function openPullDialog() {
@@ -95,7 +220,6 @@
</script>
<div class="space-y-6">
- <!-- Header with refresh and pull buttons -->
<div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">
<div>
<h1 class="text-3xl font-bold tracking-tight">Docker Images</h1>
@@ -103,8 +227,38 @@
Manage your Docker images
</p>
</div>
- <div class="flex gap-2">
- <!-- put buttons here -->
+ <div class="flex items-center gap-2">
+ <Button
+ variant="secondary"
+ size="icon"
+ onclick={refreshData}
+ disabled={isRefreshing}
+ >
+ <RefreshCw class={cn("h-4 w-4", isRefreshing && "animate-spin")} />
+ <span class="sr-only">Refresh</span>
+ </Button>
+ <Button
+ variant="secondary"
+ onclick={() => (isConfirmPruneDialogOpen = true)}
+ disabled={isPruning}
+ >
+ {#if isPruning}
+ <Loader2 class="w-4 h-4 animate-spin" /> Pruning...
+ {:else}
+ <CopyX class="w-4 h-4" /> Prune Unused
+ {/if}
+ </Button>
+ <Button
+ variant="secondary"
+ onclick={openPullDialog}
+ disabled={isPullingImage}
+ >
+ {#if isPullingImage}
+ <Loader2 class="w-4 h-4 animate-spin" /> Pulling...
+ {:else}
+ <Download class="w-4 h-4" /> Pull Image
+ {/if}
+ </Button>
</div>
</div>
@@ -116,7 +270,6 @@
</Alert.Root>
{/if}
- <!-- Image stats summary -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<Card.Root>
<Card.Content class="p-4 flex items-center justify-between">
@@ -143,22 +296,49 @@
</Card.Root>
</div>
- <!-- Main images table -->
{#if images && images.length > 0}
<Card.Root class="border shadow-sm">
<Card.Header class="px-6">
<div class="flex items-center justify-between">
<div>
<Card.Title>Image List</Card.Title>
- <Card.Description
- >View and manage your Docker images</Card.Description
- >
+ <Card.Description>
+ View and manage your Docker images
+ </Card.Description>
</div>
<div class="flex items-center gap-2">
- <Button variant="outline" size="sm" onclick={openPullDialog}>
- <Download class="w-4 h-4" />
- Pull Image
- </Button>
+ {#if selectedIds.length > 0}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button
+ {...props}
+ variant="outline"
+ disabled={isDeletingSelected}
+ aria-label={`Group actions for ${selectedIds.length} selected image(s)`}
+ >
+ {#if isDeletingSelected}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ Processing...
+ {:else}
+ Actions ({selectedIds.length})
+ <ChevronDown class="w-4 h-4 ml-2" />
+ {/if}
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content>
+ <DropdownMenu.Item
+ onclick={() => (isConfirmDeleteDialogOpen = true)}
+ class="text-red-500 focus:!text-red-700"
+ disabled={isDeletingSelected}
+ >
+ <Trash2 class="w-4 h-4" />
+ Delete Selected
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ {/if}
</div>
</div>
</Card.Header>
@@ -166,6 +346,7 @@
<UniversalTable
data={images}
{columns}
+ idKey="id"
display={{
filterPlaceholder: "Search images...",
noResultsMessage: "No images found",
@@ -206,4 +387,70 @@
{pullProgress}
onSubmit={handlePullImageSubmit}
/>
+
+ <Dialog.Root bind:open={isConfirmDeleteDialogOpen}>
+ <Dialog.Content>
+ <Dialog.Header>
+ <Dialog.Title>Delete Selected Images</Dialog.Title>
+ <Dialog.Description>
+ Are you sure you want to delete {selectedIds.length} selected image(s)?
+ This action cannot be undone. Images currently used by containers will
+ not be deleted.
+ </Dialog.Description>
+ </Dialog.Header>
+ <div class="flex justify-end gap-3 pt-6">
+ <Button
+ variant="outline"
+ onclick={() => (isConfirmDeleteDialogOpen = false)}
+ disabled={isDeletingSelected}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onclick={handleDeleteSelected}
+ disabled={isDeletingSelected}
+ >
+ {#if isDeletingSelected}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" /> Deleting...
+ {:else}
+ Delete {selectedIds.length} Image{#if selectedIds.length > 1}s{/if}
+ {/if}
+ </Button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Root>
+
+ <Dialog.Root bind:open={isConfirmPruneDialogOpen}>
+ <Dialog.Content>
+ <Dialog.Header>
+ <Dialog.Title>Prune Unused Images</Dialog.Title>
+ <Dialog.Description>
+ Are you sure you want to remove all unused (dangling) Docker images?
+ This will free up disk space but cannot be undone. Images actively
+ used by containers will not be affected.
+ </Dialog.Description>
+ </Dialog.Header>
+ <div class="flex justify-end gap-3 pt-6">
+ <Button
+ variant="outline"
+ onclick={() => (isConfirmPruneDialogOpen = false)}
+ disabled={isPruning}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onclick={handlePruneImages}
+ disabled={isPruning}
+ >
+ {#if isPruning}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" /> Pruning...
+ {:else}
+ Prune Images
+ {/if}
+ </Button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Root>
</div>
diff --git a/src/routes/networks/+page.svelte b/src/routes/networks/+page.svelte
index 912de015c..33c6e86e1 100644
--- a/src/routes/networks/+page.svelte
+++ b/src/routes/networks/+page.svelte
@@ -6,22 +6,38 @@
AlertCircle,
Network,
RefreshCw,
- Filter,
- ArrowUpDown,
+ Trash2,
+ Loader2,
+ ChevronDown,
} from "@lucide/svelte";
import UniversalTable from "$lib/components/universal-table.svelte";
import { columns } from "./columns";
import type { PageData } from "./$types";
import * as Alert from "$lib/components/ui/alert/index.js";
import { invalidateAll } from "$app/navigation";
+ import { toast } from "svelte-sonner";
+ import { cn } from "$lib/utils";
+ import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js";
+ import * as Dialog from "$lib/components/ui/dialog/index.js";
+ import CreateNetworkDialog from "./CreateNetworkDialog.svelte";
+ import type { NetworkCreateOptions } from "dockerode";
let { data }: { data: PageData } = $props();
- const { networks, error } = data;
- let selectedIds = $state([]);
+ let networks = $state(data.networks || []);
+ let error = $state(data.error);
+ let selectedIds = $state<string[]>([]);
let isRefreshing = $state(false);
+ let isDeletingSelected = $state(false);
+ let isConfirmDeleteDialogOpen = $state(false);
+ let isCreateDialogOpen = $state(false);
+ let isCreatingNetwork = $state(false);
+
+ $effect(() => {
+ networks = data.networks || [];
+ error = data.error;
+ });
- // Calculate network stats
const totalNetworks = $derived(networks?.length || 0);
const bridgeNetworks = $derived(
networks?.filter((n) => n.driver === "bridge").length || 0
@@ -30,21 +46,109 @@
networks?.filter((n) => n.driver === "overlay").length || 0
);
- function createNetwork() {
- alert("Implement create network functionality");
+ function openCreateDialog() {
+ isCreateDialogOpen = true;
+ }
+
+ async function handleCreateNetworkSubmit(options: NetworkCreateOptions) {
+ isCreatingNetwork = true;
+ try {
+ const response = await fetch("/api/networks/create", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(options),
+ });
+
+ const result = await response.json();
+
+ if (!response.ok) {
+ throw new Error(
+ result.message || `HTTP error! status: ${response.status}`
+ );
+ }
+
+ toast.success(
+ result.message || `Network "${result.network.name}" created.`
+ );
+ isCreateDialogOpen = false;
+ setTimeout(async () => {
+ await refreshData();
+ }, 300);
+ } catch (err: any) {
+ console.error("Failed to create network:", err);
+ toast.error(`Failed to create network: ${err.message}`);
+ } finally {
+ isCreatingNetwork = false;
+ }
}
async function refreshData() {
+ if (isRefreshing) return;
isRefreshing = true;
- await invalidateAll();
- setTimeout(() => {
- isRefreshing = false;
- }, 500);
+ try {
+ await invalidateAll();
+ } catch (err) {
+ console.error("Error refreshing networks:", err);
+ toast.error("Failed to refresh network list.");
+ } finally {
+ setTimeout(() => {
+ isRefreshing = false;
+ }, 300);
+ }
+ }
+
+ async function handleDeleteSelected() {
+ isDeletingSelected = true;
+ const deletePromises = selectedIds.map(async (id) => {
+ try {
+ const networkName =
+ networks.find((n) => n.id === id)?.name || id.substring(0, 12);
+
+ const response = await fetch(
+ `/api/networks/${encodeURIComponent(id)}`,
+ {
+ method: "DELETE",
+ }
+ );
+ const result = await response.json();
+ if (!response.ok) {
+ throw new Error(
+ result.message || `HTTP error! status: ${response.status}`
+ );
+ }
+ return { id, success: true, name: networkName };
+ } catch (err: any) {
+ console.error(`Failed to delete network "${id}":`, err);
+ const networkName =
+ networks.find((n) => n.id === id)?.name || id.substring(0, 12);
+ return { id, success: false, error: err.message, name: networkName };
+ }
+ });
+
+ const results = await Promise.all(deletePromises);
+ const successfulDeletes = results.filter((r) => r.success);
+ const failedDeletes = results.filter((r) => !r.success);
+
+ if (successfulDeletes.length > 0) {
+ toast.success(
+ `Successfully deleted ${successfulDeletes.length} network(s).`
+ );
+ setTimeout(async () => {
+ await refreshData();
+ selectedIds = [];
+ }, 500);
+ }
+
+ failedDeletes.forEach((r) => {
+ toast.error(`Failed to delete network "${r.name}": ${r.error}`);
+ });
+
+ isDeletingSelected = false;
+ isConfirmDeleteDialogOpen = false;
}
</script>
<div class="space-y-6">
- <!-- Header with refresh and create buttons -->
<div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">
<div>
<h1 class="text-3xl font-bold tracking-tight">Networks</h1>
@@ -52,8 +156,24 @@
Manage Docker container networking
</p>
</div>
- <div class="flex gap-2">
- <!-- Put buttons here -->
+ <div class="flex items-center gap-2">
+ <Button
+ variant="secondary"
+ size="icon"
+ onclick={refreshData}
+ disabled={isRefreshing}
+ >
+ <RefreshCw class={cn("h-4 w-4", isRefreshing && "animate-spin")} />
+ <span class="sr-only">Refresh</span>
+ </Button>
+ <Button
+ variant="secondary"
+ onclick={openCreateDialog}
+ disabled={isCreatingNetwork}
+ >
+ <Plus class="w-4 h-4" />
+ Create Network
+ </Button>
</div>
</div>
@@ -65,7 +185,6 @@
</Alert.Root>
{/if}
- <!-- Network stats summary -->
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
<Card.Root>
<Card.Content class="p-4 flex items-center justify-between">
@@ -110,7 +229,6 @@
</Card.Root>
</div>
- <!-- Main networks table -->
<Card.Root class="border shadow-sm">
<Card.Header class="px-6">
<div class="flex items-center justify-between">
@@ -119,10 +237,39 @@
<Card.Description>Manage container communication</Card.Description>
</div>
<div class="flex items-center gap-2">
- <Button variant="outline" size="sm" onclick={createNetwork}>
- <Plus class="w-4 h-4" />
- Create Network
- </Button>
+ {#if selectedIds.length > 0}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button
+ {...props}
+ variant="outline"
+ size="sm"
+ disabled={isDeletingSelected}
+ aria-label={`Group actions for ${selectedIds.length} selected network(s)`}
+ >
+ {#if isDeletingSelected}
+ <Loader2 class="w-4 h-4 animate-spin" />
+ Processing...
+ {:else}
+ Actions ({selectedIds.length})
+ <ChevronDown class="w-4 h-4" />
+ {/if}
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content>
+ <DropdownMenu.Item
+ onclick={() => (isConfirmDeleteDialogOpen = true)}
+ class="text-red-500 focus:!text-red-700"
+ disabled={isDeletingSelected}
+ >
+ <Trash2 class="w-4 h-4" />
+ Delete Selected
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ {/if}
</div>
</div>
</Card.Header>
@@ -131,10 +278,14 @@
<UniversalTable
data={networks}
{columns}
+ idKey="id"
display={{
filterPlaceholder: "Search networks...",
noResultsMessage: "No networks found",
}}
+ sort={{
+ defaultSort: { id: "name", desc: false },
+ }}
bind:selectedIds
/>
{:else if !error}
@@ -152,7 +303,7 @@
<RefreshCw class="h-4 w-4" />
Refresh
</Button>
- <Button variant="outline" size="sm" onclick={createNetwork}>
+ <Button variant="outline" size="sm" onclick={openCreateDialog}>
<Plus class="h-4 w-4" />
Create Network
</Button>
@@ -161,4 +312,43 @@
{/if}
</Card.Content>
</Card.Root>
+
+ <CreateNetworkDialog
+ bind:open={isCreateDialogOpen}
+ isCreating={isCreatingNetwork}
+ onSubmit={handleCreateNetworkSubmit}
+ />
+
+ <Dialog.Root bind:open={isConfirmDeleteDialogOpen}>
+ <Dialog.Content>
+ <Dialog.Header>
+ <Dialog.Title>Delete Selected Networks</Dialog.Title>
+ <Dialog.Description>
+ Are you sure you want to delete {selectedIds.length} selected network(s)?
+ This action cannot be undone. Networks currently in use by containers cannot
+ be deleted.
+ </Dialog.Description>
+ </Dialog.Header>
+ <div class="flex justify-end gap-3 pt-6">
+ <Button
+ variant="outline"
+ onclick={() => (isConfirmDeleteDialogOpen = false)}
+ disabled={isDeletingSelected}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onclick={handleDeleteSelected}
+ disabled={isDeletingSelected}
+ >
+ {#if isDeletingSelected}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" /> Deleting...
+ {:else}
+ Delete {selectedIds.length} Network{#if selectedIds.length > 1}s{/if}
+ {/if}
+ </Button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Root>
</div>
diff --git a/src/routes/networks/CreateNetworkDialog.svelte b/src/routes/networks/CreateNetworkDialog.svelte
new file mode 100644
index 000000000..df9b651f4
--- /dev/null
+++ b/src/routes/networks/CreateNetworkDialog.svelte
@@ -0,0 +1,266 @@
+<script lang="ts">
+ import * as Dialog from "$lib/components/ui/dialog/index.js";
+ import { Button } from "$lib/components/ui/button/index.js";
+ import { Input } from "$lib/components/ui/input/index.js";
+ import { Label } from "$lib/components/ui/label/index.js";
+ import * as Select from "$lib/components/ui/select/index.js";
+ import { Checkbox } from "$lib/components/ui/checkbox/index.js";
+ import { Loader2, Plus, X } from "@lucide/svelte";
+ import type { NetworkCreateOptions } from "dockerode";
+ import { preventDefault } from "$lib/utils/form.utils";
+
+ type Props = {
+ open: boolean;
+ isCreating: boolean;
+ onSubmit: (options: NetworkCreateOptions) => void;
+ };
+
+ let {
+ open = $bindable(),
+ isCreating = false, // Default value for the prop
+ onSubmit,
+ }: Props = $props();
+
+ // Form state
+ let name = $state("");
+ let driver = $state("bridge"); // Default driver
+ let checkDuplicate = $state(true);
+ let internal = $state(false);
+ let labels = $state<{ key: string; value: string }[]>([
+ { key: "", value: "" },
+ ]);
+ // Basic IPAM config state (optional)
+ let enableIpam = $state(false);
+ let subnet = $state("");
+ let gateway = $state("");
+
+ function addLabel() {
+ labels = [...labels, { key: "", value: "" }];
+ }
+
+ function removeLabel(index: number) {
+ labels = labels.filter((_, i) => i !== index);
+ }
+
+ function handleSubmit() {
+ const finalLabels: Record<string, string> = {};
+ labels.forEach((label) => {
+ if (label.key.trim()) {
+ finalLabels[label.key.trim()] = label.value.trim();
+ }
+ });
+
+ const options: NetworkCreateOptions = {
+ Name: name.trim(),
+ Driver: driver,
+ CheckDuplicate: checkDuplicate,
+ Internal: internal,
+ Labels: Object.keys(finalLabels).length > 0 ? finalLabels : undefined,
+ };
+
+ if (enableIpam && (subnet.trim() || gateway.trim())) {
+ const ipamConfig: { Subnet?: string; Gateway?: string } = {};
+ const trimmedSubnet = subnet.trim();
+ const trimmedGateway = gateway.trim();
+
+ if (trimmedSubnet) {
+ ipamConfig.Subnet = trimmedSubnet;
+ }
+ if (trimmedGateway) {
+ ipamConfig.Gateway = trimmedGateway;
+ }
+
+ // Only add IPAM config if Subnet or Gateway is provided
+ if (Object.keys(ipamConfig).length > 0) {
+ options.IPAM = {
+ Driver: "default", // Usually 'default'
+ Config: [ipamConfig],
+ };
+ }
+ }
+
+ onSubmit(options);
+ }
+
+ // Reset form when dialog opens/closes
+ $effect(() => {
+ if (!open) {
+ name = "";
+ driver = "bridge";
+ checkDuplicate = true;
+ internal = false;
+ labels = [{ key: "", value: "" }];
+ enableIpam = false;
+ subnet = "";
+ gateway = "";
+ }
+ });
+</script>
+
+<Dialog.Root bind:open>
+ <Dialog.Content class="sm:max-w-[600px]">
+ <Dialog.Header>
+ <Dialog.Title>Create Network</Dialog.Title>
+ <Dialog.Description>
+ Configure and create a new Docker network.
+ </Dialog.Description>
+ </Dialog.Header>
+
+ <form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-4">
+ <!-- Name -->
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label for="network-name" class="text-right">Name</Label>
+ <Input
+ id="network-name"
+ bind:value={name}
+ required
+ class="col-span-3"
+ placeholder="e.g., my-app-network"
+ disabled={isCreating}
+ />
+ </div>
+
+ <!-- Driver -->
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label for="network-driver" class="text-right">Driver</Label>
+ <!-- Update the Select component structure -->
+ <Select.Root type="single" bind:value={driver}>
+ <Select.Trigger
+ class="col-span-3"
+ id="network-driver"
+ disabled={isCreating}
+ >
+ <span>{driver}</span>
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Item value="bridge">bridge</Select.Item>
+ <Select.Item value="overlay">overlay</Select.Item>
+ <Select.Item value="macvlan">macvlan</Select.Item>
+ <Select.Item value="ipvlan">ipvlan</Select.Item>
+ <Select.Item value="none">none</Select.Item>
+ </Select.Content>
+ </Select.Root>
+ </div>
+
+ <!-- Options: Check Duplicate, Internal -->
+ <div class="grid grid-cols-4 items-center gap-4">
+ <span class="text-right text-sm font-medium">Options</span>
+ <div class="col-span-3 flex items-center space-x-4">
+ <div class="flex items-center space-x-2">
+ <Checkbox
+ id="check-duplicate"
+ bind:checked={checkDuplicate}
+ disabled={isCreating}
+ />
+ <Label for="check-duplicate" class="text-sm font-normal"
+ >Check Duplicate</Label
+ >
+ </div>
+ <div class="flex items-center space-x-2">
+ <Checkbox
+ id="internal"
+ bind:checked={internal}
+ disabled={isCreating}
+ />
+ <Label for="internal" class="text-sm font-normal">Internal</Label>
+ </div>
+ </div>
+ </div>
+
+ <!-- Labels -->
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label class="text-right pt-2">Labels</Label>
+ <div class="col-span-3 space-y-2">
+ {#each labels as label, index}
+ <div class="flex gap-2 items-center">
+ <Input
+ placeholder="Key"
+ bind:value={label.key}
+ class="flex-1"
+ disabled={isCreating}
+ />
+ <Input
+ placeholder="Value"
+ bind:value={label.value}
+ class="flex-1"
+ disabled={isCreating}
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onclick={() => removeLabel(index)}
+ disabled={isCreating || labels.length <= 1}
+ class="text-destructive hover:text-destructive"
+ title="Remove Label"
+ >
+ <X class="w-4 h-4" />
+ </Button>
+ </div>
+ {/each}
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onclick={addLabel}
+ disabled={isCreating}
+ >
+ <Plus class="w-4 h-4 mr-2" /> Add Label
+ </Button>
+ </div>
+ </div>
+
+ <!-- IPAM Configuration (Optional) -->
+ <div class="grid grid-cols-4 items-start gap-4 border-t pt-4 mt-2">
+ <div class="flex items-center space-x-2 col-span-4">
+ <Checkbox
+ id="enable-ipam"
+ bind:checked={enableIpam}
+ disabled={isCreating}
+ />
+ <Label for="enable-ipam" class="text-sm font-medium"
+ >Enable IPAM Configuration</Label
+ >
+ </div>
+ {#if enableIpam}
+ <div class="grid grid-cols-4 items-center gap-4 col-span-4">
+ <Label for="subnet" class="text-right">Subnet</Label>
+ <Input
+ id="subnet"
+ bind:value={subnet}
+ placeholder="e.g., 172.20.0.0/16"
+ class="col-span-3"
+ disabled={isCreating}
+ />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4 col-span-4">
+ <Label for="gateway" class="text-right">Gateway</Label>
+ <Input
+ id="gateway"
+ bind:value={gateway}
+ placeholder="e.g., 172.20.0.1"
+ class="col-span-3"
+ disabled={isCreating}
+ />
+ </div>
+ {/if}
+ </div>
+
+ <Dialog.Footer>
+ <Button
+ type="button"
+ variant="outline"
+ onclick={() => (open = false)}
+ disabled={isCreating}>Cancel</Button
+ >
+ <Button type="submit" disabled={isCreating || !name.trim()}>
+ {#if isCreating}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" /> Creating...
+ {:else}
+ Create Network
+ {/if}
+ </Button>
+ </Dialog.Footer>
+ </form>
+ </Dialog.Content>
+</Dialog.Root>
diff --git a/src/routes/networks/NetworkActions.svelte b/src/routes/networks/NetworkActions.svelte
index a639e6f15..6cf9ecbbb 100644
--- a/src/routes/networks/NetworkActions.svelte
+++ b/src/routes/networks/NetworkActions.svelte
@@ -1,6 +1,10 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button/index.js";
- import { Trash2 } from "@lucide/svelte";
+ import { Trash2, Loader2 } from "@lucide/svelte";
+ import * as Dialog from "$lib/components/ui/dialog/index.js";
+ import { toast } from "svelte-sonner";
+ import { invalidateAll } from "$app/navigation";
+ import { cn } from "$lib/utils";
interface Props {
id: string | undefined;
@@ -9,18 +13,100 @@
let { id, name }: Props = $props();
- function deleteNetwork() {
- // TODO: Implement network deletion logic
- alert(`Implement deletion for network: ${name} (ID: ${id ?? "N/A"})`);
+ let isConfirmDeleteDialogOpen = $state(false);
+ let isDeleting = $state(false);
+
+ // Add a derived state to check if the network is a default one
+ const isDefaultNetwork = $derived(
+ name === "host" || name === "bridge" || name === "none"
+ );
+
+ function openConfirmDialog() {
+ if (!id) return; // Should not happen if button is rendered
+ isConfirmDeleteDialogOpen = true;
+ }
+
+ async function handleConfirmDelete() {
+ if (!id) return;
+ isDeleting = true;
+
+ try {
+ const response = await fetch(`/api/networks/${encodeURIComponent(id)}`, {
+ method: "DELETE",
+ });
+ const result = await response.json();
+
+ if (!response.ok) {
+ throw new Error(
+ result.message || `HTTP error! status: ${response.status}`
+ );
+ }
+
+ toast.success(`Network "${name}" deleted successfully.`);
+ isConfirmDeleteDialogOpen = false; // Close dialog
+ await invalidateAll(); // Refresh the list on the parent page
+ } catch (err: any) {
+ console.error(`Failed to delete network ${id}:`, err);
+ toast.error(`Failed to delete network "${name}": ${err.message}`);
+ // Keep dialog open on error? Optional.
+ // isConfirmDeleteDialogOpen = false;
+ } finally {
+ isDeleting = false;
+ }
}
</script>
-<Button
- variant="destructive"
- size="sm"
- onclick={deleteNetwork}
- title="Delete Network"
->
- <Trash2 class="w-4 h-4" />
-</Button>
+{#if id}
+ <!-- Delete Button -->
+ <Button
+ variant="ghost"
+ size="icon"
+ class={cn(
+ "size-8",
+ !isDefaultNetwork &&
+ "text-destructive hover:text-destructive hover:bg-destructive/10"
+ )}
+ onclick={openConfirmDialog}
+ title={isDefaultNetwork
+ ? "Cannot delete default network"
+ : "Delete Network"}
+ disabled={isDeleting || isDefaultNetwork}
+ >
+ <Trash2 class="w-4 h-4" />
+ </Button>
+
+ <!-- Confirmation Dialog -->
+ <Dialog.Root bind:open={isConfirmDeleteDialogOpen}>
+ <Dialog.Content>
+ <Dialog.Header>
+ <Dialog.Title>Delete Network "{name}"</Dialog.Title>
+ <Dialog.Description>
+ Are you sure you want to delete this network? This action cannot be
+ undone. Networks currently in use by containers cannot be deleted.
+ </Dialog.Description>
+ </Dialog.Header>
+ <div class="flex justify-end gap-3 pt-6">
+ <Button
+ variant="outline"
+ onclick={() => (isConfirmDeleteDialogOpen = false)}
+ disabled={isDeleting}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onclick={handleConfirmDelete}
+ disabled={isDeleting}
+ >
+ {#if isDeleting}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" /> Deleting...
+ {:else}
+ Delete Network
+ {/if}
+ </Button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Root>
+{/if}
+
<!-- Add other actions like inspect if needed -->
diff --git a/src/routes/networks/SubnetCell.svelte b/src/routes/networks/SubnetCell.svelte
index b9651aefd..5917980a4 100644
--- a/src/routes/networks/SubnetCell.svelte
+++ b/src/routes/networks/SubnetCell.svelte
@@ -1,6 +1,10 @@
<!-- filepath: /Users/kylemendell/dev/ofkm/arcane/src/routes/networks/SubnetCell.svelte -->
<script lang="ts">
- export let subnet: string | null;
+ interface Props {
+ subnet: string | null;
+ }
+
+ let { subnet }: Props = $props();
</script>
{#if subnet}
diff --git a/src/routes/settings/+page.server.ts b/src/routes/settings/+page.server.ts
index 01bbbbc36..a9f444425 100644
--- a/src/routes/settings/+page.server.ts
+++ b/src/routes/settings/+page.server.ts
@@ -31,6 +31,14 @@ export const actions: Actions = {
const pollingIntervalStr = formData.get("pollingInterval") as string;
const stacksDirectory = (formData.get("stacksDirectory") as string) || "";
+ // --- Read pruneMode from form data ---
+ const pruneModeValue = formData.get("pruneMode");
+ // Validate the value, default to current setting or 'all' if invalid/missing
+ const pruneMode: "all" | "dangling" =
+ pruneModeValue === "all" || pruneModeValue === "dangling"
+ ? pruneModeValue
+ : settings.pruneMode || "all"; // Fallback to current or default
+
if (!dockerHost) {
return fail(400, {
error: "Docker host cannot be empty.",
@@ -90,6 +98,7 @@ export const actions: Actions = {
pollingEnabled,
pollingInterval,
stacksDirectory,
+ pruneMode: pruneMode,
externalServices,
};
@@ -99,9 +108,10 @@ export const actions: Actions = {
return { success: true };
} catch (error: any) {
console.error("Error updating settings:", error);
+ const formValues = Object.fromEntries(formData);
return fail(500, {
error: error.message || "Failed to save settings.",
- values: Object.fromEntries(formData),
+ values: formValues,
});
}
},
diff --git a/src/routes/settings/tabs/app-settings.svelte b/src/routes/settings/tabs/app-settings.svelte
index 3c5b074b5..3ba764709 100644
--- a/src/routes/settings/tabs/app-settings.svelte
+++ b/src/routes/settings/tabs/app-settings.svelte
@@ -2,7 +2,16 @@
import * as Card from "$lib/components/ui/card/index.js";
import { Input } from "$lib/components/ui/input/index.js";
import { Switch } from "$lib/components/ui/switch/index.js";
- import { Save, RefreshCw, Key, Plus, Trash2 } from "@lucide/svelte";
+ import {
+ Save,
+ RefreshCw,
+ Key,
+ Plus,
+ Trash2,
+ ImageMinus,
+ } from "@lucide/svelte";
+ import * as RadioGroup from "$lib/components/ui/radio-group/index.js";
+ import { Label } from "$lib/components/ui/label/index.js";
import type { ActionData, PageData } from "../$types";
let { data, form } = $props<{ data: PageData; form: ActionData }>();
@@ -14,17 +23,15 @@
form?.values?.dockerHost || settings?.dockerHost || ""
);
- // Make sure the pollingEnabled variable comes from settings.pollingEnabled
let pollingEnabled = $derived(
form?.values?.pollingEnabled !== undefined
? form.values.pollingEnabled === "on"
: settings?.pollingEnabled || false
);
- // Rename to pollingInterval to be consistent
let pollingInterval = $derived(
form?.values?.pollingInterval !== undefined
- ? form.values.pollingInterval
+ ? Number(form.values.pollingInterval)
: settings?.pollingInterval || 10
);
@@ -37,8 +44,14 @@
: settings?.autoUpdate || false
);
+ let pruneMode = $derived<"all" | "dangling">(
+ form?.values?.pruneMode || settings?.pruneMode || "all"
+ );
+
let registryCredentials = $derived(
- form?.values?.registryCredentials || settings?.registryCredentials || []
+ typeof form?.values?.registryCredentials === "string"
+ ? JSON.parse(form.values.registryCredentials)
+ : form?.values?.registryCredentials || settings?.registryCredentials || []
);
const defaultRegistry = { url: "", username: "", password: "" };
@@ -47,7 +60,6 @@
registryCredentials = [...registryCredentials, { ...defaultRegistry }];
}
- // Remove a registry
function removeRegistry(index: number) {
registryCredentials = registryCredentials.filter(
(_: unknown, i: number) => i !== index
@@ -169,13 +181,12 @@
{/if}
</div>
- <!-- Auto Update option -->
<div
class="flex items-center justify-between rounded-lg border p-4 bg-muted/30"
>
<div class="space-y-0.5">
- <label for="autoUpdateSwitch" class="text-base font-medium"
- >Auto Update Containers</label
+ <Label for="autoUpdateSwitch" class="text-base font-medium"
+ >Auto Update Containers</Label
>
<p class="text-sm text-muted-foreground">
Automatically update containers when newer images are available
@@ -190,6 +201,51 @@
{/if}
</Card.Content>
</Card.Root>
+
+ <!-- Prune Settings Card -->
+ <Card.Root class="border shadow-sm">
+ <Card.Header class="pb-3">
+ <div class="flex items-center gap-2">
+ <div class="bg-purple-500/10 p-2 rounded-full">
+ <ImageMinus class="h-5 w-5 text-purple-500" />
+ </div>
+ <div>
+ <Card.Title>Image Pruning</Card.Title>
+ <Card.Description>Configure image prune behavior</Card.Description>
+ </div>
+ </div>
+ </Card.Header>
+ <Card.Content class="space-y-4">
+ <div>
+ <Label for="pruneMode" class="text-base font-medium block mb-2"
+ >Prune Action Behavior</Label
+ >
+ <RadioGroup.Root
+ bind:value={pruneMode}
+ name="pruneMode"
+ class="flex flex-col space-y-1"
+ id="pruneMode"
+ >
+ <div class="flex items-center space-x-2">
+ <RadioGroup.Item value="all" id="prune-all" />
+ <Label for="prune-all" class="font-normal">
+ All Unused Images (like `docker image prune -a`)
+ </Label>
+ </div>
+ <div class="flex items-center space-x-2">
+ <RadioGroup.Item value="dangling" id="prune-dangling" />
+ <Label for="prune-dangling" class="font-normal">
+ Dangling Images Only (like `docker image prune`)
+ </Label>
+ </div>
+ </RadioGroup.Root>
+ <p class="text-xs text-muted-foreground mt-2">
+ Select which images are removed by the "Prune Unused" action on the
+ Images page.
+ </p>
+ </div>
+ </Card.Content>
+ </Card.Root>
</div>
<!-- Docker Registry Credentials Card -->
diff --git a/src/routes/stacks/+page.svelte b/src/routes/stacks/+page.svelte
index 55f39017c..9ca1aed24 100644
--- a/src/routes/stacks/+page.svelte
+++ b/src/routes/stacks/+page.svelte
@@ -90,19 +90,18 @@
<div class="flex gap-2">
<Button
variant="outline"
- size="sm"
+ size="icon"
onclick={refreshData}
disabled={isRefreshing}
>
<RefreshCw class={isRefreshing ? "w-4 h-4 animate-spin" : "w-4 h-4"} />
- Refresh
</Button>
</div>
</div>
{#if error}
<Alert.Root variant="destructive">
- <AlertCircle class="h-4 w-4 mr-2" />
+ <AlertCircle class="h-4 w-4" />
<Alert.Title>Error Loading Stacks</Alert.Title>
<Alert.Description>{error}</Alert.Description>
</Alert.Root>
@@ -158,11 +157,11 @@
<Card.Description>Manage Docker Compose stacks</Card.Description>
</div>
<div class="flex items-center gap-2">
- <Button variant="outline" size="sm" onclick={importStack}>
+ <Button variant="secondary" onclick={importStack}>
<Upload class="w-4 h-4" />
Import
</Button>
- <Button variant="outline" size="sm" onclick={createStack}>
+ <Button variant="secondary" onclick={createStack}>
<Plus class="w-4 h-4" />
Create Stack
</Button>
@@ -174,6 +173,9 @@
<UniversalTable
data={stacks}
{columns}
+ features={{
+ selection: false,
+ }}
display={{
filterPlaceholder: "Search stacks...",
noResultsMessage: "No stacks found",
diff --git a/src/routes/stacks/[stackId]/+page.svelte b/src/routes/stacks/[stackId]/+page.svelte
index 18c00fab2..c7bcf65a2 100644
--- a/src/routes/stacks/[stackId]/+page.svelte
+++ b/src/routes/stacks/[stackId]/+page.svelte
@@ -231,13 +231,13 @@
value={composeContent}
on:change={(e) => (composeContent = e.detail.value)}
height="400px"
- placeholder="Enter your docker-compose.yml content"
+ placeholder="Enter your compose.yaml content"
forceDarkTheme={true}
/>
{/key}
<p class="text-xs text-muted-foreground">
- Edit your docker-compose.yml file directly. Syntax errors will
- be highlighted.
+ Edit your <span class="font-bold">compose.yaml</span> file directly.
+ Syntax errors will be highlighted.
</p>
</div>
</div>
diff --git a/src/routes/stacks/new/+page.server.ts b/src/routes/stacks/new/+page.server.ts
deleted file mode 100644
index f4fac4076..000000000
--- a/src/routes/stacks/new/+page.server.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { redirect } from "@sveltejs/kit";
-import { createStack } from "$lib/services/compose";
-
-/** @type {import('./$types').Actions} */
-export const actions = {
- default: async ({ request }) => {
- const formData = await request.formData();
-
- const name = formData.get("name")?.toString() || "";
- const composeContent = formData.get("composeContent")?.toString() || "";
-
- if (!name) {
- return {
- success: false,
- error: "Stack name is required",
- };
- }
-
- if (!composeContent) {
- return {
- success: false,
- error: "Compose file content is required",
- };
- }
-
- try {
- const stack = await createStack(name, composeContent);
- if (stack && stack.id) {
- throw redirect(303, `/stacks/${stack.id}`);
- }
-
- return {
- success: true,
- stack: stack,
- };
- } catch (err) {
- // Don't catch redirects
- if (
- err instanceof Response ||
- (err &&
- typeof err === "object" &&
- "status" in err &&
- err.status === 303)
- ) {
- throw err;
- }
-
- console.error("Error creating stack:", err);
- return {
- success: false,
- error: err instanceof Error ? err.message : "Failed to create stack",
- };
- }
- },
-};
diff --git a/src/routes/stacks/new/+page.svelte b/src/routes/stacks/new/+page.svelte
index d479a8b75..3cccf5b8f 100644
--- a/src/routes/stacks/new/+page.svelte
+++ b/src/routes/stacks/new/+page.svelte
@@ -1,5 +1,4 @@
<script lang="ts">
- import type { ActionData } from "./$types";
import * as Card from "$lib/components/ui/card/index.js";
import { Button } from "$lib/components/ui/button/index.js";
import {
@@ -10,22 +9,28 @@
FileStack,
} from "@lucide/svelte";
import * as Breadcrumb from "$lib/components/ui/breadcrumb/index.js";
- import { enhance } from "$app/forms";
import * as Alert from "$lib/components/ui/alert/index.js";
import { Input } from "$lib/components/ui/input/index.js";
import { Label } from "$lib/components/ui/label/index.js";
+ import { goto, invalidateAll } from "$app/navigation";
+ import { toast } from "svelte-sonner";
import { oneDark } from "@codemirror/theme-one-dark";
import { browser } from "$app/environment";
import YamlEditor from "$lib/components/yaml-editor.svelte";
- let { form }: { form: ActionData } = $props();
-
let saving = $state(false);
let darkMode = $state(false);
+ let apiError = $state<string | null>(null);
+
+ function preventDefault(fn: (event: Event) => any) {
+ return function (this: any, event: Event) {
+ event.preventDefault();
+ fn.call(this, event);
+ };
+ }
- // Check for dark mode preference
$effect(() => {
if (browser) {
darkMode =
@@ -34,15 +39,12 @@
}
});
- // Set up CodeMirror extensions
let extensions = $state([oneDark]);
- // Dynamic theme based on dark mode
$effect(() => {
extensions = darkMode ? [oneDark] : [];
});
- // Default compose file template
const defaultComposeTemplate = `services:
web:
image: nginx:alpine
@@ -56,10 +58,42 @@
let name = $state("");
let composeContent = $state(defaultComposeTemplate);
+
+ async function handleSubmit() {
+ saving = true;
+ apiError = null;
+
+ try {
+ const response = await fetch("/api/stacks/create", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ name, composeContent }),
+ });
+
+ const result = await response.json();
+
+ if (!response.ok) {
+ throw new Error(
+ result.message || `HTTP error! status: ${response.status}`
+ );
+ }
+
+ toast.success(result.message || `Stack "${result.stack.name}" created.`);
+ await invalidateAll();
+ goto(`/stacks/${result.stack.id}`);
+ } catch (err: any) {
+ console.error("Failed to create stack:", err);
+ apiError = err.message || "An unknown error occurred.";
+ toast.error(`Failed to create stack: ${apiError}`);
+ } finally {
+ saving = false;
+ }
+ }
</script>
<div class="space-y-6 pb-8">
- <!-- Breadcrumb Navigation -->
<div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">
<div>
<Breadcrumb.Root>
@@ -82,27 +116,15 @@
</div>
</div>
- <!-- Error Alert -->
- {#if form?.error}
+ {#if apiError}
<Alert.Root variant="destructive">
<AlertCircle class="h-4 w-4 mr-2" />
<Alert.Title>Failed to Create Stack</Alert.Title>
- <Alert.Description>{form.error}</Alert.Description>
+ <Alert.Description>{apiError}</Alert.Description>
</Alert.Root>
{/if}
- <!-- Stack Editor -->
- <form
- method="POST"
- class="space-y-6"
- use:enhance={() => {
- saving = true;
- return async ({ update }) => {
- saving = false;
- await update();
- };
- }}
- >
+ <form class="space-y-6" onsubmit={preventDefault(handleSubmit)}>
<Card.Root class="border shadow-sm">
<Card.Header>
<div class="flex items-center gap-3">
@@ -128,17 +150,14 @@
bind:value={name}
required
placeholder="e.g., my-web-app"
+ disabled={saving}
/>
</div>
<div class="grid w-full items-center gap-1.5">
<Label for="compose-editor">Docker Compose File</Label>
- <!-- Hidden textarea to submit the form value -->
- <input type="hidden" name="composeContent" value={composeContent} />
-
- <!-- YamlEditor Component -->
- <YamlEditor bind:value={composeContent} />
+ <YamlEditor bind:value={composeContent} readOnly={saving} />
<p class="text-xs text-muted-foreground">
Enter a valid compose.yaml file.
@@ -151,11 +170,16 @@
variant="outline"
type="button"
onclick={() => window.history.back()}
+ disabled={saving}
>
<ArrowLeft class="w-4 h-4 mr-2" />
Cancel
</Button>
- <Button type="submit" variant="default" disabled={saving}>
+ <Button
+ type="submit"
+ variant="default"
+ disabled={saving || !name || !composeContent}
+ >
{#if saving}
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
{:else}
diff --git a/src/routes/volumes/+page.svelte b/src/routes/volumes/+page.svelte
index 851e03230..54d0dc6c2 100644
--- a/src/routes/volumes/+page.svelte
+++ b/src/routes/volumes/+page.svelte
@@ -2,22 +2,33 @@
import * as Card from "$lib/components/ui/card/index.js";
import { Button } from "$lib/components/ui/button/index.js";
import { toast } from "svelte-sonner";
- import { Plus, AlertCircle, HardDrive, Database } from "@lucide/svelte";
+ import {
+ Plus,
+ AlertCircle,
+ HardDrive,
+ Database,
+ Trash2,
+ Loader2,
+ ChevronDown,
+ } from "@lucide/svelte";
import UniversalTable from "$lib/components/universal-table.svelte";
import { columns } from "./columns";
import type { PageData } from "./$types";
import * as Alert from "$lib/components/ui/alert/index.js";
import { invalidateAll } from "$app/navigation";
import CreateVolumeDialog from "./create-volume-dialog.svelte";
+ import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js";
+ import * as Dialog from "$lib/components/ui/dialog/index.js";
let { data }: { data: PageData } = $props();
let { error } = data;
let volumes = $state(data.volumes);
- let selectedIds = $state([]);
-
+ let selectedIds = $state<string[]>([]);
let isRefreshing = $state(false);
let isCreateDialogOpen = $state(false);
let isCreatingVolume = $state(false);
+ let isDeletingSelected = $state(false);
+ let isConfirmDeleteDialogOpen = $state(false);
const totalVolumes = $derived(volumes?.length || 0);
@@ -55,7 +66,6 @@
toast.success(`Volume "${result.volume.Name}" created successfully.`);
isCreateDialogOpen = false;
- // Force a refresh with a short timeout to ensure Docker API has time to register the volume
setTimeout(async () => {
await refreshData();
}, 500);
@@ -79,6 +89,56 @@
}
}
+ async function handleDeleteSelected() {
+ isDeletingSelected = true;
+ const deletePromises = selectedIds.map(async (name) => {
+ try {
+ const volume = volumes?.find((v) => v.name === name);
+ if (volume?.inUse) {
+ toast.error(`Volume "${name}" is in use and cannot be deleted.`);
+ return { name, success: false, error: "Volume in use" };
+ }
+
+ const response = await fetch(`/api/volumes/${name}`, {
+ method: "DELETE",
+ });
+ const result = await response.json();
+ if (!response.ok) {
+ throw new Error(
+ result.error || `HTTP error! status: ${response.status}`
+ );
+ }
+ return { name, success: true };
+ } catch (err: any) {
+ console.error(`Failed to delete volume "${name}":`, err);
+ return { name, success: false, error: err.message };
+ }
+ });
+
+ const results = await Promise.all(deletePromises);
+ const successfulDeletes = results.filter((r) => r.success);
+ const failedDeletes = results.filter((r) => !r.success);
+
+ if (successfulDeletes.length > 0) {
+ toast.success(
+ `Successfully deleted ${successfulDeletes.length} volume(s).`
+ );
+ setTimeout(async () => {
+ await refreshData();
+ selectedIds = [];
+ }, 500);
+ }
+
+ failedDeletes.forEach((r) => {
+ if (r.error !== "Volume in use") {
+ toast.error(`Failed to delete volume "${r.name}": ${r.error}`);
+ }
+ });
+
+ isDeletingSelected = false;
+ isConfirmDeleteDialogOpen = false;
+ }
+
function openCreateDialog() {
isCreateDialogOpen = true;
}
@@ -139,7 +199,39 @@
<Card.Description>Manage persistent data storage</Card.Description>
</div>
<div class="flex items-center gap-2">
- <Button variant="outline" size="sm" onclick={openCreateDialog}>
+ {#if selectedIds.length > 0}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button
+ {...props}
+ variant="outline"
+ disabled={isDeletingSelected}
+ aria-label={`Group actions for ${selectedIds.length} selected volume(s)`}
+ >
+ {#if isDeletingSelected}
+ <Loader2 class="w-4 h-4 animate-spin" />
+ Processing...
+ {:else}
+ Actions ({selectedIds.length})
+ <ChevronDown class="w-4 h-4" />
+ {/if}
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content>
+ <DropdownMenu.Item
+ onclick={() => (isConfirmDeleteDialogOpen = true)}
+ class="text-red-500 focus:!text-red-700"
+ disabled={isDeletingSelected}
+ >
+ <Trash2 class="w-4 h-4" />
+ Delete Selected
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ {/if}
+ <Button variant="secondary" onclick={openCreateDialog}>
<Plus class="w-4 h-4" />
Create Volume
</Button>
@@ -151,6 +243,7 @@
<UniversalTable
data={volumes}
{columns}
+ idKey="name"
display={{
filterPlaceholder: "Search volumes...",
noResultsMessage: "No volumes found",
@@ -177,4 +270,38 @@
isCreating={isCreatingVolume}
onSubmit={handleCreateVolumeSubmit}
/>
+
+ <Dialog.Root bind:open={isConfirmDeleteDialogOpen}>
+ <Dialog.Content>
+ <Dialog.Header>
+ <Dialog.Title>Delete Selected Volumes</Dialog.Title>
+ <Dialog.Description>
+ Are you sure you want to delete {selectedIds.length} selected volume(s)?
+ This action cannot be undone. Volumes currently in use by containers will
+ not be deleted.
+ </Dialog.Description>
+ </Dialog.Header>
+ <div class="flex justify-end gap-3 pt-6">
+ <Button
+ variant="outline"
+ onclick={() => (isConfirmDeleteDialogOpen = false)}
+ disabled={isDeletingSelected}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onclick={handleDeleteSelected}
+ disabled={isDeletingSelected}
+ >
+ {#if isDeletingSelected}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ Deleting...
+ {:else}
+ Delete {selectedIds.length} Volume{#if selectedIds.length > 1}s{/if}
+ {/if}
+ </Button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Root>
</div>
diff --git a/static/img/arcane.png b/static/img/arcane.png
new file mode 100644
index 000000000..f3ff76e69
Binary files /dev/null and b/static/img/arcane.png differ
diff --git a/static/img/nautix_logo_new.png b/static/img/nautix_logo_new.png
deleted file mode 100644
index 24e00b2d0..000000000
Binary files a/static/img/nautix_logo_new.png and /dev/null differ