Skip to content

Modern Docker Management, Designed for Everyone

feat: implement full docker compose spec (#45)

Kyle Mendell103707fe353b
diff --git a/src/lib/components/action-buttons.svelte b/src/lib/components/action-buttons.svelte
new file mode 100644
index 000000000..a6aaf7ac9
--- /dev/null
+++ b/src/lib/components/action-buttons.svelte
@@ -0,0 +1,159 @@
+<script lang="ts">
+ import { Button } from "$lib/components/ui/button/index.js";
+ import {
+ Play,
+ StopCircle,
+ RotateCcw,
+ Download,
+ Rocket,
+ RefreshCw,
+ Trash2,
+ Loader2,
+ } from "@lucide/svelte";
+
+ type TargetType = "container" | "stack";
+ type LoadingStates = {
+ start?: boolean;
+ stop?: boolean;
+ restart?: boolean;
+ pull?: boolean;
+ deploy?: boolean;
+ redeploy?: boolean;
+ remove?: boolean;
+ };
+
+ let {
+ id,
+ type = "container",
+ state = "stopped",
+ loading = {},
+ formAction = null,
+ }: {
+ id: string;
+ type?: TargetType;
+ state?: string;
+ loading?: LoadingStates;
+ formAction?: string | null;
+ } = $props();
+
+ const isRunning = $derived(
+ state === "running" || (type === "stack" && state === "partially running")
+ );
+</script>
+
+<div class="flex items-center gap-2">
+ {#if !isRunning}
+ <Button
+ type="submit"
+ variant="default"
+ disabled={loading.start}
+ size="sm"
+ class="font-medium h-9"
+ formaction={formAction || "?/start"}
+ >
+ {#if loading.start}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {:else}
+ <Play class="w-4 h-4 mr-2" />
+ {/if}
+ {type === "stack" ? "Deploy" : "Start"}
+ </Button>
+ {:else}
+ <Button
+ type="submit"
+ variant="secondary"
+ disabled={loading.stop}
+ size="sm"
+ class="font-medium h-9"
+ formaction={formAction || "?/stop"}
+ >
+ {#if loading.stop}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {:else}
+ <StopCircle class="w-4 h-4 mr-2" />
+ {/if}
+ Stop
+ </Button>
+
+ <Button
+ type="submit"
+ variant="outline"
+ disabled={loading.restart}
+ size="sm"
+ class="font-medium h-9"
+ formaction={formAction || "?/restart"}
+ name="action"
+ value="restart"
+ >
+ {#if loading.restart}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {:else}
+ <RotateCcw class="w-4 h-4 mr-2" />
+ {/if}
+ Restart
+ </Button>
+ {/if}
+
+ {#if type === "container"}
+ <Button
+ type="submit"
+ variant="destructive"
+ disabled={loading.remove}
+ size="sm"
+ class="font-medium h-9"
+ formaction={formAction || "?/remove"}
+ onclick={(e) => {
+ if (!confirm(`Are you sure you want to remove this ${type}?`)) {
+ e.preventDefault();
+ return false;
+ }
+ }}
+ >
+ {#if loading.remove}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {:else}
+ <Trash2 class="w-4 h-4 mr-2" />
+ {/if}
+ Remove
+ </Button>
+ {:else}
+ <!-- Stack-specific actions -->
+ <Button
+ type="submit"
+ variant="outline"
+ disabled={loading.pull}
+ size="sm"
+ class="font-medium h-9"
+ formaction={formAction || "?/pull"}
+ >
+ {#if loading.pull}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {:else}
+ <Download class="w-4 h-4 mr-2" />
+ {/if}
+ Pull
+ </Button>
+
+ <Button
+ type="submit"
+ variant="destructive"
+ disabled={loading.remove}
+ size="sm"
+ class="font-medium h-9"
+ formaction={formAction || "?/remove"}
+ onclick={(e) => {
+ if (!confirm(`Are you sure you want to remove this ${type}?`)) {
+ e.preventDefault();
+ return false;
+ }
+ }}
+ >
+ {#if loading.remove}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {:else}
+ <Trash2 class="w-4 h-4 mr-2" />
+ {/if}
+ Remove
+ </Button>
+ {/if}
+</div>
diff --git a/src/lib/components/badges/custom-badge.svelte b/src/lib/components/badges/custom-badge.svelte
new file mode 100644
index 000000000..c933c42a3
--- /dev/null
+++ b/src/lib/components/badges/custom-badge.svelte
@@ -0,0 +1,195 @@
+<script lang="ts">
+ import type { Icon as IconType } from "@lucide/svelte";
+
+ let {
+ variant = "default",
+ text = "",
+ bgColor = undefined,
+ textColor = undefined,
+ size = "default",
+ rounded = true,
+ className = "",
+ icon = undefined,
+ iconClass = "w-3.5 h-3.5 mr-1",
+ }: {
+ variant?: "default" | "secondary" | "destructive" | "outline" | "status";
+ text: string;
+ bgColor?: string;
+ textColor?: string;
+ size?: "default" | "sm" | "lg";
+ rounded?: boolean;
+ className?: string;
+ icon?: typeof IconType;
+ iconClass?: string;
+ } = $props();
+
+ // Map variant to style variables
+ function getVariantStyles() {
+ const variants = {
+ default: {
+ bg: "var(--primary)",
+ color: "var(--primary-foreground)",
+ border: "var(--primary)",
+ },
+ secondary: {
+ bg: "var(--secondary)",
+ color: "var(--secondary-foreground)",
+ border: "var(--secondary)",
+ },
+ destructive: {
+ bg: "var(--destructive)",
+ color: "var(--destructive-foreground)",
+ border: "var(--destructive)",
+ },
+ outline: {
+ bg: "transparent",
+ color: "var(--foreground)",
+ border: "var(--border)",
+ },
+ status: {
+ bg: "transparent",
+ color: "var(--foreground)",
+ border: "transparent",
+ },
+ };
+
+ return variants[variant];
+ }
+
+ // Extended color map for all badge types
+ function getCustomStyles() {
+ const colorMap: Record<string, string> = {
+ // Backgrounds
+ "amber-100": "rgb(254 243 199)",
+ "green-100": "rgb(220 252 231)",
+ "red-100": "rgb(254 226 226)",
+ "blue-100": "rgb(219 234 254)",
+ "gray-100": "rgb(243 244 246)",
+ "purple-100": "rgb(237 233 254)",
+ "indigo-100": "rgb(224 231 255)",
+
+ // Text colors (darker variants)
+ "amber-900": "rgb(120 53 15)",
+ "green-900": "rgb(20 83 45)",
+ "red-900": "rgb(127 29 29)",
+ "blue-900": "rgb(30 58 138)",
+ "gray-900": "rgb(17 24 39)",
+ "purple-900": "rgb(88 28 135)",
+ "indigo-900": "rgb(49 46 129)",
+
+ // Basic colors
+ black: "rgb(0 0 0)",
+ white: "rgb(255 255 255)",
+
+ // Status colors
+ running: "rgb(34 197 94)", // green-500
+ partially: "rgb(245 158 11)", // amber-500
+ stopped: "rgb(156 163 175)", // gray-400
+ error: "rgb(239 68 68)", // red-500
+ };
+
+ const style = {
+ bg: bgColor && bgColor in colorMap ? colorMap[bgColor] : undefined,
+ color:
+ textColor && textColor in colorMap ? colorMap[textColor] : undefined,
+ border: bgColor && bgColor in colorMap ? colorMap[bgColor] : undefined,
+ };
+
+ return style;
+ }
+
+ // Add status presets for common status badges
+ function applyStatusPreset(): {
+ bg?: string;
+ color?: string;
+ border?: string;
+ } {
+ if (variant !== "status" || !text) return {};
+
+ const statusStyles: Record<
+ string,
+ { bg: string; color: string; border: string }
+ > = {
+ running: {
+ bg: "rgba(34, 197, 94, 0.15)",
+ color: "rgb(21, 128, 61)",
+ border: "rgba(34, 197, 94, 0.15)",
+ },
+ "partially running": {
+ bg: "rgba(245, 158, 11, 0.15)",
+ color: "rgb(180, 83, 9)",
+ border: "rgba(245, 158, 11, 0.15)",
+ },
+ stopped: {
+ bg: "rgba(156, 163, 175, 0.15)",
+ color: "rgb(75, 85, 99)",
+ border: "rgba(156, 163, 175, 0.15)",
+ },
+ error: {
+ bg: "rgba(239, 68, 68, 0.15)",
+ color: "rgb(185, 28, 28)",
+ border: "rgba(239, 68, 68, 0.15)",
+ },
+ pending: {
+ bg: "rgba(59, 130, 246, 0.15)",
+ color: "rgb(37, 99, 235)",
+ border: "rgba(59, 130, 246, 0.15)",
+ },
+ external: {
+ bg: "rgba(245, 158, 11, 0.15)",
+ color: "rgb(180, 83, 9)",
+ border: "rgba(245, 158, 11, 0.15)",
+ },
+ managed: {
+ bg: "rgba(34, 197, 94, 0.15)",
+ color: "rgb(21, 128, 61)",
+ border: "rgba(34, 197, 94, 0.15)",
+ },
+ };
+
+ // Check for exact match or partial match
+ for (const [key, style] of Object.entries(statusStyles)) {
+ if (text.toLowerCase() === key.toLowerCase()) {
+ return style;
+ }
+ }
+
+ // Text doesn't match any preset
+ return {};
+ }
+
+ // Combine variant and custom styles
+ const baseStyles = $derived(getVariantStyles());
+ const customStyles = $derived(getCustomStyles());
+ const statusStyles = $derived(applyStatusPreset());
+
+ const style = $derived(
+ [
+ `background-color: ${customStyles.bg || statusStyles.bg || baseStyles.bg};`,
+ `color: ${customStyles.color || statusStyles.color || baseStyles.color};`,
+ `border: 1px solid ${customStyles.border || statusStyles.border || baseStyles.border};`,
+ ].join(" ")
+ );
+
+ // Size classes
+ const sizeClass = $derived(
+ size === "sm"
+ ? "text-xs py-0 px-2"
+ : size === "lg"
+ ? "text-sm py-1 px-3"
+ : "text-xs py-0.5 px-2.5"
+ );
+
+ const roundedClass = $derived(rounded ? "rounded-full" : "rounded-md");
+</script>
+
+<span
+ class={`inline-flex items-center font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${sizeClass} ${roundedClass} ${className}`}
+ {style}
+>
+ {#if icon}
+ {@const Icon = icon}
+ <Icon class={iconClass} />
+ {/if}
+ {text}
+</span>
diff --git a/src/lib/components/docker/StatusBadge.svelte b/src/lib/components/docker/StatusBadge.svelte
deleted file mode 100644
index 41250cd43..000000000
--- a/src/lib/components/docker/StatusBadge.svelte
+++ /dev/null
@@ -1,39 +0,0 @@
-<script lang="ts">
- import { Badge } from "$lib/components/ui/badge/index.js"; // Assuming you use shadcn-svelte Badge
-
- type ContainerState =
- | "created"
- | "running"
- | "paused"
- | "restarting"
- | "removing"
- | "exited"
- | "dead"
- | string; // Allow other potential states
-
- let { state }: { state: ContainerState } = $props();
-
- // Determine badge variant and text based on state
- let variant: "default" | "secondary" | "destructive" | "outline" =
- $derived.by(() => {
- switch (state) {
- case "running":
- return "default"; // Typically green/primary in shadcn
- case "exited":
- case "dead":
- return "destructive"; // Red
- case "paused":
- case "restarting":
- case "created":
- return "secondary"; // Gray/Yellowish
- default:
- return "outline"; // Default outline for unknown states
- }
- });
-
- let text = $derived(state.charAt(0).toUpperCase() + state.slice(1)); // Capitalize state
-</script>
-
-<Badge {variant} class="capitalize">
- {text}
-</Badge>
diff --git a/src/lib/components/universal-modal.svelte b/src/lib/components/universal-modal.svelte
new file mode 100644
index 000000000..878a3fae7
--- /dev/null
+++ b/src/lib/components/universal-modal.svelte
@@ -0,0 +1,92 @@
+<script lang="ts">
+ import * as Dialog from "$lib/components/ui/dialog/index.js";
+ import { Button } from "$lib/components/ui/button/index.js";
+ import {
+ AlertCircle,
+ CheckCircle2,
+ Info,
+ AlertTriangle,
+ X,
+ } from "@lucide/svelte";
+
+ type MessageType = "success" | "error" | "warning" | "info";
+
+ let {
+ open = $bindable(false),
+ type = "info",
+ title = "",
+ message = "",
+ okText = "OK",
+ cancelText = "Cancel",
+ onConfirm = undefined,
+ showCancel = false,
+ }: {
+ open?: boolean;
+ type?: MessageType;
+ title?: string;
+ message?: string;
+ okText?: string;
+ cancelText?: string;
+ onConfirm?: () => void;
+ showCancel?: boolean;
+ } = $props();
+
+ // Determine icon and color based on type
+ const iconMap = {
+ success: CheckCircle2,
+ error: AlertCircle,
+ warning: AlertTriangle,
+ info: Info,
+ };
+
+ const colorMap = {
+ success: "text-green-500",
+ error: "text-red-500",
+ warning: "text-amber-500",
+ info: "text-blue-500",
+ };
+
+ const Icon = iconMap[type];
+ const iconColor = colorMap[type];
+
+ function handleConfirm() {
+ if (onConfirm) onConfirm();
+ open = false;
+ }
+</script>
+
+<Dialog.Root bind:open>
+ <Dialog.Content class="sm:max-w-[425px]">
+ <div class="flex items-start gap-4">
+ <div class={`${iconColor} shrink-0`}>
+ <Icon class="h-6 w-6" />
+ </div>
+
+ <div class="flex-1">
+ <Dialog.Header>
+ <Dialog.Title>{title}</Dialog.Title>
+ {#if message}
+ <Dialog.Description>
+ {message}
+ </Dialog.Description>
+ {/if}
+ </Dialog.Header>
+ </div>
+ </div>
+
+ <Dialog.Footer>
+ {#if showCancel}
+ <Button type="button" variant="outline" onclick={() => (open = false)}>
+ {cancelText}
+ </Button>
+ {/if}
+ <Button
+ type="button"
+ onclick={handleConfirm}
+ variant={type === "error" ? "destructive" : "default"}
+ >
+ {okText}
+ </Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+</Dialog.Root>
diff --git a/src/lib/components/yaml-editor.svelte b/src/lib/components/yaml-editor.svelte
index 11276d614..5ea5f8c6d 100644
--- a/src/lib/components/yaml-editor.svelte
+++ b/src/lib/components/yaml-editor.svelte
@@ -47,7 +47,6 @@
return diagnostics;
}
- // Use the oneDark theme
const extensions = $derived([
yaml(),
lintGutter(),
diff --git a/src/lib/services/compose.ts b/src/lib/services/compose.ts
index f62974ce0..6b45658a4 100644
--- a/src/lib/services/compose.ts
+++ b/src/lib/services/compose.ts
@@ -415,6 +415,7 @@ export async function updateStack(
export async function startStack(stackId: string): Promise<boolean> {
try {
const compose = await getComposeInstance(stackId);
+ await compose.pull();
await compose.up();
return true;
} catch (err: unknown) {
@@ -480,3 +481,163 @@ export async function removeStack(stackId: string): Promise<boolean> {
throw new Error(`Failed to remove stack: ${errorMessage}`);
}
}
+
+/**
+ * Discover existing Docker Compose stacks by analyzing container labels
+ * @returns {Promise<Stack[]>} External stacks discovered
+ */
+export async function discoverExternalStacks(): Promise<Stack[]> {
+ try {
+ const docker = getDockerClient();
+ const containers = await docker.listContainers({ all: true });
+
+ // Docker Compose adds these labels to managed containers
+ const composeProjectLabel = "com.docker.compose.project";
+ const composeServiceLabel = "com.docker.compose.service";
+
+ // Group containers by project
+ const projectMap: Record<string, any[]> = {};
+
+ containers.forEach((container) => {
+ const labels = container.Labels || {};
+ const projectName = labels[composeProjectLabel];
+
+ if (projectName) {
+ if (!projectMap[projectName]) {
+ projectMap[projectName] = [];
+ }
+
+ projectMap[projectName].push({
+ id: container.Id,
+ name: labels[composeServiceLabel] || container.Names[0]?.substring(1),
+ state: {
+ Running: container.State === "running",
+ Status: container.State,
+ ExitCode: 0,
+ },
+ });
+ }
+ });
+
+ // Convert to our Stack format
+ const externalStacks: Stack[] = [];
+
+ for (const [projectName, services] of Object.entries(projectMap)) {
+ // Check if this stack is already in our managed stacks
+ const stackDir = getStackDir(projectName);
+ try {
+ await fs.access(stackDir);
+ // Stack is managed by Arcane, skip it
+ continue;
+ } catch {
+ // Stack is not managed by Arcane, include it
+ }
+
+ const serviceCount = services.length;
+ const runningCount = services.filter((s) => s.state.Running).length;
+
+ let status: Stack["status"] = "stopped";
+ if (runningCount === serviceCount && serviceCount > 0) {
+ status = "running";
+ } else if (runningCount > 0) {
+ status = "partially running";
+ }
+
+ externalStacks.push({
+ id: projectName,
+ name: projectName,
+ services,
+ serviceCount,
+ runningCount,
+ status,
+ isExternal: true,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ });
+ }
+
+ return externalStacks;
+ } catch (err) {
+ console.error("Error discovering external stacks:", err);
+ return [];
+ }
+}
+
+/**
+ * Import an external stack into Arcane
+ *
+ * @param stackId The ID of the external stack to import
+ * @returns The newly imported stack object
+ */
+export async function importExternalStack(stackId: string): Promise<Stack> {
+ // 1. First, check if we can find the stack by ID
+ const docker = getDockerClient();
+ const containers = await docker.listContainers({ all: true });
+
+ // Filter containers that belong to this stack
+ const stackContainers = containers.filter((container) => {
+ const labels = container.Labels || {};
+ return labels["com.docker.compose.project"] === stackId;
+ });
+
+ if (stackContainers.length === 0) {
+ throw new Error(`No containers found for stack '${stackId}'`);
+ }
+
+ // 2. Try to locate the compose file (if available)
+ let composeFilePath = "";
+ const container = stackContainers[0];
+ const labels = container.Labels || {};
+
+ if (labels["com.docker.compose.project.config_files"]) {
+ composeFilePath = labels["com.docker.compose.project.config_files"];
+ }
+
+ // 3. Read the compose file if available, or create a new one
+ let composeContent = "";
+
+ if (composeFilePath) {
+ try {
+ composeContent = await fs.readFile(composeFilePath, "utf8");
+ } catch (err) {
+ console.warn(`Couldn't read compose file at ${composeFilePath}:`, err);
+ // Will generate a new one below
+ }
+ }
+
+ // 4. If we couldn't read the compose file, generate one based on container inspection
+ if (!composeContent) {
+ // Create a basic compose file from container inspection
+ const services: Record<string, any> = {};
+
+ for (const container of stackContainers) {
+ const containerLabels = container.Labels || {};
+ const serviceName =
+ containerLabels["com.docker.compose.service"] ||
+ container.Names[0]?.replace(`/${stackId}_`, "").replace("_1", "") ||
+ `service_${container.Id.substring(0, 8)}`;
+
+ // Inspect the container to get more details
+ const containerDetails = await docker
+ .getContainer(container.Id)
+ .inspect();
+
+ services[serviceName] = {
+ image: container.Image,
+ // Add other properties based on containerDetails
+ };
+ }
+
+ // Generate the compose file content
+ composeContent = `# Generated compose file for imported stack: ${stackId}
+# This was automatically generated by Arcane from an external stack
+# You may need to adjust it manually for correct operation
+
+version: '3'
+services:
+${yaml.dump({ services }).substring(10)}`; // Remove the services: line
+ }
+
+ // 5. Create a new stack in Arcane's managed stacks
+ return await createStack(stackId, composeContent);
+}
diff --git a/src/lib/types/stack.ts b/src/lib/types/stack.ts
index d2a7c8a75..164fefaa8 100644
--- a/src/lib/types/stack.ts
+++ b/src/lib/types/stack.ts
@@ -25,7 +25,8 @@ export interface Stack {
createdAt: string;
updatedAt: string;
composeContent?: string;
- compose?: any; // Don't include this in serialized responses
+ isExternal?: boolean;
+ compose?: any;
}
export interface StackUpdate {
diff --git a/src/lib/types/statuses.ts b/src/lib/types/statuses.ts
new file mode 100644
index 000000000..fd94282dd
--- /dev/null
+++ b/src/lib/types/statuses.ts
@@ -0,0 +1,18 @@
+export const statusConfig = {
+ running: {
+ bgColor: "green-100",
+ textColor: "green-900",
+ },
+ "partially running": {
+ bgColor: "amber-100",
+ textColor: "amber-900",
+ },
+ stopped: {
+ bgColor: "gray-100",
+ textColor: "gray-900",
+ },
+ error: {
+ bgColor: "red-100",
+ textColor: "red-900",
+ },
+};
diff --git a/src/lib/utils.ts b/src/lib/utils.ts
index c650cdecd..f73f5b52e 100644
--- a/src/lib/utils.ts
+++ b/src/lib/utils.ts
@@ -30,3 +30,48 @@ export function formatBytes(bytes: number, decimals = 2): string {
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
}
+
+export const capitalizeFirstLetter = (text: string) => {
+ if (!text) return "";
+ return text.charAt(0).toUpperCase() + text.slice(1);
+};
+
+export function getStatusColor(status: string): { bg: string; text: string } {
+ const statusLower = status.toLowerCase();
+
+ if (statusLower === "running") {
+ return { bg: "green-100", text: "green-900" };
+ } else if (statusLower === "created" || statusLower === "restarting") {
+ return { bg: "blue-100", text: "blue-900" };
+ } else if (statusLower === "paused") {
+ return { bg: "amber-100", text: "amber-900" };
+ } else if (statusLower === "exited" || statusLower === "dead") {
+ return { bg: "red-100", text: "red-900" };
+ } else {
+ return { bg: "gray-100", text: "gray-900" }; // Default for unknown status
+ }
+}
+
+export function formatDate(dateString: string | undefined | null): string {
+ if (!dateString) return "Unknown";
+ try {
+ return new Date(dateString).toLocaleString();
+ } catch (e) {
+ return "Invalid Date";
+ }
+}
+
+// Function to format logs with some basic highlighting
+export function formatLogLine(line: string): string {
+ if (
+ line.includes("ERROR") ||
+ line.includes("FATAL") ||
+ line.includes("WARN")
+ ) {
+ return `<span class="text-red-400">${line}</span>`;
+ }
+ if (line.includes("INFO")) {
+ return `<span class="text-blue-400">${line}</span>`;
+ }
+ return line;
+}
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index 47d24341e..3f1346023 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -3,11 +3,13 @@
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";
let { children, data } = $props();
- // We'll pass this directly to the navbar component
const versionInformation = data.versionInformation;
+
+ const isNavigating = $derived($navigating !== null);
</script>
<svelte:head><title>Arcane</title></svelte:head>
@@ -15,6 +17,11 @@
<ModeWatcher />
<Toaster />
+<!-- Apply a loading state to the page during navigation -->
+{#if isNavigating}
+ <!-- add a loading indicator heret -->
+{/if}
+
<div class="flex min-h-screen bg-background">
<Nav {versionInformation} />
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index e4b9388cf..c8491a28f 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -2,9 +2,7 @@
import type { PageData } from "./$types";
import * as Card from "$lib/components/ui/card/index.js";
import { Button } from "$lib/components/ui/button/index.js";
- import * as Table from "$lib/components/ui/table/index.js";
import UniversalTable from "$lib/components/universal-table.svelte";
- import StatusBadge from "$lib/components/docker/StatusBadge.svelte";
import { dashboardContainerColumns, dashboardImageColumns } from "./columns";
import {
AlertCircle,
@@ -20,7 +18,6 @@
import * as Alert from "$lib/components/ui/alert/index.js";
import { Progress } from "$lib/components/ui/progress/index.js";
import { Badge } from "$lib/components/ui/badge/index.js";
- import { invalidateAll } from "$app/navigation";
import { formatBytes } from "$lib/utils";
let { data }: { data: PageData } = $props();
diff --git a/src/routes/api/stacks/import/+server.ts b/src/routes/api/stacks/import/+server.ts
new file mode 100644
index 000000000..ca6294f3b
--- /dev/null
+++ b/src/routes/api/stacks/import/+server.ts
@@ -0,0 +1,41 @@
+import { json } from "@sveltejs/kit";
+import type { RequestHandler } from "./$types";
+import { importExternalStack } from "$lib/services/compose";
+
+export const POST: RequestHandler = async ({ request }) => {
+ const data = await request.formData();
+ const stackId = data.get("stackId")?.toString();
+ const stackName = data.get("stackName")?.toString();
+
+ if (!stackId) {
+ return json(
+ { success: false, error: "Stack ID is required" },
+ { status: 400 }
+ );
+ }
+
+ try {
+ const importedStack = await importExternalStack(stackId);
+
+ console.log(
+ `Successfully imported stack: ${stackId} (${
+ stackName || importedStack.name
+ })`
+ );
+
+ return json({
+ success: true,
+ stack: importedStack,
+ message: `Successfully imported stack ${importedStack.name}`,
+ });
+ } catch (err) {
+ console.error(`Error importing stack ${stackId}:`, err);
+ return json(
+ {
+ success: false,
+ error: err instanceof Error ? err.message : "Failed to import stack",
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/src/routes/columns.ts b/src/routes/columns.ts
index 1df21da46..b47472a07 100644
--- a/src/routes/columns.ts
+++ b/src/routes/columns.ts
@@ -4,7 +4,9 @@ import type {
ServiceImage,
} from "$lib/services/docker-service";
import { formatBytes } from "$lib/utils";
-import StatusBadge from "$lib/components/docker/StatusBadge.svelte";
+import CustomBadge from "$lib/components/badges/custom-badge.svelte";
+import { capitalizeFirstLetter } from "$lib/utils";
+import { statusConfig } from "$lib/types/statuses";
import { renderComponent } from "$lib/components/ui/data-table/index.js";
// Column definitions for the dashboard containers table
@@ -21,9 +23,21 @@ export const dashboardContainerColumns: ColumnDef<ServiceContainer>[] = [
},
{
accessorKey: "state",
- header: "State",
+ header: "Status",
cell: ({ row }) => {
- return renderComponent(StatusBadge, { state: row.original.state });
+ const config = statusConfig[
+ row.getValue("state") as keyof typeof statusConfig
+ ] || {
+ bgColor: "blue-100",
+ textColor: "blue-900",
+ };
+
+ return renderComponent(CustomBadge, {
+ variant: "status",
+ rounded: true,
+ text: capitalizeFirstLetter(row.getValue("state") as string),
+ ...config,
+ });
},
},
{
diff --git a/src/routes/containers/[id]/+page.server.ts b/src/routes/containers/[id]/+page.server.ts
index 81c379700..2a3fe8a86 100644
--- a/src/routes/containers/[id]/+page.server.ts
+++ b/src/routes/containers/[id]/+page.server.ts
@@ -5,20 +5,17 @@ import {
stopContainer,
restartContainer,
removeContainer,
- getContainerLogs, // Add this import
+ getContainerLogs,
} from "$lib/services/docker-service";
import { error, fail, redirect } from "@sveltejs/kit";
-import { invalidateAll } from "$app/navigation"; // Used client-side, but good practice to know
export const load: PageServerLoad = async ({ params }) => {
const containerId = params.id;
try {
- // Fetch container details and logs concurrently for better performance
const [container, logs] = await Promise.all([
getContainer(containerId),
getContainerLogs(containerId, { tail: 100 }).catch((err) => {
- // Handle log retrieval errors gracefully
console.error(`Failed to retrieve logs for ${containerId}:`, err);
return "Failed to load logs. This could be because the container hasn't been started yet.";
}),
@@ -36,7 +33,6 @@ export const load: PageServerLoad = async ({ params }) => {
};
} catch (err: any) {
console.error(`Failed to load container ${containerId}:`, err);
- // Use the error helper for consistency
error(500, {
message:
err.message || `Failed to load container details for "${containerId}".`,
@@ -50,7 +46,6 @@ export const actions: Actions = {
const containerId = params.id;
try {
await startContainer(containerId);
- // No redirect needed, page data will refresh via invalidateAll on client
return { success: true, message: "Container started." };
} catch (err: any) {
return fail(500, { error: err.message });
diff --git a/src/routes/containers/[id]/+page.svelte b/src/routes/containers/[id]/+page.svelte
index abe03f0eb..63803e778 100644
--- a/src/routes/containers/[id]/+page.svelte
+++ b/src/routes/containers/[id]/+page.svelte
@@ -2,16 +2,10 @@
import type { PageData, ActionData } from "./$types";
import * as Card from "$lib/components/ui/card/index.js";
import { Button } from "$lib/components/ui/button/index.js";
- import StatusBadge from "$lib/components/docker/StatusBadge.svelte";
import {
ArrowLeft,
- Loader2,
AlertCircle,
RefreshCw,
- PlayCircle,
- StopCircle,
- RotateCw,
- Trash2,
HardDrive,
Clock,
Network,
@@ -23,6 +17,14 @@
import * as Alert from "$lib/components/ui/alert/index.js";
import { Separator } from "$lib/components/ui/separator/index.js";
import { Badge } from "$lib/components/ui/badge/index.js";
+ import ActionButtons from "$lib/components/action-buttons.svelte";
+ import CustomBadge from "$lib/components/badges/custom-badge.svelte";
+ import {
+ capitalizeFirstLetter,
+ getStatusColor,
+ formatDate,
+ formatLogLine,
+ } from "$lib/utils";
let { data, form }: { data: PageData; form: ActionData } = $props();
let { container, logs } = $derived(data);
@@ -33,31 +35,6 @@
let removing = $state(false);
let isRefreshing = $state(false);
- function formatDate(dateString: string | undefined | null): string {
- if (!dateString) return "Unknown";
- try {
- return new Date(dateString).toLocaleString();
- } catch (e) {
- return "Invalid Date";
- }
- }
-
- // Function to format logs with some basic highlighting
- function formatLogLine(line: string): string {
- if (
- line.includes("ERROR") ||
- line.includes("FATAL") ||
- line.includes("WARN")
- ) {
- return `<span class="text-red-400">${line}</span>`;
- }
- if (line.includes("INFO")) {
- return `<span class="text-blue-400">${line}</span>`;
- }
- return line;
- }
-
- // Format all logs
let formattedLogs = $derived(
logs ? logs.split("\n").map(formatLogLine).join("\n") : ""
);
@@ -113,135 +90,46 @@
{container?.name || "Container Details"}
</h1>
{#if container}
- <StatusBadge state={container.state?.Status ?? "unknown"} />
+ <CustomBadge
+ variant="status"
+ text={capitalizeFirstLetter(container.state?.Status || "unknown")}
+ bgColor={getStatusColor(container.state?.Status || "unknown").bg}
+ textColor={getStatusColor(container.state?.Status || "unknown")
+ .text}
+ iconClass="w-3 h-3 mr-1"
+ />
{/if}
</div>
</div>
{#if container}
<div class="flex gap-2 flex-wrap">
- <Button
- variant="outline"
- size="sm"
- onclick={refreshData}
- disabled={isRefreshing}
- class="h-9"
- >
- <RefreshCw
- class={`h-4 w-4 mr-2 ${isRefreshing ? "animate-spin" : ""}`}
- />
- Refresh
- </Button>
-
- {#if container.state?.Running}
- <form
- method="POST"
- action="?/stop"
- use:enhance={() => {
- stopping = true;
- return async ({ update }) => {
- await update({ reset: false });
- };
- }}
- >
- <Button
- type="submit"
- variant="secondary"
- disabled={stopping}
- size="sm"
- class="font-medium h-9"
- >
- {#if stopping}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
- {:else}
- <StopCircle class="w-4 h-4 mr-2" />
- {/if}
- Stop
- </Button>
- </form>
- <form
- method="POST"
- action="?/restart"
- use:enhance={() => {
- restarting = true;
- return async ({ update }) => {
- await update({ reset: false });
- };
- }}
- >
- <Button
- type="submit"
- variant="outline"
- disabled={restarting}
- size="sm"
- class="font-medium h-9"
- >
- {#if restarting}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
- {:else}
- <RotateCw class="w-4 h-4 mr-2" />
- {/if}
- Restart
- </Button>
- </form>
- {:else if container.state?.Status === "exited" || container.state?.Status === "created"}
- <form
- method="POST"
- action="?/start"
- use:enhance={() => {
- starting = true;
- return async ({ update }) => {
- await update({ reset: false });
- };
- }}
- >
- <Button
- type="submit"
- variant="default"
- disabled={starting}
- size="sm"
- class="font-medium h-9"
- >
- {#if starting}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
- {:else}
- <PlayCircle class="w-4 h-4 mr-2" />
- {/if}
- Start
- </Button>
- </form>
- {/if}
+ <!-- Use ActionButtons for container actions -->
<form
method="POST"
- action="?/remove"
+ action={container.state?.Running ? "?/stop" : "?/start"}
use:enhance={() => {
- if (
- !confirm(
- `Are you sure you want to remove container "${container?.name}"?`
- )
- ) {
- return;
+ if (container.state?.Running) {
+ stopping = true;
+ } else {
+ starting = true;
}
- removing = true;
return async ({ update }) => {
await update({ reset: false });
};
}}
>
- <Button
- type="submit"
- variant="destructive"
- disabled={removing}
- size="sm"
- class="font-medium h-9"
- >
- {#if removing}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
- {:else}
- <Trash2 class="w-4 h-4 mr-2" />
- {/if}
- Remove
- </Button>
+ <ActionButtons
+ id={container.id}
+ type="container"
+ state={container.state?.Running ? "running" : "stopped"}
+ loading={{
+ start: starting,
+ stop: stopping,
+ restart: restarting,
+ remove: removing,
+ }}
+ />
</form>
</div>
{/if}
diff --git a/src/routes/containers/columns.ts b/src/routes/containers/columns.ts
index 2c81090de..4b12a6ad9 100644
--- a/src/routes/containers/columns.ts
+++ b/src/routes/containers/columns.ts
@@ -2,7 +2,9 @@ import type { ServiceContainer } from "$lib/services/docker-service";
import type { ColumnDef } from "@tanstack/table-core";
import { renderComponent } from "$lib/components/ui/data-table/index.js";
import DataTableActions from "./ContainerActions.svelte";
-import StatusBadge from "$lib/components/docker/StatusBadge.svelte";
+import { capitalizeFirstLetter } from "$lib/utils";
+import { statusConfig } from "$lib/types/statuses";
+import CustomBadge from "$lib/components/badges/custom-badge.svelte";
import IdCell from "./IdCell.svelte";
export const columns: ColumnDef<ServiceContainer>[] = [
@@ -24,9 +26,21 @@ export const columns: ColumnDef<ServiceContainer>[] = [
},
{
accessorKey: "state",
- header: "State",
+ header: "Status",
cell: ({ row }) => {
- return renderComponent(StatusBadge, { state: row.original.state });
+ const config = statusConfig[
+ row.getValue("state") as keyof typeof statusConfig
+ ] || {
+ bgColor: "blue-100",
+ textColor: "blue-900",
+ };
+
+ return renderComponent(CustomBadge, {
+ variant: "status",
+ rounded: true,
+ text: capitalizeFirstLetter(row.getValue("state") as string),
+ ...config,
+ });
},
},
{
diff --git a/src/routes/stacks/+page.server.ts b/src/routes/stacks/+page.server.ts
index 00a56795a..86db5c431 100644
--- a/src/routes/stacks/+page.server.ts
+++ b/src/routes/stacks/+page.server.ts
@@ -1,12 +1,29 @@
import { error } from "@sveltejs/kit";
-import { loadComposeStacks } from "$lib/services/compose";
+import {
+ loadComposeStacks,
+ discoverExternalStacks,
+} from "$lib/services/compose";
/** @type {import('./$types').PageServerLoad} */
export async function load() {
try {
- const stacks = await loadComposeStacks();
+ // Get managed stacks
+ const managedStacks = await loadComposeStacks();
+
+ // Discover external stacks
+ const externalStacks = await discoverExternalStacks();
+
+ // Combine both, ensuring no duplicates by ID
+ const combinedStacks = [...managedStacks];
+
+ for (const externalStack of externalStacks) {
+ if (!combinedStacks.some((stack) => stack.id === externalStack.id)) {
+ combinedStacks.push(externalStack);
+ }
+ }
+
return {
- stacks,
+ stacks: combinedStacks,
};
} catch (err) {
console.error("Failed to load stacks:", err);
diff --git a/src/routes/stacks/+page.svelte b/src/routes/stacks/+page.svelte
index 996181f0e..55f39017c 100644
--- a/src/routes/stacks/+page.svelte
+++ b/src/routes/stacks/+page.svelte
@@ -7,8 +7,6 @@
AlertCircle,
Layers,
RefreshCw,
- Filter,
- ArrowUpDown,
Upload,
FileStack,
} from "@lucide/svelte";
@@ -16,12 +14,35 @@
import { columns } from "./columns";
import * as Alert from "$lib/components/ui/alert/index.js";
import { invalidateAll } from "$app/navigation";
+ import { enhance } from "$app/forms";
+ import UniversalModal from "$lib/components/universal-modal.svelte";
let { data }: { data: PageData } = $props();
const { stacks, error } = data;
let selectedIds = $state([]);
let isRefreshing = $state(false);
+ let isRemoving = $state(false);
+ let deleteDialogOpen = $state(false);
+ let id = $state(""); // Store the ID of the stack to be deleted
+
+ // Message Dialog state
+ let dialogOpen = $state(false);
+ let dialogProps = $state({
+ type: "info" as const,
+ title: "",
+ message: "",
+ okText: "OK",
+ cancelText: "Cancel",
+ showCancel: false,
+ });
+
+ let modalOpen = $state(false);
+ let modalProps = $state({
+ type: "info" as "info" | "success" | "error",
+ title: "",
+ message: "",
+ });
// Calculate stack stats
const totalStacks = $derived(stacks?.length || 0);
@@ -37,8 +58,15 @@
}
async function importStack() {
- // TODO: Implement import stack modal functionality
- alert("Implement import stack functionality");
+ dialogOpen = true;
+ dialogProps = {
+ type: "info",
+ title: "Import Stack",
+ message: "This feature is not yet implemented. Check back soon!",
+ okText: "Close",
+ cancelText: "Cancel",
+ showCancel: false,
+ };
}
async function refreshData() {
@@ -60,7 +88,15 @@
</p>
</div>
<div class="flex gap-2">
- <!-- put buttons here -->
+ <Button
+ variant="outline"
+ size="sm"
+ onclick={refreshData}
+ disabled={isRefreshing}
+ >
+ <RefreshCw class={isRefreshing ? "w-4 h-4 animate-spin" : "w-4 h-4"} />
+ Refresh
+ </Button>
</div>
</div>
@@ -158,4 +194,69 @@
{/if}
</Card.Content>
</Card.Root>
+
+ <form
+ method="POST"
+ action={`/stacks/${id}?/remove`}
+ use:enhance={() => {
+ isRemoving = true;
+ deleteDialogOpen = false;
+ deleteDialogOpen = false;
+
+ return async ({ result }) => {
+ if (result.type === "success" && result.data) {
+ const data = result.data as {
+ success: boolean;
+ stack?: { name: string };
+ error?: string;
+ };
+ if (data.success) {
+ modalProps = {
+ type: "success",
+ title: "Stack Imported",
+ message: `Stack '${data.stack?.name}' has been successfully imported.`,
+ };
+ } else {
+ modalProps = {
+ type: "error",
+ title: "Import Failed",
+ message: data.error || "Failed to import stack",
+ };
+ }
+ modalOpen = true;
+ }
+
+ await invalidateAll();
+ isRemoving = false;
+
+ if (result.type === "success") {
+ // Force navigation to the stacks page after successful deletion
+ window.location.href = "/stacks";
+ } else {
+ console.error("Error removing stack:", result);
+ await invalidateAll();
+ }
+ };
+ }}
+ >
+ <!-- Button remains the same -->
+ </form>
+
+ <UniversalModal
+ bind:open={dialogOpen}
+ type={dialogProps.type}
+ title={dialogProps.title}
+ message={dialogProps.message}
+ okText={dialogProps.okText}
+ cancelText={dialogProps.cancelText}
+ showCancel={dialogProps.showCancel}
+ />
+
+ <UniversalModal
+ bind:open={modalOpen}
+ type={modalProps.type}
+ title={modalProps.title}
+ message={modalProps.message}
+ okText="OK"
+ />
</div>
diff --git a/src/routes/stacks/ImportExternalStack.svelte b/src/routes/stacks/ImportExternalStack.svelte
new file mode 100644
index 000000000..c34cbc03b
--- /dev/null
+++ b/src/routes/stacks/ImportExternalStack.svelte
@@ -0,0 +1,41 @@
+<script lang="ts">
+ import { Button } from "$lib/components/ui/button/index.js";
+ import { enhance } from "$app/forms";
+ import { Import, Loader2 } from "@lucide/svelte";
+ import { invalidateAll } from "$app/navigation";
+
+ const { id, name, isExternal } = $props();
+ let stack = $derived({ id, name, isExternal });
+
+ let importing = $state(false);
+</script>
+
+{#if stack.isExternal}
+ <form
+ method="POST"
+ action="/stacks/import"
+ use:enhance={() => {
+ importing = true;
+ return async ({ result }) => {
+ await invalidateAll();
+ importing = false;
+ };
+ }}
+ >
+ <input type="hidden" name="stackId" value={stack.id} />
+ <Button
+ size="sm"
+ variant="outline"
+ title="Import to Arcane"
+ disabled={importing}
+ type="submit"
+ >
+ {#if importing}
+ <Loader2 class="h-4 w-4 mr-2 animate-spin" />
+ {:else}
+ <Import class="h-4 w-4 mr-2" />
+ {/if}
+ Import
+ </Button>
+ </form>
+{/if}
diff --git a/src/routes/stacks/StackActions.svelte b/src/routes/stacks/StackActions.svelte
index 05b8bde12..4d520fa41 100644
--- a/src/routes/stacks/StackActions.svelte
+++ b/src/routes/stacks/StackActions.svelte
@@ -1,65 +1,241 @@
<script lang="ts">
import { enhance } from "$app/forms";
+ import { invalidateAll, goto } from "$app/navigation";
+ import { page } from "$app/stores";
import { Button } from "$lib/components/ui/button/index.js";
+ import * as Dialog from "$lib/components/ui/dialog/index.js";
import {
Play,
CircleStop,
Trash2,
Settings,
RefreshCw,
+ Loader2,
+ AlertTriangle,
+ Import,
} from "@lucide/svelte";
interface Props {
id: string;
status: string;
+ name?: string;
+ isExternal?: boolean;
}
- let { id, status }: Props = $props();
+ let { id, status, name = id, isExternal = false }: Props = $props();
const isRunning = status === "running" || status === "partially running";
+
+ // Loading states
+ let isStarting = $state(false);
+ let isStopping = $state(false);
+ let isRestarting = $state(false);
+ let isRemoving = $state(false);
+ let isImporting = $state(false);
+
+ // Delete dialog state
+ let deleteDialogOpen = $state(false);
+
+ // Check if we're on the stack detail page or the stacks list page
+ let isStackDetailPage = $derived($page.route.id === "/stacks/[stackId]");
+
+ // Handle form submission with proper redirection
+ const handleDeleteSubmit = () => {
+ isRemoving = true;
+ deleteDialogOpen = false;
+
+ return async ({
+ result,
+ }: {
+ result: { type: string; data?: { redirectTo?: string } };
+ }) => {
+ if (result.type === "success") {
+ if (isStackDetailPage && result.data?.redirectTo) {
+ // Only redirect if we're on the stack detail page
+ goto(result.data.redirectTo);
+ } else {
+ // Otherwise just refresh the data
+ await invalidateAll();
+ }
+ } else {
+ // Handle errors
+ console.error("Error removing stack:", result);
+ // Show error message
+ }
+ isRemoving = false;
+ };
+ };
+
+ // Handle import functionality
+ const handleImport = () => {
+ isImporting = true;
+ return async ({}) => {
+ await invalidateAll();
+ isImporting = false;
+ };
+ };
</script>
<div class="flex items-center gap-2 justify-end">
- {#if isRunning}
- <form method="POST" action="/stacks/{id}?/stop" use:enhance>
- <Button type="submit" size="icon" variant="outline" title="Stop Stack">
- <CircleStop class="h-4 w-4" />
+ {#if isExternal}
+ <!-- Show import button for external stacks -->
+ <form method="POST" action="/api/stacks/import" use:enhance={handleImport}>
+ <input type="hidden" name="stackId" value={id} />
+ <input type="hidden" name="stackName" value={name} />
+
+ <Button
+ type="submit"
+ size="sm"
+ variant="outline"
+ title="Import Stack to Arcane"
+ disabled={isImporting}
+ class="flex items-center"
+ >
+ {#if isImporting}
+ <Loader2 class="h-4 w-4 mr-2 animate-spin" />
+ {:else}
+ <Import class="h-4 w-4 mr-2" />
+ {/if}
+ Import
</Button>
</form>
{:else}
- <form method="POST" action="/stacks/{id}?/start" use:enhance>
- <Button type="submit" size="icon" variant="outline" title="Start Stack">
- <Play class="h-4 w-4" />
- </Button>
- </form>
- {/if}
+ <!-- Show regular action buttons for managed stacks -->
+ {#if isRunning}
+ <form
+ method="POST"
+ action="/stacks/{id}?/stop"
+ use:enhance={() => {
+ isStopping = true;
+ return async ({ result }) => {
+ await invalidateAll();
+ isStopping = false;
+ };
+ }}
+ >
+ <Button
+ type="submit"
+ size="icon"
+ variant="outline"
+ title="Stop Stack"
+ disabled={isStopping}
+ >
+ {#if isStopping}
+ <Loader2 class="h-4 w-4 animate-spin" />
+ {:else}
+ <CircleStop class="h-4 w-4" />
+ {/if}
+ </Button>
+ </form>
+ {:else}
+ <form
+ method="POST"
+ action="/stacks/{id}?/start"
+ use:enhance={() => {
+ isStarting = true;
+ return async ({ result }) => {
+ await invalidateAll();
+ isStarting = false;
+ };
+ }}
+ >
+ <Button
+ type="submit"
+ size="icon"
+ variant="outline"
+ title="Start Stack"
+ disabled={isStarting}
+ >
+ {#if isStarting}
+ <Loader2 class="h-4 w-4 animate-spin" />
+ {:else}
+ <Play class="h-4 w-4" />
+ {/if}
+ </Button>
+ </form>
+ {/if}
- <form method="POST" action="/stacks/{id}?/restart" use:enhance>
- <Button
- type="submit"
- size="icon"
- variant="outline"
- disabled={!isRunning}
- title="Restart Stack"
+ <form
+ method="POST"
+ action="/stacks/{id}?/restart"
+ use:enhance={() => {
+ isRestarting = true;
+ return async ({ result }) => {
+ await invalidateAll();
+ isRestarting = false;
+ };
+ }}
>
- <RefreshCw class="h-4 w-4" />
- </Button>
- </form>
+ <Button
+ type="submit"
+ size="icon"
+ variant="outline"
+ disabled={!isRunning || isRestarting}
+ title="Restart Stack"
+ >
+ {#if isRestarting}
+ <Loader2 class="h-4 w-4 animate-spin" />
+ {:else}
+ <RefreshCw class="h-4 w-4" />
+ {/if}
+ </Button>
+ </form>
- <a href="/stacks/{id}">
- <Button size="icon" variant="outline" title="Edit Stack">
- <Settings class="h-4 w-4" />
- </Button>
- </a>
+ <a href="/stacks/{id}">
+ <Button size="icon" variant="outline" title="Edit Stack">
+ <Settings class="h-4 w-4" />
+ </Button>
+ </a>
- <form method="POST" action="/stacks/{id}?/remove" use:enhance>
<Button
- type="submit"
+ type="button"
size="icon"
variant="destructive"
title="Remove Stack"
+ onclick={() => (deleteDialogOpen = true)}
>
<Trash2 class="h-4 w-4" />
</Button>
- </form>
+ {/if}
+
+ <!-- Delete confirmation dialog -->
+ {#if !isExternal}
+ <Dialog.Root bind:open={deleteDialogOpen}>
+ <Dialog.Content class="sm:max-w-[425px]">
+ <Dialog.Header>
+ <div class="flex items-center gap-2 text-destructive">
+ <AlertTriangle class="h-5 w-5" />
+ <Dialog.Title>Delete Stack</Dialog.Title>
+ </div>
+ <Dialog.Description>
+ Are you sure you want to remove stack "{name}"? This action cannot
+ be undone.
+ </Dialog.Description>
+ </Dialog.Header>
+
+ <Dialog.Footer>
+ <Button
+ type="button"
+ variant="outline"
+ onclick={() => (deleteDialogOpen = false)}
+ >
+ Cancel
+ </Button>
+
+ <form
+ method="POST"
+ action="/stacks/{id}?/remove"
+ use:enhance={handleDeleteSubmit}
+ >
+ <Button type="submit" variant="destructive" disabled={isRemoving}>
+ {#if isRemoving}
+ <Loader2 class="h-4 w-4 mr-2 animate-spin" />
+ {/if}
+ Delete
+ </Button>
+ </form>
+ </Dialog.Footer>
+ </Dialog.Content>
+ </Dialog.Root>
+ {/if}
</div>
diff --git a/src/routes/stacks/[stackId]/+page.server.ts b/src/routes/stacks/[stackId]/+page.server.ts
index 2652396a8..7a52eadab 100644
--- a/src/routes/stacks/[stackId]/+page.server.ts
+++ b/src/routes/stacks/[stackId]/+page.server.ts
@@ -46,14 +46,9 @@ export const actions = {
},
start: async ({ params }) => {
- const { stackId } = params;
-
try {
- await startStack(stackId);
- return {
- success: true,
- message: "Stack started successfully",
- };
+ await startStack(params.stackId);
+ return { success: true };
} catch (err) {
console.error("Error starting stack:", err);
return {
@@ -64,14 +59,9 @@ export const actions = {
},
stop: async ({ params }) => {
- const { stackId } = params;
-
try {
- await stopStack(stackId);
- return {
- success: true,
- message: "Stack stopped successfully",
- };
+ await stopStack(params.stackId);
+ return { success: true };
} catch (err) {
console.error("Error stopping stack:", err);
return {
@@ -82,14 +72,9 @@ export const actions = {
},
restart: async ({ params }) => {
- const { stackId } = params;
-
try {
- await restartStack(stackId);
- return {
- success: true,
- message: "Stack restarted successfully",
- };
+ await restartStack(params.stackId);
+ return { success: true };
} catch (err) {
console.error("Error restarting stack:", err);
return {
@@ -100,14 +85,13 @@ export const actions = {
},
remove: async ({ params }) => {
- const { stackId } = params;
-
try {
- await removeStack(stackId);
- throw redirect(303, "/stacks");
+ const success = await removeStack(params.stackId);
+ if (success) {
+ return { success: true, redirectTo: "/stacks" };
+ }
+ return { success: false, error: "Failed to remove stack" };
} catch (err) {
- if (err instanceof Response) throw err; // Rethrow the redirect
-
console.error("Error removing stack:", err);
return {
success: false,
diff --git a/src/routes/stacks/[stackId]/+page.svelte b/src/routes/stacks/[stackId]/+page.svelte
index d706445f1..d72f2e835 100644
--- a/src/routes/stacks/[stackId]/+page.svelte
+++ b/src/routes/stacks/[stackId]/+page.svelte
@@ -6,11 +6,6 @@
ArrowLeft,
Loader2,
AlertCircle,
- RefreshCw,
- PlayCircle,
- StopCircle,
- RotateCw,
- Trash2,
Save,
FileStack,
Layers,
@@ -22,19 +17,20 @@
import { Badge } from "$lib/components/ui/badge/index.js";
import { Input } from "$lib/components/ui/input/index.js";
import { Label } from "$lib/components/ui/label/index.js";
- import StatusBadge from "$lib/components/docker/StatusBadge.svelte";
import YamlEditor from "$lib/components/yaml-editor.svelte";
import { onMount } from "svelte";
+ import ActionButtons from "$lib/components/action-buttons.svelte";
+ import CustomBadge from "$lib/components/badges/custom-badge.svelte";
+ import { capitalizeFirstLetter, getStatusColor } from "$lib/utils";
let { data, form }: { data: PageData; form: ActionData } = $props();
let { stack } = $derived(data);
- let starting = $state(false);
+ let depoloying = $state(false);
let stopping = $state(false);
let restarting = $state(false);
let removing = $state(false);
let saving = $state(false);
- let isRefreshing = $state(false);
let name = $state("");
let composeContent = $state("");
@@ -53,7 +49,7 @@
});
$effect(() => {
- starting = false;
+ depoloying = false;
stopping = false;
restarting = false;
removing = false;
@@ -107,115 +103,42 @@
{#if stack}
<div class="flex gap-2 flex-wrap">
- {#if stack.status === "running" || stack.status === "partially running"}
- <form
- method="POST"
- action="?/stop"
- use:enhance={() => {
- stopping = true;
- return async ({ update }) => {
- await update({ reset: false });
- };
- }}
- >
- <Button
- type="submit"
- variant="secondary"
- disabled={stopping}
- size="sm"
- class="font-medium h-9"
- >
- {#if stopping}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
- {:else}
- <StopCircle class="w-4 h-4 mr-2" />
- {/if}
- Stop
- </Button>
- </form>
- <form
- method="POST"
- action="?/restart"
- use:enhance={() => {
- restarting = true;
- return async ({ update }) => {
- await update({ reset: false });
- };
- }}
- >
- <Button
- type="submit"
- variant="outline"
- disabled={restarting}
- size="sm"
- class="font-medium h-9"
- >
- {#if restarting}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
- {:else}
- <RotateCw class="w-4 h-4 mr-2" />
- {/if}
- Restart
- </Button>
- </form>
- {:else}
- <form
- method="POST"
- action="?/start"
- use:enhance={() => {
- starting = true;
- return async ({ update }) => {
- await update({ reset: false });
- };
- }}
- >
- <Button
- type="submit"
- variant="default"
- disabled={starting}
- size="sm"
- class="font-medium h-9"
- >
- {#if starting}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
- {:else}
- <PlayCircle class="w-4 h-4 mr-2" />
- {/if}
- Start
- </Button>
- </form>
- {/if}
<form
method="POST"
- action="?/remove"
+ action={stack.status === "running" ||
+ stack.status === "partially running"
+ ? "?/stop"
+ : "?/start"}
use:enhance={() => {
- if (
- !confirm(
- `Are you sure you want to remove stack "${stack?.name}"?`
- )
- ) {
- return;
- }
- removing = true;
+ const isStarting =
+ stack.status !== "running" &&
+ stack.status !== "partially running";
+ if (isStarting) depoloying = true;
+ else stopping = true;
return async ({ update }) => {
await update({ reset: false });
};
}}
>
- <Button
- type="submit"
- variant="destructive"
- disabled={removing}
- size="sm"
- class="font-medium h-9"
- >
- {#if removing}
- <Loader2 class="w-4 h-4 mr-2 animate-spin" />
- {:else}
- <Trash2 class="w-4 h-4 mr-2" />
- {/if}
- Remove
- </Button>
+ <input
+ type="hidden"
+ name="action"
+ value={stack.status === "running" ||
+ stack.status === "partially running"
+ ? "stop"
+ : "start"}
+ />
+ <ActionButtons
+ id={stack.id}
+ type="stack"
+ state={stack.status}
+ loading={{
+ start: depoloying,
+ stop: stopping,
+ restart: restarting,
+ remove: removing,
+ }}
+ />
</form>
</div>
{/if}
@@ -381,7 +304,17 @@
</div>
</div>
<div class="flex items-center gap-2">
- <StatusBadge state={service.state?.Status || "unknown"} />
+ <CustomBadge
+ variant="status"
+ text={capitalizeFirstLetter(
+ service.state?.Status || "unknown"
+ )}
+ bgColor={getStatusColor(service.state?.Status || "unknown")
+ .bg}
+ textColor={getStatusColor(
+ service.state?.Status || "unknown"
+ ).text}
+ />
{#if service.id}
<div class="text-xs text-blue-500 ml-2">
<span class="hidden sm:inline">View details</span>
diff --git a/src/routes/stacks/columns.ts b/src/routes/stacks/columns.ts
index a1ce92ff8..fd91c79e6 100644
--- a/src/routes/stacks/columns.ts
+++ b/src/routes/stacks/columns.ts
@@ -2,9 +2,11 @@ import type { Stack } from "$lib/types/stack";
import type { ColumnDef } from "@tanstack/table-core";
import { renderComponent } from "$lib/components/ui/data-table/index.js";
import StackActions from "./StackActions.svelte";
-import StatusBadge from "$lib/components/docker/StatusBadge.svelte";
import StackNameCell from "./StackNameCell.svelte";
import StackDateCell from "./StackDateCell.svelte";
+import CustomBadge from "$lib/components/badges/custom-badge.svelte";
+import { capitalizeFirstLetter } from "$lib/utils";
+import { statusConfig } from "$lib/types/statuses";
export const columns: ColumnDef<Stack>[] = [
{
@@ -25,7 +27,19 @@ export const columns: ColumnDef<Stack>[] = [
accessorKey: "status",
header: "Status",
cell: ({ row }) => {
- return renderComponent(StatusBadge, { state: row.original.status });
+ const status = row.getValue("status");
+
+ const config = statusConfig[status as keyof typeof statusConfig] || {
+ bgColor: "blue-100",
+ textColor: "blue-900",
+ };
+
+ return renderComponent(CustomBadge, {
+ variant: "status",
+ rounded: true,
+ text: capitalizeFirstLetter(status as string),
+ ...config,
+ });
},
},
{
@@ -37,6 +51,20 @@ export const columns: ColumnDef<Stack>[] = [
});
},
},
+ {
+ header: "Source",
+ accessorKey: "isExternal",
+ cell: ({ row }) => {
+ const isExternal = row.getValue("isExternal");
+ return renderComponent(CustomBadge, {
+ variant: "outline",
+ rounded: true,
+ bgColor: isExternal ? "amber-100" : "indigo-100",
+ textColor: isExternal ? "amber-900" : "indigo-900",
+ text: isExternal ? "External" : "Managed",
+ });
+ },
+ },
{
id: "actions",
header: "",
@@ -44,6 +72,8 @@ export const columns: ColumnDef<Stack>[] = [
return renderComponent(StackActions, {
id: row.original.id,
status: row.original.status,
+ name: row.original.name,
+ isExternal: row.original.isExternal,
});
},
enableSorting: false,
diff --git a/src/routes/stacks/new/+page.server.ts b/src/routes/stacks/new/+page.server.ts
index 4953ab814..f4fac4076 100644
--- a/src/routes/stacks/new/+page.server.ts
+++ b/src/routes/stacks/new/+page.server.ts
@@ -25,9 +25,25 @@ export const actions = {
try {
const stack = await createStack(name, composeContent);
- throw redirect(303, `/stacks/${stack.id}`);
+ if (stack && stack.id) {
+ throw redirect(303, `/stacks/${stack.id}`);
+ }
+
+ return {
+ success: true,
+ stack: stack,
+ };
} catch (err) {
- if (err instanceof Response) throw err; // Rethrow the redirect
+ // 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 {
diff --git a/src/routes/stacks/new/+page.svelte b/src/routes/stacks/new/+page.svelte
index c57e946d1..d479a8b75 100644
--- a/src/routes/stacks/new/+page.svelte
+++ b/src/routes/stacks/new/+page.svelte
@@ -15,9 +15,6 @@
import { Input } from "$lib/components/ui/input/index.js";
import { Label } from "$lib/components/ui/label/index.js";
- // Import CodeMirror components
- import CodeMirror from "svelte-codemirror-editor";
- import { yaml } from "@codemirror/lang-yaml";
import { oneDark } from "@codemirror/theme-one-dark";
import { browser } from "$app/environment";
diff --git a/src/routes/volumes/+page.svelte b/src/routes/volumes/+page.svelte
index bbc50340c..851e03230 100644
--- a/src/routes/volumes/+page.svelte
+++ b/src/routes/volumes/+page.svelte
@@ -2,16 +2,7 @@
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,
- RefreshCw,
- Filter,
- ArrowUpDown,
- Database,
- Loader2,
- } from "@lucide/svelte";
+ import { Plus, AlertCircle, HardDrive, Database } from "@lucide/svelte";
import UniversalTable from "$lib/components/universal-table.svelte";
import { columns } from "./columns";
import type { PageData } from "./$types";