Skip to content

Modern Docker Management, Designed for Everyone

refactor: api, tables, and ui cleanup and refactor code, add e2e tests (#96)

Kyle Mendelleec7fd245402
diff --git a/.github/svelte-check-matcher.json b/.github/svelte-check-matcher.json
index 9a5fe5728..c7e0e5e39 100644
--- a/.github/svelte-check-matcher.json
+++ b/.github/svelte-check-matcher.json
@@ -1,21 +1,21 @@
{
- "problemMatcher": [
- {
- "owner": "svelte-check",
- "pattern": [
- {
- "regexp": "^([^\\s].*):(\\d+):(\\d+)$",
- "file": 1,
- "line": 2,
- "column": 3
- },
- {
- "regexp": "^\\s*(Error|Warning):\\s*(.*)\\s+\\((?:ts|js|svelte)\\)$",
- "severity": 1, // "Error" or "Warning"
- "message": 2, // The actual error message text
- "loop": false // This message belongs to the file/line matched above
- }
- ]
- }
- ]
+ "problemMatcher": [
+ {
+ "owner": "svelte-check",
+ "pattern": [
+ {
+ "regexp": "^([^\\s].*):(\\d+):(\\d+)$",
+ "file": 1,
+ "line": 2,
+ "column": 3
+ },
+ {
+ "regexp": "^\\s*(Error|Warning):\\s*(.*)\\s+\\((?:ts|js|svelte)\\)$",
+ "severity": 1,
+ "message": 2,
+ "loop": false
+ }
+ ]
+ }
+ ]
}
diff --git a/.gitignore b/.gitignore
index 73137b64c..31a24e936 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,4 +25,8 @@ vite.config.ts.timestamp-*
.arcane/*
.arcane/stacks/*
.dev-data/*
-.dev-data/settings/*
\ No newline at end of file
+.dev-data/settings/*
+
+test-results/*
+tests/.report/*
+.test-data/*
\ No newline at end of file
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 000000000..9ce92eb05
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,8 @@
+{
+ "github.copilot.enable": {
+ "*": false,
+ "plaintext": false,
+ "markdown": false,
+ "scminput": false
+ }
+}
diff --git a/Dockerfile b/Dockerfile
index 7110e8579..19a521117 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -17,22 +17,16 @@ RUN NODE_ENV=build npm run build
# Stage 3: Production image
FROM node:22-alpine AS runner
-# Delete default node user first (combine with package installation to reduce layers)
-RUN deluser --remove-home node && \
- apk add --no-cache su-exec curl shadow
+# Delete default node user first (combine with system upgrade package installation to reduce layers)
+RUN deluser --remove-home node && apk upgrade -a && apk add --no-cache su-exec curl shadow
WORKDIR /app
# Set up environment variables early for better caching
-ENV DOCKER_GID=998 \
- PUID=1000 \
- PGID=1000
+ENV DOCKER_GID=998 PUID=1000 PGID=1000
# Create necessary groups and users
-RUN addgroup -g ${PGID} arcane && \
- adduser -D -u ${PUID} -G arcane arcane && \
- addgroup -g ${DOCKER_GID} docker && \
- adduser arcane docker
+RUN addgroup -g ${PGID} arcane && adduser -D -u ${PUID} -G arcane arcane && addgroup -g ${DOCKER_GID} docker && adduser arcane docker
# Set up directories and permissions
RUN mkdir -p /app/data && chmod 755 /app/data
@@ -40,16 +34,13 @@ RUN mkdir -p /app/data && chmod 755 /app/data
# Copy only necessary files from builder
COPY --from=builder /app/build ./build
COPY --from=builder /app/static ./static
-# COPY --chown=arcane:arcane app-settings.json /app/data/app-settings.json.default
# Copy entrypoint script
COPY --chmod=755 scripts/docker/entrypoint.sh /usr/local/bin/entrypoint.sh
# Install only production dependencies
COPY package*.json ./
-RUN npm install --omit=dev && \
- npm cache clean --force && \
- chown -R arcane:arcane /app
+RUN npm install --omit=dev && npm cache clean --force && chown -R arcane:arcane /app
# Configure container
EXPOSE 3000
diff --git a/README.md b/README.md
index a86b3ce40..d6511e964 100644
--- a/README.md
+++ b/README.md
@@ -7,23 +7,29 @@
> [!IMPORTANT]
> **⚠️** Arcane is currently pre-release software. Features may change, and bugs are expected. Please report any issues with the `Bug` template on Github.
-Arcane is a web-based user interface built with SvelteKit designed to simplify interaction with your Docker environment. It provides a clean overview and management capabilities for your containers, images, volumes, and networks.
+Arcane is a modern, web-based interface for managing your Docker environment, built with SvelteKit. It offers a clean, intuitive overview and powerful management tools for your containers, images, volumes, and networks—all in one place.
-## Features
+---
-- **Containers:** List, inspect, start, stop, restart, and remove containers. View container logs. Create containers (basic implementation).
-- **Images:** List, pull, and remove images. Prune unused images.
-- **Volumes:** List, create, and remove volumes.
-- **Networks:** List, inspect, create, and remove networks.
-- **Stacks:** Manage Docker Compose stacks.
-- **Settings:** Configure Docker connection details (Host/Socket Path) and application preferences like polling interval.
+## Why Arcane?
+
+I created Arcane because I couldn’t find a Docker UI that was both simple and feature-rich enough for my needs. Every feature in Arcane is something I personally found missing or cumbersome in other tools. As the project grew, it became clear that others might benefit from it too.
+If you have suggestions, feedback, or feature requests, please open an issue or submit a pull request!
+
+---
## Documentation
-For detailed instructions on getting started, configuration, development, and more, please visit the **[official documentation site](https://docs.example.com/arcane)** (Link placeholder).
+For setup instructions, configuration details, and development guides, visit the **[official documentation site](https://arcane.ofkm.dev)**.
+
+---
## Important Notes
- **Security:** Mounting the Docker socket (`/var/run/docker.sock`) into any container grants it root-level access to your Docker host. Understand the security implications before running Arcane or any container with socket access.
-- **Pre-release:** This software is under active development. Expect breaking changes and bugs.
+- **Pre-release:** Arcane is under active development. Expect breaking changes and bugs.
- **Data:** Stack definitions and application settings are stored in the mapped data volume (`/app/data` inside the container). Back up this directory if needed.
+
+---
+
+Thank you for checking out Arcane! Your feedback and contributions are always welcome.
diff --git a/docs/docs/features/containers/inspecting-logs.md b/docs/docs/features/containers/inspecting-logs.md
deleted file mode 100644
index c16e5d8a1..000000000
--- a/docs/docs/features/containers/inspecting-logs.md
+++ /dev/null
@@ -1,44 +0,0 @@
----
-sidebar_position: 3
-title: Inspecting Containers & Logs
----
-
-# Inspecting Containers & Logs
-
-This guide covers how to view detailed information about a container (inspect) and access its logs using the Arcane UI.
-
-## Inspecting Container Details
-
-To view the full configuration and current state of a container:
-
-1. Navigate to the "Containers" list view.
-2. Click on the **Name** of the container you want to inspect.
-3. This will take you to the container's details page.
-4. This page presents comprehensive information retrieved using the equivalent of the `docker inspect` command (`#attachment_container_service_ts`). Key details often include:
- - **General Info:** ID, Name, Image, Status, Creation Date, Entrypoint, Command.
- - **State:** Detailed state information, including Running status, PID, Exit Code, Started/Finished times.
- - **Network Settings:** IP Address, MAC Address, Connected Networks, Port Mappings.
- - **Mounts:** Details about volumes and bind mounts, including source and destination paths.
- - **Environment Variables:** A list of all environment variables set within the container.
- - **Labels:** All labels applied to the container.
- - **Restart Policy:** The configured restart policy.
- - **Resource Limits:** Configured memory or CPU limits.
- - **Host Config:** Detailed host configuration options used when the container was created.
-
-This detailed view is invaluable for troubleshooting configuration issues or understanding exactly how a container is set up.
-
-## Viewing Container Logs
-
-Arcane allows you to view the standard output (`stdout`) and standard error (`stderr`) streams generated by your containers.
-
-1. Navigate to the container's details page (by clicking its name in the list).
-2. Look for a "Logs" tab or section on the details page.
-3. Clicking this tab will display the container's logs (`#attachment_container_service_ts`).
-4. Arcane typically provides options to control the log view:
- - **Tailing:** Enable/disable automatic scrolling to show new logs as they arrive (live view).
- - **Timestamps:** Show/hide timestamps for each log entry.
- - **Line Count:** Specify the number of recent log lines to retrieve initially (e.g., last 100 lines, all lines).
- - **Since/Until:** Potentially filter logs based on a time range (if supported).
- - **Refresh:** Manually fetch the latest logs if tailing is disabled.
-
-Container logs are essential for debugging application errors, monitoring activity, and understanding what a container is doing.
diff --git a/docs/docs/features/containers/managing-containers.md b/docs/docs/features/containers/managing-containers.md
deleted file mode 100644
index a100857b7..000000000
--- a/docs/docs/features/containers/managing-containers.md
+++ /dev/null
@@ -1,56 +0,0 @@
----
-sidebar_position: 2
-title: Managing Containers
----
-
-# Managing Containers
-
-This guide explains how to use the Arcane UI to list, create, control the state of, and remove individual Docker containers.
-
-## Viewing Containers
-
-Navigate to the "Containers" section in the Arcane sidebar. This page displays a table (`#attachment_page_svelte`) listing all containers on your connected Docker host.
-
-Key information displayed typically includes:
-
-- **Name:** The container's name.
-- **State:** The current status (e.g., `running`, `exited`).
-- **Image:** The image the container is based on.
-- **IP Address:** The container's IP address within its Docker network.
-- **Ports:** Mappings between host and container ports.
-- **Actions:** Buttons for common operations like Start, Stop, Restart, and Remove (`#attachment_ContainerActions_svelte`).
-
-You can usually filter or sort this list based on different criteria.
-
-## Creating a New Container
-
-1. Click the "Create Container" or "+" button, typically located near the top of the container list.
-2. A detailed dialog (`#attachment_create_container_dialog_svelte`) will appear, allowing you to configure the new container. Key sections include:
- - **General:** Name, Image (you can search/select available images).
- - **Ports:** Define port mappings (Host Port : Container Port).
- - **Volumes:** Map host directories or named volumes to paths inside the container.
- - **Environment:** Add environment variables (KEY=VALUE).
- - **Network:** Choose the Docker network, set hostname, and potentially assign a static IP address within user-defined networks.
- - **Restart Policy:** Define when the container should automatically restart (e.g., `unless-stopped`, `on-failure`).
- - **Labels:** Add custom metadata labels.
- - **Advanced:** May include options for command overrides, user specification, healthchecks, and resource limits (CPU/Memory).
-3. Fill in the desired configuration options.
-4. Click "Create" or "Deploy". Arcane will use the provided configuration (`ContainerConfig`) to create and start the new container via the Docker API (`#attachment_container_service_ts`).
-
-## Controlling Container State
-
-You can control the state of containers directly from the list view or potentially from the container's details page using the action buttons (`#attachment_ContainerActions_svelte`):
-
-- **Start:** Select a stopped container and click the "Start" button. Arcane will execute the start command (`#attachment_container_service_ts`).
-- **Stop:** Select a running container and click the "Stop" button. Arcane will send a stop signal to the container (`#attachment_container_service_ts`).
-- **Restart:** Select a running container and click the "Restart" button. Arcane will stop and then immediately start the container again (`#attachment_container_service_ts`).
-
-## Removing Containers
-
-1. **Ensure the container is stopped.** You generally cannot remove a running container unless using a "force" option.
-2. Select the stopped container(s) you wish to remove.
-3. Click the "Remove" or trash can icon (`#attachment_ContainerActions_svelte`).
-4. **Confirmation:** You will likely be asked to confirm the removal.
-5. **Force Option:** If available, the "Force" option allows removing a running container. This is equivalent to `docker rm -f` and should be used cautiously as it doesn't allow the container to shut down gracefully.
-
-Removing a container deletes its writable layer; associated volumes are typically _not_ removed automatically unless specifically configured (e.g., anonymous volumes with `docker run --rm`).
diff --git a/docs/docs/features/containers/overview.md b/docs/docs/features/containers/overview.md
index 8c886d7ad..a1cfc3195 100644
--- a/docs/docs/features/containers/overview.md
+++ b/docs/docs/features/containers/overview.md
@@ -5,55 +5,48 @@ title: Containers Overview
# Containers Overview
-The "Containers" section is the core of Arcane, providing a comprehensive interface for managing individual Docker containers running on your connected Docker host.
-
-## Key Concepts
-
-- **Container:** A runnable instance of a Docker image. It packages application code with all its dependencies.
-- **Container ID:** A unique identifier (long or short hash) for a specific container instance.
-- **Container Name:** A user-friendly name assigned to a container (either automatically generated by Docker or specified during creation).
-- **Image:** The blueprint from which a container is created (e.g., `nginx:latest`).
-- **State:** The current status of a container (e.g., `running`, `exited`, `paused`, `restarting`).
-- **Ports:** Mappings between ports on the host machine and ports inside the container.
-- **Volumes:** Mechanisms for persisting data generated by and used by containers, often mapping a host directory or a named volume to a directory inside the container.
-- **Environment Variables:** Key-value pairs passed into the container to configure its behavior.
-- **Network:** How the container connects to other containers or the host machine.
-
-## Core Functionality
-
-Based on the `container-service.ts` and related UI components, Arcane allows you to perform the following actions on Docker containers:
-
-- **List Containers:** View all containers on the Docker host (both running and stopped). The list typically displays the container's Name, ID, Image, and Status (`#attachment_columns_ts`, `#attachment_page_svelte`).
-- **Create Containers:** Launch new containers from existing images using a detailed configuration dialog (`#attachment_create_container_dialog_svelte`). This includes setting:
- - Name and Image
- - Port Mappings
- - Volume Mounts
- - Environment Variables
- - Network Settings (including static IPs for user-defined networks)
- - Restart Policies
- - Healthchecks
- - Labels
- - Command Overrides
- - User specification
- - Resource Limits (Memory, CPU)
-- **Inspect Containers:** View detailed information about a specific container, including its configuration, network settings, mounts, state, logs, and more (`#attachment_container_service_ts`).
-- **Control Container State:**
- - **Start:** Start a stopped container (`#attachment_ContainerActions_svelte`, `#attachment_container_service_ts`).
- - **Stop:** Stop a running container (`#attachment_ContainerActions_svelte`, `#attachment_container_service_ts`).
- - **Restart:** Restart a running container (`#attachment_ContainerActions_svelte`, `#attachment_container_service_ts`).
-- **Remove Containers:** Delete stopped containers. A "force" option might be available to remove running containers (use with caution) (`#attachment_ContainerActions_svelte`, `#attachment_container_service_ts`).
-- **View Logs:** Fetch and display logs generated by a container, with options for tailing, timestamps, and specifying the number of lines (`#attachment_container_service_ts`).
-- **View Statistics:** The UI displays summary statistics like total, running, and stopped container counts (`#attachment_page_svelte`).
-
-## Container Data
-
-Arcane represents container information using structures defined in `container.type.ts`, including:
-
-- `ServiceContainer`: For list views, containing essential details like ID, name, image, state, status, and ports.
-- `ContainerConfig`: For creation, defining all the configurable options.
-- Detailed inspection data mirroring the output of `docker inspect`.
-
-## Next Steps
-
-- Learn how to perform specific actions in [Managing Containers](./managing-containers) (You'll need to create this file).
-- Understand how to view container details and logs in [Inspecting Containers & Logs](./inspecting-logs) (You'll need to create this file).
+## What Can You Do With Containers in Arcane?
+
+- **View Containers:** See all containers on your Docker host, including their names, IDs, images, and current status (like running or stopped).
+- **Create Containers:** Launch new containers from existing images. You can set the name, image, ports, volumes, environment variables, and more using a guided form.
+- **Start/Stop/Restart Containers:** Easily control the state of your containers with one click.
+- **Inspect Containers:** Click on a container to see detailed information, including configuration, network settings, mounts, and logs.
+- **Remove Containers:** Delete containers you no longer need. You can only remove stopped containers (unless you use the force option).
+- **View Logs:** Check the output and error logs for each container to help with troubleshooting.
+
+## How to Use
+
+### Viewing Containers
+
+1. Go to the **Containers** section in the sidebar.
+2. You’ll see a table listing all your Docker containers with their names, IDs, images, and status.
+
+### Creating a Container
+
+1. Click the **Create Container** button.
+2. Fill out the form with the required details (name, image, etc.).
+3. (Optional) Set advanced options like ports, volumes, environment variables, and more.
+4. Click **Create** to launch your new container.
+
+### Controlling a Container
+
+- **Start:** Click the **Start** button to run a stopped container.
+- **Stop:** Click the **Stop** button to stop a running container.
+- **Restart:** Click the **Restart** button to quickly restart a container.
+
+### Inspecting a Container
+
+1. Click on a container’s name or the **Inspect** button.
+2. View detailed information about the container’s configuration, state, network, mounts, and logs.
+
+### Removing a Container
+
+1. In the containers list, find the container you want to remove.
+2. Click the **Remove** button (trash icon).
+3. Confirm the deletion in the dialog.
+ > **Note:** You can only remove stopped containers unless you use the force option.
+
+### Viewing Logs
+
+1. Click on a container to open its details.
+2. Go to the **Logs** tab to see the container’s output and error logs.
diff --git a/docs/docs/features/images/managing-images.md b/docs/docs/features/images/managing-images.md
deleted file mode 100644
index 177be30d4..000000000
--- a/docs/docs/features/images/managing-images.md
+++ /dev/null
@@ -1,53 +0,0 @@
----
-sidebar_position: 2
-title: Managing Images
----
-
-# Managing Images
-
-This guide explains how to use the Arcane UI to list, pull, inspect, and remove Docker images on your connected Docker host.
-
-## Viewing Images
-
-Navigate to the "Images" section in the Arcane sidebar. This page displays a list of all images currently available locally on your Docker host.
-
-For each image, you'll typically see:
-
-- **Tags:** The repository name(s) and tag(s) associated with the image (e.g., `nginx:latest`, `ubuntu:22.04`). An image might have multiple tags. Untagged images might be shown as `<none>:<none>`.
-- **Image ID:** The unique short ID of the image.
-- **Size:** The amount of disk space the image occupies.
-- **Created:** The date and time the image was built or pulled.
-- **Actions:** Buttons or icons for performing actions like Inspect or Remove.
-
-## Pulling an Image
-
-1. Click the "Pull Image" button, often located near the top of the Images list page.
-2. A dialog box (`pull-image-dialog.svelte`) will appear.
-3. Enter the full name of the image you want to pull, including the tag. If you omit the tag, Docker typically defaults to `latest`.
- - Examples: `redis:latest`, `postgres:15-alpine`, `ghcr.io/ofkm/arcane:latest`
-4. Click "Pull". Arcane will initiate the image download process from the specified registry (Docker Hub by default, unless a different registry is part of the image name).
-5. You might see progress updates in the UI or notifications. Once complete, the new image will appear in the image list.
-
-## Inspecting an Image
-
-1. Find the image you want to inspect in the list.
-2. Click on its name, ID, or an "Inspect" icon/button associated with it.
-3. A details view or modal will open, displaying comprehensive information about the image, such as:
- - Full Image ID and Tags
- - Creation Date and Architecture
- - Environment Variables defined in the image
- - Exposed Ports
- - Entrypoint and Command
- - Labels
- - Layer history (potentially)
-
-## Removing Images
-
-1. **Single Image:**
- - Find the image you want to remove in the list.
- - Click the "Remove" or trash can icon associated with that specific image or tag.
-2. **Multiple Images (if supported):**
- - Select the checkboxes next to the images you wish to remove.
- - Click a main "Remove Selected" button.
-3. **Confirmation:** You will likely be asked to confirm the removal.
-4. **Force Option:** Arcane might offer a "Force remove" option. This is necessary if you want to remove an image that is currently used by a stopped container. **Use force removal with caution**, as it can affect containers based on that image. You generally cannot remove images used by _running_ containers.
diff --git a/docs/docs/features/images/overview.md b/docs/docs/features/images/overview.md
index 994a6281c..074fe8e4a 100644
--- a/docs/docs/features/images/overview.md
+++ b/docs/docs/features/images/overview.md
@@ -1,40 +1,45 @@
---
sidebar_position: 1
-title: Images Overview
+title: Image Management
---
-# Images Overview
+# Image Management
-The "Images" section in Arcane provides tools to manage the Docker images available on your connected Docker host. Docker images are the blueprints used to create containers.
+## What Can You Do With Images in Arcane?
-## Key Concepts
+- **View Images:** See a list of all Docker images on your system, including their tags, size, and when they were created.
+- **Pull Images:** Download new images from Docker Hub or another registry by entering the image name and tag (like `nginx:latest`).
+- **Inspect Images:** Click on an image to see more details, such as its ID, tags, creation date, and configuration.
+- **Remove Images:** Delete images you no longer need. Arcane will warn you if an image is in use by a container.
+- **Prune Images:** Clean up unused images to free up disk space. You can remove dangling images (those without tags) or all images not used by any container.
-- **Image:** A read-only template containing application code, libraries, dependencies, tools, and other files needed for an application to run.
-- **Tag:** A label applied to an image to distinguish different versions or variants (e.g., `latest`, `1.2.0`, `alpine`). An image can have multiple tags.
-- **Image ID:** A unique identifier (SHA256 hash) for an image's content.
-- **Registry:** A storage and distribution system for Docker images (e.g., Docker Hub, GitHub Container Registry, private registries).
-- **Dangling Image:** An image layer that is not associated with any tagged image. These often result from building new versions of an image without removing the old one.
+## How to Use
-## Core Functionality
+### Viewing Images
-Based on the `image-service.ts` and related components, Arcane allows you to perform the following actions on Docker images:
+1. Go to the **Images** section in the sidebar.
+2. You’ll see a table listing all your Docker images with their tags, size, and creation date.
-- **List Images:** View all images currently present on the Docker host, including their tags, size, creation date, and ID.
-- **Pull Images:** Download new images from a specified registry (like Docker Hub). You can specify the image name and tag (e.g., `nginx:latest`, `redis:7-alpine`). The UI includes a dedicated dialog (`pull-image-dialog.svelte`) for this purpose.
-- **Inspect Images:** View detailed information about a specific image, potentially including its layers, environment variables, exposed ports, and command history.
-- **Remove Images:** Delete one or more images from the Docker host to free up disk space. You can typically only remove images that are not currently being used by any containers (stopped or running). Arcane might offer options to force removal.
-- **Prune Images:** Remove unused images, specifically dangling images (those without tags) and potentially all images not associated with at least one container. This helps reclaim disk space efficiently.
+### Pulling a New Image
-## Image Data
+1. Click the **Pull Image** button.
+2. Enter the image name and tag (for example, `redis:latest`).
+3. Click **Pull**. The image will be downloaded and added to your list.
-Arcane represents image information using a structure defined in `image.type.ts`, likely including fields such as:
+### Inspecting an Image
-- `Id`: The unique image ID.
-- `RepoTags`: A list of repository names and tags associated with the image.
-- `Created`: Timestamp of when the image was created.
-- `Size`: The virtual size of the image.
-- `Labels`: Any metadata labels applied to the image.
+1. Find the image you want to inspect in the list.
+2. Click on its name, ID, or the **Inspect** button to see more details.
-## Next Steps
+### Removing an Image
-- Learn how to perform specific actions in [Managing Images](./managing-images).
+1. In the images list, find the image you want to remove.
+2. Click the **Remove** button (trash icon) next to it.
+3. Confirm the deletion in the dialog.
+ > **Note:** You cannot remove images that are currently used by running containers.
+
+### Pruning Images
+
+1. Click the **Prune Images** button.
+2. Choose whether to remove only dangling images or all unused images.
+3. Confirm the action to free up disk space.
diff --git a/docs/docs/features/networks/overview.md b/docs/docs/features/networks/overview.md
index e69de29bb..14870924a 100644
--- a/docs/docs/features/networks/overview.md
+++ b/docs/docs/features/networks/overview.md
@@ -0,0 +1,38 @@
+# Network Management
+
+## What Can You Do With Networks in Arcane?
+
+- **View Networks:** See a list of all Docker networks on your system, including their names, drivers, and subnets.
+- **Create Networks:** Add a new network by choosing a name, driver, and optional settings like subnet or gateway.
+- **Inspect Networks:** Click on a network to see details, including connected containers and configuration.
+- **Remove Networks:** Delete networks you no longer need. Arcane will warn you if a network is in use or is a default Docker network.
+
+## How to Use
+
+### Viewing Networks
+
+1. Go to the **Networks** section in the sidebar.
+2. You’ll see a table listing all your Docker networks.
+
+### Creating a Network
+
+1. Click the **Create Network** button.
+2. Enter a name for your network.
+3. (Optional) Choose a driver (like `bridge` or `overlay`) and set advanced options if needed.
+4. Click **Create**. Your new network will appear in the list.
+
+### Inspecting a Network
+
+1. Click on a network’s name in the list.
+2. You’ll see details like its ID, driver, subnet, gateway, and which containers are connected.
+
+### Removing a Network
+
+1. In the networks list, find the network you want to remove.
+2. Click the dropdown, then the **Delete** button (trash icon).
+3. Confirm the deletion in the dialog.
+ > **Note:** You cannot remove a network that is currently used by containers or is a default Docker network (like `bridge`, `host`, or `none`).
+
+---
+
+For more advanced networking, see the [official Docker documentation](https://docs.docker.com/network/).
diff --git a/docs/docs/features/overview.mdx b/docs/docs/features/overview.mdx
deleted file mode 100644
index 04f5de5f0..000000000
--- a/docs/docs/features/overview.mdx
+++ /dev/null
@@ -1,22 +0,0 @@
----
-sidebar_position: 2
-title: Features
----
-
-import FeatureCard from '@site/src/components/FeatureCard';
-import ContainersIcon from '@site/src/components/icons/ContainersIcon';
-import ImagesIcon from '@site/src/components/icons/ImagesIcon';
-import NetworkIcon from '@site/src/components/icons/NetworkIcon';
-
-# Arcane Features
-
-Arcane provides a comprehensive set of features for managing your Docker environments.
-
-<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '1rem', marginTop: '2rem' }}>
- <FeatureCard title="Container Management" description="Start, stop, and inspect containers with an intuitive interface." icon={<ContainersIcon />} />
-
- <FeatureCard title="Image Handling" description="Browse and manage your Docker images. Pull from registries, build new images, and clean up unused ones." icon={<ImagesIcon />} />
-
- <FeatureCard title="Network Visualization" description="Visualize and configure Docker networks to understand container communication." icon={<NetworkIcon />} />
-
-</div>
diff --git a/docs/docs/features/stacks/managing-stacks.md b/docs/docs/features/stacks/managing-stacks.md
deleted file mode 100644
index fa77aa06d..000000000
--- a/docs/docs/features/stacks/managing-stacks.md
+++ /dev/null
@@ -1,56 +0,0 @@
----
-sidebar_position: 2
-title: Managing Stacks
----
-
-# Managing Stacks
-
-This guide explains how to use the Arcane UI to create, inspect, control, and remove Docker Compose stacks.
-
-## Viewing Stacks
-
-Navigate to the "Stacks" section in the Arcane sidebar. Here you will see a list of:
-
-- **Managed Stacks:** Stacks whose definitions are stored and managed by Arcane.
-- **External Stacks:** Stacks detected running on the Docker host but not yet managed by Arcane. These are typically identified by the `com.docker.compose.project` label on their containers.
-
-Each stack entry usually displays its name, status (`running`, `partially running`, `stopped`), and the number of running services/containers.
-
-## Creating a New Stack
-
-1. Click the "Create Stack" or "+" button (the exact UI element may vary).
-2. A form or modal will appear asking for:
- - **Stack Name:** A unique name for your stack (e.g., `my-app`, `monitoring`). This name will be used as the Compose project name.
- - **Compose Definition:** A text editor area where you can paste or write your `docker-compose.yml` content.
-3. Review your Compose definition for correctness.
-4. Click "Create" or "Deploy". Arcane will save the definition and attempt to start the stack using `compose up`.
-
-## Inspecting a Stack
-
-Click on the name of any stack (managed or external) in the list to view its details page. This page typically shows:
-
-- **Stack Name and Status:** The current state of the stack.
-- **Services:** A list of services defined in the `docker-compose.yml`, along with the status and count of running containers for each service.
-- **Compose Definition:** The content of the `docker-compose.yml` file associated with the stack.
-- **Action Buttons:** Controls available for the stack (see below).
-
-## Controlling Managed Stacks
-
-On the details page for a **managed stack**, you will find several action buttons:
-
-- **Start:** Starts all services defined in the stack (`compose up -d`). If the stack is already running, this might recreate services whose configuration or image has changed.
-- **Stop:** Stops and removes the containers associated with the stack (`compose down`). Persistent volumes are typically _not_ removed by this action.
-- **Restart:** Stops the stack (`compose down`) and then starts it again (`compose up -d`). Useful for applying changes or refreshing the application state.
-- **Redeploy:** Stops the stack (`compose down`), attempts to pull the latest images for all services defined in the compose file (`compose pull`), and then starts the stack again (`compose up -d`). This is useful for updating your application services to their newest image versions.
-- **Update:** Allows you to modify the stack's name or edit its `docker-compose.yml` definition. After saving changes, you might need to manually Redeploy or Restart the stack for them to take effect.
-- **Remove:** Stops the stack (`compose down`) and permanently deletes the stack's definition (`docker-compose.yml` and `meta.json`) from Arcane's storage (`/app/data/stacks`). **Use with caution!**
-
-## Importing External Stacks
-
-If Arcane detects an external stack running on your Docker host, it will typically appear in the Stacks list with an "Import" option.
-
-1. Find the external stack in the list.
-2. Click the "Import" button associated with it.
-3. Arcane will attempt to retrieve the `docker-compose.yml` content (if possible, though this might not always be feasible depending on how the stack was deployed) and pre-fill the creation form.
-4. Review the retrieved name and Compose definition. You may need to manually paste the correct `docker-compose.yml` content if it couldn't be retrieved automatically.
-5. Click "Import" or "Save". The stack will now be listed as a managed stack, and its definition will be stored by Arcane. You can now use all the control actions available for managed stacks.
diff --git a/docs/docs/features/stacks/overview.md b/docs/docs/features/stacks/overview.md
index 2cc1ca7c6..1c1130521 100644
--- a/docs/docs/features/stacks/overview.md
+++ b/docs/docs/features/stacks/overview.md
@@ -5,43 +5,57 @@ title: Stacks Overview
# Stacks Overview
-The "Stacks" feature in Arcane allows you to manage multi-container applications defined using Docker Compose files directly within the Arcane UI. It provides a convenient way to deploy, monitor, and control complex applications composed of multiple services.
+## What is a Stack?
-## Key Concepts
+A **Stack** is a collection of services defined in a `compose.yaml` file. For example, a stack might include a web server, a database, and a cache, all running together.
-- **Stack:** Represents a multi-container application defined by a `docker-compose.yml` file. Arcane uses the `docker-compose` command-line tool (or equivalent library like `dockerode-compose`) under the hood to manage these.
-- **Managed Stack:** A stack created or imported within Arcane. Its definition (`docker-compose.yml` and metadata) is stored within Arcane's configured data directory (see [Storage](#storage)).
-- **External Stack:** A stack detected running on the Docker host (identified by the `com.docker.compose.project` label) but whose definition is not stored or managed by Arcane. You can import these to manage them within Arcane.
-- **Stack Definition:** Consists primarily of the `docker-compose.yml` content and associated metadata like name and timestamps stored by Arcane.
-- **Stack Status:** Arcane determines the status based on the state of the containers belonging to the stack:
- - `running`: All services defined in the compose file are running.
- - `partially running`: Some, but not all, services are running.
- - `stopped`: No services belonging to the stack are running.
+---
+
+## What Can You Do With Stacks in Arcane?
+
+- **View Stacks:** See all your managed stacks and any external stacks detected on your Docker host.
+- **Create Stacks:** Add a new stack by giving it a name and pasting your `compose.yaml` content.
+- **Start/Stop Stacks:** Easily start or stop all services in a stack with one click.
+- **Restart or Redeploy:** Restart a stack or redeploy it to pull the latest images for your services.
+- **Update Stacks:** Change the stack’s name or update its compose file.
+- **Remove Stacks:** Delete a stack and its definition from Arcane.
+- **Import External Stacks:** Bring existing stacks (not yet managed by Arcane) under Arcane’s control.
+
+---
+
+## How to Use Stacks
-## Core Functionality
+### Viewing Stacks
-With the Stacks feature, you can:
+1. Go to the **Stacks** section in the sidebar.
+2. You’ll see a list of all stacks, including their names, status (running, partially running, stopped), and how many services are running.
-- **Create Stacks:** Define and deploy new applications by providing a name and the `docker-compose.yml` content.
-- **List Stacks:** View all managed stacks and discovered external stacks.
-- **Inspect Stacks:** See details of a stack, including its services, their status, running container count, and the underlying `docker-compose.yml` content.
-- **Control Stacks:**
- - **Start:** Bring up all services defined in the stack (`compose up`).
- - **Stop:** Stop and remove the stack's containers (`compose down`).
- - **Restart:** Stop and then start the stack (`compose down` followed by `compose up`).
- - **Redeploy:** Stop the stack, pull the latest images for all services, and then start the stack again (`compose down`, `compose pull`, `compose up`).
-- **Update Stacks:** Modify the name or the `docker-compose.yml` content of a managed stack.
-- **Remove Stacks:** Stop the stack's services and permanently delete the stack definition from Arcane's storage.
-- **Import External Stacks:** Bring an existing, externally managed stack under Arcane's control by saving its definition.
+### Creating a Stack
-## Storage
+1. Click the **Create Stack** button.
+2. Enter a name for your stack.
+3. Paste or write your `compose.yaml` content.
+4. Click **Create**. Arcane will save your stack and try to start it.
-Managed stack definitions (`docker-compose.yml` and `meta.json`) are stored within the directory specified by the `stacksDirectory` setting in your `app-settings.json`. By default, this is `/app/data/stacks` inside the Arcane container.
+### Controlling a Stack
-:::tip Persistence
-To ensure your stack definitions are not lost when the Arcane container is recreated, it is crucial to mount the `/app/data` directory (or at least `/app/data/stacks`) as a volume, as shown in the recommended [Docker Compose setup](../getting-started/quickstart).
-:::
+- **Start:** Click the **Start** button to launch all services in the stack.
+- **Stop:** Click **Stop** to stop and remove all containers in the stack.
+- **Restart:** Click **Restart** to stop and then start the stack again.
+- **Redeploy:** Click **Redeploy** to pull the latest images and restart the stack.
+
+### Updating or Removing a Stack
+
+- To update, open the stack and click **Edit**. Change the name or compose file, then save.
+- To remove, click the **Remove** button. Confirm the action to delete the stack from Arcane.
+
+### Importing External Stacks
+
+If Arcane detects a stack running on your Docker host that it doesn’t manage yet, you’ll see an **Import** option. Click it to bring the stack under Arcane’s management.
+
+---
-## Next Steps
+## Where Are My Stacks Stored?
-- Learn how to [Create and Manage Stacks](./managing-stacks).
+Arcane saves your stack definitions (compose files and metadata) in its data directory (by default `/app/data/stacks`).
+**Tip:** To keep your stacks safe, make sure to mount this directory as a Docker volume if you’re running Arcane in a container.
diff --git a/docs/docs/features/volumes/overview.md b/docs/docs/features/volumes/overview.md
index e69de29bb..c663b64b5 100644
--- a/docs/docs/features/volumes/overview.md
+++ b/docs/docs/features/volumes/overview.md
@@ -0,0 +1,28 @@
+# Volume Management
+
+## What Can You Do With Volumes in Arcane?
+
+- **View Volumes:** See a list of all Docker volumes on your system, along with details like name, driver, and usage.
+- **Create Volumes:** Add a new volume by providing a name and (optionally) driver or labels.
+- **Remove Volumes:** Delete volumes you no longer need. Arcane will warn you if a volume is currently in use by a container.
+
+## How to Use
+
+### Viewing Volumes
+
+1. Go to the **Volumes** section in the sidebar.
+2. You’ll see a table listing all your Docker volumes.
+
+### Creating a Volume
+
+1. Click the **Create Volume** button.
+2. Enter a name for your new volume.
+3. (Optional) Choose a driver or add labels if needed.
+4. Click **Create**. Your new volume will appear in the list.
+
+### Removing a Volume
+
+1. In the volumes list, find the volume you want to remove.
+2. Click the dropdown then the **Delete** button (trash icon) in the list.
+3. Confirm the deletion in the dialog.
+ > **Note:** You cannot remove a volume that is currently used by a container.
diff --git a/docs/docs/getting-started/user-management.md b/docs/docs/getting-started/user-management.md
new file mode 100644
index 000000000..b209df1c4
--- /dev/null
+++ b/docs/docs/getting-started/user-management.md
@@ -0,0 +1,20 @@
+---
+sidebar_position: 3
+title: User Management
+---
+
+# User Management
+
+Arcane comes with built-in user management to help you control who can access your app.
+
+## Default Admin User
+
+- On your first run, Arcane will automatically create a default admin user if no users exist.
+- **Username:** `arcane`
+- **Password:** `arcane-admin`
+- The onboarding flow will force you to change this password on first run as well.
+
+## Adding Users
+
+- Go to the Settings in the sidebar then USer Management, and click Create User.
+- Fill in the required details: username, display name, email, and password.
diff --git a/docs/docs/guides/docker-compose.md b/docs/docs/guides/docker-compose.md
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs/docs/guides/remote-hosts.md b/docs/docs/guides/remote-hosts.md
deleted file mode 100644
index bce3b35a9..000000000
--- a/docs/docs/guides/remote-hosts.md
+++ /dev/null
@@ -1,6 +0,0 @@
----
-sidebar_position: 2
-title: Remote Hosts
----
-
-Using a Remote Docker Host is currently not supported but is planned for a future release.
diff --git a/docs/docs/guides/troubleshooting.md b/docs/docs/guides/troubleshooting.md
index dd1c4baae..ae1f7b17b 100644
--- a/docs/docs/guides/troubleshooting.md
+++ b/docs/docs/guides/troubleshooting.md
@@ -3,15 +3,62 @@ sidebar_position: 1
title: Troubleshooting
---
-### Docker Socker Permission Issues
+# Troubleshooting
-Make sure you run:
+If you run into problems using Arcane, try these simple steps to get back on track.
-- Linux: `getent group docker | cut -d: -f3`
-- macOS (if Docker group exists): `dscl . -read /Groups/docker PrimaryGroupID | awk '{print $2}'`
+## Docker Connection Issues
-This will give you the GID of the local docker group.
+- **Is Docker running?**
-Then pass that to the DOCKER_GID environment variable in your docker-compose.yml file.
+ - Make sure Docker is started on your computer. You can check by running `docker ps` in your terminal.
-For example: `DOCKER_GID=998`
+- **Permission errors or can't connect to Docker?**
+ 1. Find your Docker group GID:
+ - Linux: `getent group docker | cut -d: -f3`
+ - macOS: `dscl . -read /Groups/docker PrimaryGroupID | awk '{print $2}'`
+ 2. Set the `DOCKER_GID` environment variable in your `docker-compose.yml` to match the GID you found.
+ ```yaml
+ environment:
+ - DOCKER_GID=998 # Replace 998 with your actual GID
+ ```
+ 3. Restart Arcane after making changes:
+ ```bash
+ docker-compose down && docker-compose up -d
+ ```
+
+## Web Interface Not Loading
+
+- Make sure the Arcane container is running:
+ ```bash
+ docker ps | grep arcane
+ ```
+- Check the logs for errors:
+ ```bash
+ docker logs arcane
+ ```
+- Make sure you are visiting the correct port (default is http://localhost:3000).
+
+## Can't Start, Stop, or Remove Containers
+
+- Make sure you have the right permissions (see above).
+- Try stopping or removing the container directly with Docker CLI to see if the problem is with Docker or Arcane.
+- You can only remove stopped containers (unless you use force remove).
+
+## Can't Pull or Remove Images
+
+- Check your internet connection if pulling images fails.
+- Make sure the image is not in use by a running container before removing it.
+- Try pulling or removing the image with Docker CLI to see if the issue is with Docker or Arcane.
+
+## Still Stuck?
+
+- Check the Arcane logs for more details:
+ ```bash
+ docker logs arcane --tail 100
+ ```
+- Restart the Arcane container:
+ ```bash
+ docker restart arcane
+ ```
+- If you still have trouble, open an issue on GitHub with details about your problem.
diff --git a/package-lock.json b/package-lock.json
index 31639b0e1..d5df2cb94 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10,6 +10,7 @@
"dependencies": {
"@codemirror/lang-yaml": "^6.1.2",
"@tanstack/table-core": "^8.21.3",
+ "axios": "^1.9.0",
"bcryptjs": "^3.0.2",
"codemirror": "^6.0.1",
"dockerode": "^4.0.6",
@@ -26,11 +27,12 @@
"@eslint/compat": "^1.2.5",
"@eslint/js": "^9.18.0",
"@lucide/svelte": "^0.503.0",
+ "@playwright/test": "^1.52.0",
"@sveltejs/adapter-node": "^5.2.12",
"@sveltejs/kit": "^2.20.8",
"@sveltejs/vite-plugin-svelte": "^5.0.0",
"@tailwindcss/vite": "^4.0.0",
- "@types/bcryptjs": "^2.4.6",
+ "@types/bcryptjs": "^3.0.0",
"@types/dockerode": "^3.3.38",
"@types/dockerode-compose": "^1.4.1",
"@types/js-yaml": "^4.0.9",
@@ -50,9 +52,9 @@
"tailwind-variants": "^1.0.0",
"tailwindcss": "^4.0.0",
"tailwindcss-animate": "^1.0.7",
- "typescript": "^5.5.0",
+ "typescript": "^5.8.0",
"typescript-eslint": "^8.31.1",
- "vite": "^6.3.3",
+ "vite": "^6.3.4",
"zod": "^3.24.3"
}
},
@@ -668,9 +670,9 @@
}
},
"node_modules/@eslint/compat": {
- "version": "1.2.8",
- "resolved": "https://registry.npmjs.org/@eslint/compat/-/compat-1.2.8.tgz",
- "integrity": "sha512-LqCYHdWL/QqKIJuZ/ucMAv8d4luKGs4oCPgpt8mWztQAtPrHfXKQ/XAUc8ljCHAfJCn6SvkpTcGt5Tsh8saowA==",
+ "version": "1.2.9",
+ "resolved": "https://registry.npmjs.org/@eslint/compat/-/compat-1.2.9.tgz",
+ "integrity": "sha512-gCdSY54n7k+driCadyMNv8JSPzYLeDVM/ikZRtvtROBpRdFSkS8W9A82MqsaY7lZuwL0wiapgD0NT1xT0hyJsA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
@@ -701,9 +703,9 @@
}
},
"node_modules/@eslint/config-helpers": {
- "version": "0.2.1",
- "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.2.1.tgz",
- "integrity": "sha512-RI17tsD2frtDu/3dmI7QRrD4bedNKPM08ziRYaC5AhkGrzIAJelm9kJU1TznK+apx6V+cqRz8tfpEeG3oIyjxw==",
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.2.2.tgz",
+ "integrity": "sha512-+GPzk8PlG0sPpzdU5ZvIRMPidzAnZDl/s9L+y13iodqvb8leL53bTannOrQ/Im7UkpsmFU5Ily5U60LWixnmLg==",
"dev": true,
"license": "Apache-2.0",
"engines": {
@@ -1129,6 +1131,22 @@
"node": ">= 8"
}
},
+ "node_modules/@playwright/test": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.52.0.tgz",
+ "integrity": "sha512-uh6W7sb55hl7D6vsAeA+V2p5JnlAqzhqFyF0VcJkKZXkgnFcVG9PziERRHQfPLfNGx1C292a4JqbWzhR8L4R1g==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright": "1.52.0"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@polka/url": {
"version": "1.0.0-next.29",
"resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz",
@@ -2019,11 +2037,15 @@
}
},
"node_modules/@types/bcryptjs": {
- "version": "2.4.6",
- "resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz",
- "integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==",
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-3.0.0.tgz",
+ "integrity": "sha512-WRZOuCuaz8UcZZE4R5HXTco2goQSI2XxjGY3hbM/xDvwmqFWd4ivooImsMx65OKM6CtNKbnZ5YL+YwAwK7c1dg==",
+ "deprecated": "This is a stub types definition. bcryptjs provides its own type definitions, so you do not need this installed.",
"dev": true,
- "license": "MIT"
+ "license": "MIT",
+ "dependencies": {
+ "bcryptjs": "*"
+ }
},
"node_modules/@types/cookie": {
"version": "0.6.0",
@@ -2525,6 +2547,23 @@
"safer-buffer": "~2.1.0"
}
},
+ "node_modules/asynckit": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
+ "license": "MIT"
+ },
+ "node_modules/axios": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
+ "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
+ "license": "MIT",
+ "dependencies": {
+ "follow-redirects": "^1.15.6",
+ "form-data": "^4.0.0",
+ "proxy-from-env": "^1.1.0"
+ }
+ },
"node_modules/axobject-query": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
@@ -2681,6 +2720,19 @@
"node": ">=10.0.0"
}
},
+ "node_modules/call-bind-apply-helpers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
@@ -2813,6 +2865,18 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT"
},
+ "node_modules/combined-stream": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+ "license": "MIT",
+ "dependencies": {
+ "delayed-stream": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/commondir": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz",
@@ -2927,6 +2991,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/delayed-stream": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
"node_modules/detect-libc": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.4.tgz",
@@ -2996,6 +3069,20 @@
"tar-fs": "^2.1.1"
}
},
+ "node_modules/dunder-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/effect": {
"version": "3.14.18",
"resolved": "https://registry.npmjs.org/effect/-/effect-3.14.18.tgz",
@@ -3037,6 +3124,51 @@
"node": ">=10.13.0"
}
},
+ "node_modules/es-define-property": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-object-atoms": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-set-tostringtag": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6",
+ "has-tostringtag": "^1.0.2",
+ "hasown": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/esbuild": {
"version": "0.25.3",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.3.tgz",
@@ -3500,6 +3632,41 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/follow-redirects": {
+ "version": "1.15.9",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
+ "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/RubenVerborgh"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0"
+ },
+ "peerDependenciesMeta": {
+ "debug": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/form-data": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
+ "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==",
+ "license": "MIT",
+ "dependencies": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.8",
+ "es-set-tostringtag": "^2.1.0",
+ "mime-types": "^2.1.12"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/formsnap": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/formsnap/-/formsnap-2.0.1.tgz",
@@ -3566,7 +3733,6 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
- "dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
@@ -3581,6 +3747,43 @@
"node": "6.* || 8.* || >= 10.*"
}
},
+ "node_modules/get-intrinsic": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/glob-parent": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
@@ -3607,6 +3810,18 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/gopd": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
@@ -3630,11 +3845,37 @@
"node": ">=8"
}
},
+ "node_modules/has-symbols": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-tostringtag": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
+ "license": "MIT",
+ "dependencies": {
+ "has-symbols": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
@@ -4227,6 +4468,15 @@
"@jridgewell/sourcemap-codec": "^1.5.0"
}
},
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/memoize-weak": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/memoize-weak/-/memoize-weak-1.0.2.tgz",
@@ -4271,6 +4521,27 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
@@ -4511,6 +4782,53 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/playwright": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.52.0.tgz",
+ "integrity": "sha512-JAwMNMBlxJ2oD1kce4KPtMkDeKGHQstdpFPcPH3maElAXon/QZeTvtsfXmTMRyO9TslfoYOXkSsvao2nE1ilTw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright-core": "1.52.0"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "fsevents": "2.3.2"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.52.0.tgz",
+ "integrity": "sha512-l2osTgLXSMeuLZOML9qYODUQoPPnUsKsb5/P6LJ2e6uPKXUdPK5WYhN4z03G+YNbWmGDY4YENauNu4ZKczreHg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/playwright/node_modules/fsevents": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
"node_modules/postcss": {
"version": "8.5.3",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.3.tgz",
@@ -4745,6 +5063,12 @@
"node": ">=12.0.0"
}
},
+ "node_modules/proxy-from-env": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
+ "license": "MIT"
+ },
"node_modules/pump": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.2.tgz",
@@ -5647,9 +5971,9 @@
}
},
"node_modules/ts-deepmerge": {
- "version": "7.0.2",
- "resolved": "https://registry.npmjs.org/ts-deepmerge/-/ts-deepmerge-7.0.2.tgz",
- "integrity": "sha512-akcpDTPuez4xzULo5NwuoKwYRtjQJ9eoNfBACiBMaXwNAx7B1PKfe5wqUFJuW5uKzQ68YjDFwPaWHDG1KnFGsA==",
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/ts-deepmerge/-/ts-deepmerge-7.0.3.tgz",
+ "integrity": "sha512-Du/ZW2RfwV/D4cmA5rXafYjBQVuvu4qGiEEla4EmEHVHgRdx68Gftx7i66jn2bzHPwSVZY36Ae6OuDn9el4ZKA==",
"dev": true,
"license": "ISC",
"engines": {
diff --git a/package.json b/package.json
index 0354bac62..5a2e6b18c 100644
--- a/package.json
+++ b/package.json
@@ -9,19 +9,25 @@
"preview": "vite preview --port 3000",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
- "format": "prettier --write .",
+ "format": "prettier --write ./src",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
- "lint": "eslint ./src"
+ "lint": "eslint ./src",
+ "lint:fix": "eslint ./src --fix",
+ "test:init": "APP_ENV=TEST npx tsx scripts/init-test-env.ts",
+ "test:e2e": "APP_ENV=TEST npm run test:init && playwright test",
+ "test:e2e:ui": "playwright test --ui",
+ "test:e2e:report": "playwright show-report"
},
"devDependencies": {
"@eslint/compat": "^1.2.5",
"@eslint/js": "^9.18.0",
"@lucide/svelte": "^0.503.0",
+ "@playwright/test": "^1.52.0",
"@sveltejs/adapter-node": "^5.2.12",
"@sveltejs/kit": "^2.20.8",
"@sveltejs/vite-plugin-svelte": "^5.0.0",
"@tailwindcss/vite": "^4.0.0",
- "@types/bcryptjs": "^2.4.6",
+ "@types/bcryptjs": "^3.0.0",
"@types/dockerode": "^3.3.38",
"@types/dockerode-compose": "^1.4.1",
"@types/js-yaml": "^4.0.9",
@@ -41,14 +47,15 @@
"tailwind-variants": "^1.0.0",
"tailwindcss": "^4.0.0",
"tailwindcss-animate": "^1.0.7",
- "typescript": "^5.5.0",
+ "typescript": "^5.8.0",
"typescript-eslint": "^8.31.1",
- "vite": "^6.3.3",
+ "vite": "^6.3.4",
"zod": "^3.24.3"
},
"dependencies": {
"@codemirror/lang-yaml": "^6.1.2",
"@tanstack/table-core": "^8.21.3",
+ "axios": "^1.9.0",
"bcryptjs": "^3.0.2",
"codemirror": "^6.0.1",
"dockerode": "^4.0.6",
diff --git a/playwright.config.ts b/playwright.config.ts
new file mode 100644
index 000000000..d0cb33dcd
--- /dev/null
+++ b/playwright.config.ts
@@ -0,0 +1,34 @@
+import { defineConfig, devices } from '@playwright/test';
+
+const authFile = 'tests/.auth/login.json';
+
+export default defineConfig({
+ testDir: './tests',
+ fullyParallel: true,
+ forbidOnly: !!process.env.CI,
+ retries: process.env.CI ? 2 : 0,
+ workers: process.env.CI ? 1 : undefined,
+ reporter: process.env.CI ? [['html', { outputFolder: 'tests/.report' }], ['github']] : [['line'], ['html', { open: 'never', outputFolder: 'tests/.report' }]],
+ use: {
+ baseURL: 'http://localhost:3000',
+ trace: 'on-first-retry',
+ video: 'retain-on-failure'
+ },
+ projects: [
+ { name: 'setup', testMatch: /.*\.setup\.ts/ },
+ {
+ name: 'chromium',
+ use: { ...devices['Desktop Chrome'], storageState: authFile },
+ dependencies: ['setup']
+ }
+ ],
+ webServer: {
+ command: 'APP_ENV=TEST npm run dev',
+ url: 'http://localhost:3000',
+ reuseExistingServer: !process.env.CI,
+ timeout: 120 * 1000,
+ env: {
+ APP_ENV: 'TEST'
+ }
+ }
+});
diff --git a/scripts/init-test-env.ts b/scripts/init-test-env.ts
new file mode 100644
index 000000000..f93f21cec
--- /dev/null
+++ b/scripts/init-test-env.ts
@@ -0,0 +1,97 @@
+import fs from 'fs/promises';
+import path from 'path';
+import bcrypt from 'bcryptjs'; // Make sure bcryptjs is installed as a dev dependency
+import { encrypt } from '../src/lib/services/encryption-service';
+import { ensureDirectory } from '../src/lib/services/paths-service';
+import { DEFAULT_SETTINGS } from '../src/lib/services/settings-service';
+
+// --- Configuration ---
+const TEST_USERNAME = 'admin';
+const TEST_PASSWORD = 'admin'; // Use a simple password for testing
+const TEST_DATA_DIR = process.env.APP_ENV === 'TEST' ? path.resolve(process.cwd(), '.test-data') : null;
+// --- End Configuration ---
+
+async function setupTestEnvironment() {
+ console.log('Starting test environment setup...');
+
+ if (!TEST_DATA_DIR) {
+ throw new Error('This script should only run in TEST environment (APP_ENV=TEST)');
+ }
+
+ // --- Ensure Directories Exist ---
+ console.log(`Ensuring test data directory exists: ${TEST_DATA_DIR}`);
+ const settingsDir = path.join(TEST_DATA_DIR, 'settings');
+ const usersDir = path.join(TEST_DATA_DIR, 'users');
+ await ensureDirectory(TEST_DATA_DIR);
+ await ensureDirectory(settingsDir);
+ await ensureDirectory(usersDir);
+ console.log('Directories ensured.');
+
+ // --- Initialize Test User ---
+ console.log(`Initializing test user: ${TEST_USERNAME}`);
+ const usersFilePath = path.join(usersDir, 'users.json');
+ const hashedPassword = await bcrypt.hash(TEST_PASSWORD, 10);
+ const testUser = {
+ username: TEST_USERNAME,
+ password: hashedPassword,
+ roles: ['admin', 'containers:view', 'containers:manage', 'settings:view', 'networks:view', 'networks:manage'], // Add all necessary roles for tests
+ createdAt: new Date().toISOString()
+ };
+ // Write user data (overwriting if exists)
+ await fs.writeFile(usersFilePath, JSON.stringify([testUser], null, 2), { mode: 0o600 });
+ console.log(`Test user data written to ${usersFilePath}`);
+
+ // --- Initialize Settings ---
+ console.log('Initializing settings...');
+ const testSettings = {
+ ...DEFAULT_SETTINGS,
+ onboarding: {
+ completed: true,
+ completedAt: new Date().toISOString()
+ },
+ auth: {
+ rbacEnabled: true,
+ localAuthEnabled: true,
+ sessionTimeout: 60,
+ passwordPolicy: 'medium'
+ },
+ registryCredentials: []
+ };
+
+ const { auth, registryCredentials, ...nonSensitiveSettings } = testSettings;
+ const dataToSave = {
+ ...nonSensitiveSettings,
+ _encrypted: await encrypt({ auth, registryCredentials })
+ };
+
+ const settingsDatPath = path.join(settingsDir, 'settings.dat');
+ await fs.writeFile(settingsDatPath, JSON.stringify(dataToSave, null, 2), { mode: 0o600 });
+ console.log(`Settings written to ${settingsDatPath}`);
+
+ // --- Cleanup Old/Unused Files ---
+ console.log('Cleaning up potentially old settings files...');
+ try {
+ await fs.unlink(path.join(settingsDir, 'settings.json'));
+ } catch (e) {
+ /* ignore */
+ }
+ try {
+ await fs.unlink(path.join(TEST_DATA_DIR, 'app-settings.json'));
+ } catch (e) {
+ /* ignore */
+ }
+ console.log('Cleanup complete.');
+
+ console.log('--- Test environment setup finished successfully! ---');
+}
+
+const isRunDirectly = import.meta.url && process.argv[1] && import.meta.url === `file://${path.resolve(process.argv[1])}`;
+
+if (isRunDirectly) {
+ setupTestEnvironment().catch((error) => {
+ console.error('Error setting up test environment:', error);
+ process.exit(1);
+ });
+}
+
+export { setupTestEnvironment };
diff --git a/src/app.d.ts b/src/app.d.ts
index 2a2f0075a..68203dd88 100644
--- a/src/app.d.ts
+++ b/src/app.d.ts
@@ -4,7 +4,10 @@ import type { UserSession } from '$lib/types/session.type';
declare global {
namespace App {
- // interface Error {}
+ interface Error {
+ message: string;
+ status?: number;
+ }
interface Locals {
user?: User | null;
session?: UserSession | null;
diff --git a/src/hooks.server.ts b/src/hooks.server.ts
index 6560d6bfb..c5567a5b0 100644
--- a/src/hooks.server.ts
+++ b/src/hooks.server.ts
@@ -6,6 +6,9 @@ import { getUserByUsername } from '$lib/services/user-service';
import { getSettings } from '$lib/services/settings-service';
import { checkFirstRun } from '$lib/utils/onboarding.utils';
+// Get environment variable
+const isTestEnvironment = process.env.APP_ENV === 'TEST';
+
// Initialize needed services
try {
await Promise.all([checkFirstRun(), initComposeService(), initAutoUpdateScheduler()]);
@@ -73,21 +76,22 @@ export const handle: Handle = async ({ event, resolve }) => {
const isOnboardingPath = path.startsWith('/onboarding');
const isApiRoute = path.startsWith('/api/');
- // Critical check: For ANY non-onboarding path, redirect to onboarding if not completed
- // This is the key change to prevent bypassing onboarding
- if (!isOnboardingPath && !isApiRoute && !settings?.onboarding?.completed) {
- throw redirect(302, '/onboarding/welcome');
- }
+ // Skip onboarding checks in test environment
+ if (!isTestEnvironment) {
+ // Critical check: For ANY non-onboarding path, redirect to onboarding if not completed
+ if (!isOnboardingPath && !isApiRoute && !settings?.onboarding?.completed) {
+ throw redirect(302, '/onboarding/welcome');
+ }
- // During onboarding, only allow API calls needed for onboarding
- // Optional enhancement to allow specific API calls during onboarding
- if (isApiRoute && !settings?.onboarding?.completed) {
- // Only allow these specific API endpoints during onboarding
- const allowedApiDuringOnboarding = ['/api/settings', '/api/users/password'];
- const isAllowedApi = allowedApiDuringOnboarding.some((api) => path.startsWith(api));
+ // During onboarding, only allow API calls needed for onboarding
+ if (isApiRoute && !settings?.onboarding?.completed) {
+ // Only allow these specific API endpoints during onboarding
+ const allowedApiDuringOnboarding = ['/api/settings', '/api/users/password'];
+ const isAllowedApi = allowedApiDuringOnboarding.some((api) => path.startsWith(api));
- if (!isAllowedApi) {
- throw redirect(302, '/onboarding/welcome');
+ if (!isAllowedApi) {
+ throw redirect(302, '/onboarding/welcome');
+ }
}
}
diff --git a/src/lib/components/action-buttons.svelte b/src/lib/components/action-buttons.svelte
index 39a1e9376..e2a969c3f 100644
--- a/src/lib/components/action-buttons.svelte
+++ b/src/lib/components/action-buttons.svelte
@@ -1,21 +1,19 @@
<script lang="ts">
- import { Button } from '$lib/components/ui/button/index.js';
import { Play, StopCircle, RotateCcw, Download, Trash2, Loader2, RefreshCcwDot } from '@lucide/svelte';
- import ConfirmDialog from './confirm-dialog.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { openConfirmDialog } from './confirm-dialog';
import { invalidateAll } from '$app/navigation';
- import type { ApiResponse } from '$lib/types/api-response.type';
import { toast } from 'svelte-sonner';
+ import type { LoadingStates } from '$lib/types/loading-states.type';
+ import ContainerAPIService from '$lib/services/api/container-api-service';
+ import StackAPIService from '$lib/services/api/stack-api-service';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import { handleApiReponse } from '$lib/utils/api.util';
+
+ const containerApi = new ContainerAPIService();
+ const stackApi = new StackAPIService();
type TargetType = 'container' | 'stack';
- type LoadingStates = {
- start?: boolean;
- stop?: boolean;
- restart?: boolean;
- pull?: boolean;
- deploy?: boolean;
- redeploy?: boolean;
- remove?: boolean;
- };
let {
id,
@@ -27,107 +25,132 @@
id: string;
type?: TargetType;
itemState?: string;
- loading?: LoadingStates;
+ loading: LoadingStates;
onActionComplete?: () => void;
} = $props();
- // Track dialog states
- let showRemoveDialog = $state(false);
- let showRedeployDialog = $state(false);
-
- // Track loading states for each action
- let isStarting = $state(false);
- let isStopping = $state(false);
- let isRestarting = $state(false);
- let isRedeploying = $state(false);
- let isRemoving = $state(false);
- let isPulling = $state(false);
+ let isLoading = $state({
+ start: false,
+ stop: false,
+ restart: false,
+ remove: false,
+ pulling: false,
+ redeploy: false
+ });
const isRunning = $derived(itemState === 'running' || (type === 'stack' && itemState === 'partially running'));
- // Handle showing confirmation dialogs
+ $effect(() => {
+ isLoading.start = loading.start ?? false;
+ isLoading.stop = loading.stop ?? false;
+ isLoading.pulling = loading.pull ?? false;
+ isLoading.remove = loading.remove ?? false;
+ isLoading.restart = loading.restart ?? false;
+ isLoading.redeploy = loading.redeploy ?? false;
+ });
+
function confirmAction(action: string) {
if (action === 'remove') {
- showRemoveDialog = true;
+ openConfirmDialog({
+ title: `Confirm Removal`,
+ message: `Are you sure you want to remove this ${type}? This action cannot be undone.`,
+ confirm: {
+ label: 'Remove',
+ destructive: true,
+ action: async () => {
+ isLoading.remove = true;
+ handleApiReponse(
+ await tryCatch(type === 'container' ? containerApi.remove(id) : stackApi.remove(id)),
+ `Failed to Remove ${type}`,
+ (value) => (isLoading.remove = value),
+ async () => {
+ toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} Removed Successfully`);
+ await invalidateAll();
+ }
+ );
+ }
+ }
+ });
} else if (action === 'redeploy') {
- showRedeployDialog = true;
- }
- }
-
- // Generic API call function
- async function callApi(action: string, loadingStateSetter: (value: boolean) => void) {
- loadingStateSetter(true);
-
- // Different endpoint format for stacks vs containers
- let endpoint;
- if (type === 'stack') {
- endpoint = `/api/stacks/${id}/${action}`; // No plural, no separator between "stack" and ID
- } else {
- endpoint = `/api/${type}s/${id}/${action}`; // Plural with separator for containers
- }
-
- const method = action === 'remove' ? 'DELETE' : 'POST';
-
- try {
- const response = await fetch(endpoint, { method });
- // Gracefully fallback when there is no JSON body
- let result: ApiResponse = {};
- if (response.headers.get('content-type')?.includes('application/json')) {
- result = await response.json();
- }
- if (!response.ok) {
- throw new Error(result.error ?? `Failed to ${action} ${type}`);
- }
- toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} ${action}ed successfully`);
- await invalidateAll();
- onActionComplete();
- } catch (error: Error | unknown) {
- console.error(`Error ${action}ing ${type}:`, error);
- const errorMessage = error instanceof Error ? error.message : String(error);
- toast.error(`Failed to ${action} ${type}: ${errorMessage}`);
- } finally {
- loadingStateSetter(false);
+ openConfirmDialog({
+ title: `Confirm Redeploy`,
+ message: `Are you sure you want to redeploy this ${type}?`,
+ confirm: {
+ label: 'Redeploy',
+ action: async () => {
+ isLoading.redeploy = true;
+ handleApiReponse(
+ await tryCatch(stackApi.redeploy(id)),
+ `Failed to Redeploy ${type}`,
+ (value) => (isLoading.redeploy = value),
+ async () => {
+ toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} Redeployed Successfully`);
+ await invalidateAll();
+ }
+ );
+ }
+ }
+ });
}
}
- // Action handlers
async function handleStart() {
- await callApi('start', (value) => (isStarting = value));
+ isLoading.start = true;
+ handleApiReponse(
+ await tryCatch(type === 'container' ? containerApi.start(id) : stackApi.start(id)),
+ `Failed to Start ${type}`,
+ (value) => (isLoading.start = value),
+ async () => {
+ toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} Started Successfully`);
+ await invalidateAll();
+ }
+ );
}
async function handleStop() {
- await callApi('stop', (value) => (isStopping = value));
+ isLoading.stop = true;
+ handleApiReponse(
+ await tryCatch(type === 'container' ? containerApi.stop(id) : stackApi.stop(id)),
+ `Failed to Stop ${type}`,
+ (value) => (isLoading.stop = value),
+ async () => {
+ toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} Stopped Successfully`);
+ await invalidateAll();
+ }
+ );
}
async function handleRestart() {
- await callApi('restart', (value) => (isRestarting = value));
- }
-
- async function handleRedeploy() {
- showRedeployDialog = false;
- await callApi('redeploy', (value) => (isRedeploying = value));
- }
-
- async function handleRemove() {
- showRemoveDialog = false;
- await callApi('remove', (value) => (isRemoving = value));
+ isLoading.restart = true;
+ handleApiReponse(
+ await tryCatch(type === 'container' ? containerApi.restart(id) : stackApi.restart(id)),
+ `Failed to Restart ${type}`,
+ (value) => (isLoading.restart = value),
+ async () => {
+ toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} Restarted Successfully`);
+ await invalidateAll();
+ }
+ );
}
async function handlePull() {
- await callApi('pull', (value) => (isPulling = value));
+ isLoading.pulling = true;
+ handleApiReponse(
+ await tryCatch(type === 'container' ? containerApi.pull(id) : stackApi.pull(id)),
+ 'Failed to Pull Image(s)',
+ (value) => (isLoading.pulling = value),
+ async () => {
+ toast.success('Image(s) Pulled Successfully.');
+ await invalidateAll();
+ }
+ );
}
</script>
-<!-- Confirmation Dialogs -->
-<ConfirmDialog bind:open={showRemoveDialog} title="Confirm Removal" description={`Are you sure you want to remove this ${type}? This action cannot be undone.`} confirmLabel="Remove" variant="destructive" onConfirm={handleRemove} />
-
-<ConfirmDialog bind:open={showRedeployDialog} title="Confirm Redeploy" description={`Are you sure you want to redeploy this ${type}?`} confirmLabel="Redeploy" variant="default" onConfirm={handleRedeploy} />
-
-<!-- Action buttons -->
<div class="flex items-center gap-2">
{#if !isRunning}
- <Button type="button" variant="default" disabled={isStarting || loading.start} class="font-medium" onclick={handleStart}>
- {#if isStarting || loading.start}
+ <Button type="button" variant="default" disabled={isLoading.start || loading.start} class="font-medium" onclick={() => handleStart()}>
+ {#if isLoading.start || loading.start}
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
{:else}
<Play class="w-4 h-4 mr-2" />
@@ -135,8 +158,8 @@
{type === 'stack' ? 'Deploy' : 'Start'}
</Button>
{:else}
- <Button type="button" variant="secondary" disabled={isStopping || loading.stop} class="font-medium" onclick={handleStop}>
- {#if isStopping || loading.stop}
+ <Button type="button" variant="secondary" disabled={isLoading.stop || loading.stop} class="font-medium" onclick={() => handleStop()}>
+ {#if isLoading.stop || loading.stop}
<Loader2 class="w-4 h-4 animate-spin" />
{:else}
<StopCircle class="w-4 h-4" />
@@ -144,8 +167,8 @@
Stop
</Button>
- <Button type="button" variant="outline" disabled={isRestarting || loading.restart} class="font-medium" onclick={handleRestart}>
- {#if isRestarting || loading.restart}
+ <Button type="button" variant="outline" disabled={isLoading.restart || loading.restart} class="font-medium" onclick={() => handleRestart()}>
+ {#if isLoading.restart || loading.restart}
<Loader2 class="w-4 h-4 animate-spin" />
{:else}
<RotateCcw class="w-4 h-4" />
@@ -155,8 +178,8 @@
{/if}
{#if type === 'container'}
- <Button type="button" variant="destructive" disabled={isRemoving || loading.remove} class="font-medium" onclick={() => confirmAction('remove')}>
- {#if isRemoving || loading.remove}
+ <Button type="button" variant="destructive" disabled={isLoading.remove || loading.remove} class="font-medium" onclick={() => confirmAction('remove')}>
+ {#if isLoading.remove || loading.remove}
<Loader2 class="w-4 h-4 animate-spin" />
{:else}
<Trash2 class="w-4 h-4" />
@@ -164,8 +187,8 @@
Remove
</Button>
{:else}
- <Button type="button" variant="secondary" disabled={isRedeploying || loading.redeploy} class="font-medium" onclick={() => confirmAction('redeploy')}>
- {#if isRedeploying || loading.redeploy}
+ <Button type="button" variant="secondary" disabled={isLoading.redeploy || loading.redeploy} class="font-medium" onclick={() => confirmAction('redeploy')}>
+ {#if isLoading.redeploy || loading.redeploy}
<Loader2 class="w-4 h-4 animate-spin" />
{:else}
<RefreshCcwDot class="w-4 h-4" />
@@ -173,8 +196,8 @@
Redeploy
</Button>
- <Button type="button" variant="outline" disabled={isPulling || loading.pull} class="font-medium" onclick={handlePull}>
- {#if isPulling || loading.pull}
+ <Button type="button" variant="outline" disabled={isLoading.pulling || loading.pull} class="font-medium" onclick={() => handlePull()}>
+ {#if isLoading.pulling || loading.pull}
<Loader2 class="w-4 h-4 animate-spin" />
{:else}
<Download class="w-4 h-4" />
@@ -182,8 +205,8 @@
Pull
</Button>
- <Button type="button" variant="destructive" disabled={isRemoving || loading.remove} class="font-medium" onclick={() => confirmAction('remove')}>
- {#if isRemoving || loading.remove}
+ <Button type="button" variant="destructive" disabled={isLoading.remove || loading.remove} class="font-medium" onclick={() => confirmAction('remove')}>
+ {#if isLoading.remove || loading.remove}
<Loader2 class="w-4 h-4 animate-spin" />
{:else}
<Trash2 class="w-4 h-4" />
diff --git a/src/lib/components/confirm-dialog.svelte b/src/lib/components/confirm-dialog.svelte
deleted file mode 100644
index 154dc4224..000000000
--- a/src/lib/components/confirm-dialog.svelte
+++ /dev/null
@@ -1,71 +0,0 @@
-<script lang="ts">
- import * as Dialog from '$lib/components/ui/dialog/index.js';
- import { Button } from '$lib/components/ui/button/index.js';
- import { AlertTriangle } from '@lucide/svelte';
- import { Checkbox } from '$lib/components/ui/checkbox/index.js';
- import { Label } from '$lib/components/ui/label/index.js';
-
- type ButtonVariant = 'destructive' | 'link' | 'default' | 'outline' | 'secondary' | 'ghost';
-
- let {
- title = $bindable('Confirm Action'),
- description = $bindable('Are you sure you want to proceed?'),
- confirmLabel = $bindable('Confirm'),
- cancelLabel = $bindable('Cancel'),
- variant = $bindable<ButtonVariant>('destructive' as ButtonVariant),
- open = $bindable(false),
- onConfirm = $bindable((_force?: boolean) => {}),
- itemType = $bindable<'container' | 'stack' | string | undefined>(undefined),
- isRunning = $bindable<boolean | undefined>(undefined)
- } = $props();
-
- let forceRemoveChecked = $state(false);
-
- const showForceRemoveCheckbox = $derived(itemType === 'container' && isRunning === true);
- const isConfirmDisabled = $derived(showForceRemoveCheckbox && !forceRemoveChecked);
- const finalDescription = $derived(showForceRemoveCheckbox ? `${description} The container is currently running and will be forcefully stopped and removed.` : description);
-
- $effect(() => {
- if (!open || !showForceRemoveCheckbox) {
- forceRemoveChecked = false;
- }
- });
-
- function handleConfirm() {
- onConfirm(showForceRemoveCheckbox && forceRemoveChecked);
- open = false;
- }
-</script>
-
-<Dialog.Root bind:open>
- <Dialog.Content class="max-w-md w-full">
- <Dialog.Header>
- <Dialog.Title class="flex items-center gap-2 text-lg font-semibold">
- <AlertTriangle class="h-5 w-5 text-destructive flex-shrink-0" />
- {title}
- </Dialog.Title>
- </Dialog.Header>
-
- <div class="mt-2 text-sm text-muted-foreground break-words min-w-0">
- {finalDescription}
- </div>
-
- {#if showForceRemoveCheckbox}
- <div class="flex items-center space-x-2 pt-4 pb-2 mt-4 border-t border-border">
- <Checkbox id="force-remove" bind:checked={forceRemoveChecked} />
- <Label for="force-remove" class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Force remove running container</Label>
- </div>
- {/if}
-
- <Dialog.Footer class="mt-6">
- <div class="flex justify-end gap-2">
- <Button variant="outline" onclick={() => (open = false)}>
- {cancelLabel}
- </Button>
- <Button {variant} onclick={handleConfirm} disabled={isConfirmDisabled}>
- {confirmLabel}
- </Button>
- </div>
- </Dialog.Footer>
- </Dialog.Content>
-</Dialog.Root>
diff --git a/src/lib/components/confirm-dialog/confirm-dialog.svelte b/src/lib/components/confirm-dialog/confirm-dialog.svelte
new file mode 100644
index 000000000..9aa450c5c
--- /dev/null
+++ b/src/lib/components/confirm-dialog/confirm-dialog.svelte
@@ -0,0 +1,43 @@
+<script lang="ts">
+ import * as Dialog from '$lib/components/ui/dialog';
+ import { AlertTriangle } from '@lucide/svelte';
+ import { confirmDialogStore } from '.';
+ import Button from '../ui/button/button.svelte';
+</script>
+
+<Dialog.Root bind:open={$confirmDialogStore.open}>
+ <Dialog.Content class="max-w-md w-full">
+ <Dialog.Header>
+ <Dialog.Title class="flex items-center gap-2 text-lg font-semibold">
+ <AlertTriangle class="h-5 w-5 text-destructive flex-shrink-0" />
+ {$confirmDialogStore.title}
+ </Dialog.Title>
+ </Dialog.Header>
+
+ <div class="mt-2 text-sm text-muted-foreground break-words min-w-0">
+ {$confirmDialogStore.message}
+ </div>
+
+ <!-- {#if showForceRemoveCheckbox}
+ <div class="flex items-center space-x-2 pt-4 pb-2 mt-4 border-t border-border">
+ <Checkbox id="force-remove" bind:checked={forceRemoveChecked} />
+ <Label for="force-remove" class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Force remove running container</Label>
+ </div>
+ {/if} -->
+
+ <Dialog.Footer class="mt-6">
+ <div class="flex justify-end gap-2">
+ <Button variant="outline" onclick={() => ($confirmDialogStore.open = false)}>Cancel</Button>
+ <Button
+ variant={$confirmDialogStore.confirm.destructive ? 'destructive' : 'default'}
+ onclick={() => {
+ $confirmDialogStore.confirm.action();
+ $confirmDialogStore.open = false;
+ }}
+ >
+ {$confirmDialogStore.confirm.label}
+ </Button>
+ </div>
+ </Dialog.Footer>
+ </Dialog.Content>
+</Dialog.Root>
diff --git a/src/lib/components/confirm-dialog/index.ts b/src/lib/components/confirm-dialog/index.ts
new file mode 100644
index 000000000..8812a6096
--- /dev/null
+++ b/src/lib/components/confirm-dialog/index.ts
@@ -0,0 +1,39 @@
+import { writable } from 'svelte/store';
+import ConfirmDialog from './confirm-dialog.svelte';
+
+export const confirmDialogStore = writable({
+ open: false,
+ title: '',
+ message: '',
+ confirm: {
+ label: 'Confirm',
+ destructive: false,
+ action: () => {}
+ }
+});
+
+function openConfirmDialog({
+ title,
+ message,
+ confirm
+}: {
+ title: string;
+ message: string;
+ confirm: {
+ label?: string;
+ destructive?: boolean;
+ action: () => void;
+ };
+}) {
+ confirmDialogStore.update((val) => ({
+ open: true,
+ title,
+ message,
+ confirm: {
+ ...val.confirm,
+ ...confirm
+ }
+ }));
+}
+
+export { ConfirmDialog, openConfirmDialog };
diff --git a/src/lib/components/dialogs/user-form-dialog.svelte b/src/lib/components/dialogs/user-form-dialog.svelte
index 11c555892..82cd063c8 100644
--- a/src/lib/components/dialogs/user-form-dialog.svelte
+++ b/src/lib/components/dialogs/user-form-dialog.svelte
@@ -1,5 +1,4 @@
<script lang="ts">
- import { createEventDispatcher } from 'svelte';
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';
@@ -12,15 +11,15 @@
let {
open = $bindable(false),
userToEdit = $bindable<User | null>(null),
- roles = []
+ roles = [],
+ onSubmit = $bindable((_data: { user: Partial<User> & { password?: string }; isEditMode: boolean; userId?: string }) => {})
}: {
open?: boolean;
userToEdit?: User | null;
roles: { id: string; name: string }[];
+ onSubmit?: (data: { user: Partial<User> & { password?: string }; isEditMode: boolean; userId?: string }) => void;
} = $props();
- const dispatch = createEventDispatcher();
-
let username = $state('');
let password = $state('');
let displayName = $state('');
@@ -42,13 +41,13 @@
password = '';
displayName = userToEdit.displayName || '';
email = userToEdit.email || '';
- selectedRole = userToEdit.roles?.[0] || 'user';
+ selectedRole = userToEdit.roles?.[0] || 'admin';
} else {
username = '';
password = '';
displayName = '';
email = '';
- selectedRole = 'user';
+ selectedRole = 'admin';
}
}
});
@@ -70,21 +69,14 @@
}
try {
- dispatch('submit', { user: userData, isEditMode, userId: userToEdit?.id });
+ onSubmit({ user: userData, isEditMode, userId: userToEdit?.id });
+ isSaving = false;
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : 'An unexpected error occurred.';
error = errorMessage;
+ isSaving = false;
}
}
-
- export function resetSavingState() {
- isSaving = false;
- }
-
- export function setSaveError(errorMessage: string) {
- error = errorMessage;
- isSaving = false;
- }
</script>
<Dialog.Root bind:open>
@@ -96,26 +88,26 @@
{/if}
</Dialog.Header>
- <form class="grid gap-4 py-4" onsubmit={preventDefault(handleSubmit)}>
+ <form class="grid gap-4 py-4" onsubmit={preventDefault(handleSubmit)} autocomplete="off">
<div class="grid grid-cols-4 items-center gap-4">
<Label for="username" class="text-right">Username</Label>
- <Input id="username" bind:value={username} required class="col-span-3" disabled={isEditMode} />
+ <Input autocomplete="off" id="username" bind:value={username} required class="col-span-3" disabled={isEditMode} />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="password" class="text-right">Password</Label>
- <Input id="password" type="password" bind:value={password} required={!isEditMode} placeholder={isEditMode ? 'Leave blank to keep current' : 'Required'} class="col-span-3" />
+ <Input autocomplete="off" id="password" type="password" bind:value={password} required={!isEditMode} placeholder={isEditMode ? 'Leave blank to keep current' : 'Required'} class="col-span-3" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="displayName" class="text-right">Display Name</Label>
- <Input id="displayName" bind:value={displayName} class="col-span-3" />
+ <Input autocomplete="off" id="displayName" bind:value={displayName} class="col-span-3" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="email" class="text-right">Email</Label>
- <Input id="email" type="email" bind:value={email} class="col-span-3" />
+ <Input autocomplete="off" id="email" type="email" bind:value={email} class="col-span-3" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="role" class="text-right">Role</Label>
- <Select.Root name="role" type="single" bind:value={selectedRole} disabled={isSaving}>
+ <Select.Root name="role" type="single" bind:value={selectedRole} disabled={true}>
<Select.Trigger class="col-span-3">
<span>{roles.find((r) => r.id === selectedRole)?.name || 'Select a role'}</span>
</Select.Trigger>
diff --git a/src/lib/components/docker/ImageRow.svelte b/src/lib/components/docker/ImageRow.svelte
deleted file mode 100644
index 1888e2b9a..000000000
--- a/src/lib/components/docker/ImageRow.svelte
+++ /dev/null
@@ -1,32 +0,0 @@
-<script lang="ts">
- import { Button } from '$lib/components/ui/button/index.js';
- import { Trash2, Info } from '@lucide/svelte';
-
- interface Props {
- image: {
- id: string;
- repo: string;
- tag: string;
- size: string;
- };
- }
-
- let { image }: Props = $props();
-</script>
-
-<tr class="border-b">
- <td class="py-2">{image.repo}</td>
- <td>{image.tag}</td>
- <td class="font-mono text-xs">{image.id.substring(7, 19)}</td>
- <td>{image.size}</td>
- <td class="py-2">
- <div class="flex gap-2">
- <Button variant="ghost" size="sm" href="/images/{image.id}">
- <Info class="w-4 h-4" />
- </Button>
- <Button variant="destructive" size="sm">
- <Trash2 class="w-4 h-4" />
- </Button>
- </div>
- </td>
-</tr>
diff --git a/src/lib/components/table-cells/user-email-cell.svelte b/src/lib/components/table-cells/user-email-cell.svelte
deleted file mode 100644
index ddb591729..000000000
--- a/src/lib/components/table-cells/user-email-cell.svelte
+++ /dev/null
@@ -1,13 +0,0 @@
-<script lang="ts">
- import { Mail } from '@lucide/svelte';
- interface Props {
- email?: string;
- }
-
- let { email = '' }: Props = $props();
-</script>
-
-<div class="flex items-center gap-1.5">
- <Mail class="h-3.5 w-3.5 text-muted-foreground" />
- <span>{email || 'No email'}</span>
-</div>
diff --git a/src/lib/components/table-cells/user-name-cell.svelte b/src/lib/components/table-cells/user-name-cell.svelte
deleted file mode 100644
index dadf8bd66..000000000
--- a/src/lib/components/table-cells/user-name-cell.svelte
+++ /dev/null
@@ -1,19 +0,0 @@
-<script lang="ts">
- import { User } from '@lucide/svelte';
- interface Props {
- displayName?: string;
- username?: string;
- }
-
- let { displayName = '', username = '' }: Props = $props();
-</script>
-
-<div class="flex items-start gap-2">
- <div class="bg-primary/10 rounded-full p-2 flex-shrink-0">
- <User class="h-4 w-4 text-primary" />
- </div>
- <div>
- <div class="font-medium">{displayName || username}</div>
- <div class="text-xs text-muted-foreground">{username}</div>
- </div>
-</div>
diff --git a/src/lib/components/table-cells/user-roles.cell.svelte b/src/lib/components/table-cells/user-roles.cell.svelte
deleted file mode 100644
index 631c055f4..000000000
--- a/src/lib/components/table-cells/user-roles.cell.svelte
+++ /dev/null
@@ -1,15 +0,0 @@
-<script lang="ts">
- import StatusBadge from '../badges/status-badge.svelte';
- interface Props {
- roles?: string[];
- }
-
- let { roles = [] }: Props = $props();
-</script>
-
-<div class="flex flex-wrap">
- {#each roles as role (role)}
- {@const isAdmin = role === 'admin'}
- <StatusBadge text={isAdmin ? 'Admin' : 'User'} variant={isAdmin ? 'amber' : 'blue'} />
- {/each}
-</div>
diff --git a/src/lib/components/table-cells/user-table-actions.svelte b/src/lib/components/table-cells/user-table-actions.svelte
deleted file mode 100644
index ac7ffd0de..000000000
--- a/src/lib/components/table-cells/user-table-actions.svelte
+++ /dev/null
@@ -1,45 +0,0 @@
-<script lang="ts">
- import { Ellipsis, Pencil, UserX } from '@lucide/svelte';
- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
- import { Button } from '$lib/components/ui/button/index.js';
- import type { User } from '$lib/types/user.type';
-
- interface Props {
- userId: string;
- username: string;
- user: User;
- onRemove: (userId: string, username: string) => void;
- onEdit: (user: User) => void;
- }
-
- let { userId, user, username, onRemove, onEdit }: Props = $props();
-
- function handleRemove() {
- onRemove(userId, username);
- }
-
- function handleEdit() {
- onEdit(user);
- }
-</script>
-
-<DropdownMenu.Root>
- <DropdownMenu.Trigger>
- <Button variant="ghost" size="icon" class="h-8 w-8">
- <Ellipsis class="h-4 w-4" />
- <span class="sr-only">Open menu</span>
- </Button>
- </DropdownMenu.Trigger>
- <DropdownMenu.Content align="end">
- <DropdownMenu.Group>
- <DropdownMenu.Item onclick={handleEdit}>
- <Pencil class="h-4 w-4" />
- Edit
- </DropdownMenu.Item>
- <DropdownMenu.Item onclick={handleRemove} class="text-red-500 focus:!text-red-700">
- <UserX class="h-4 w-4" />
- Remove User
- </DropdownMenu.Item>
- </DropdownMenu.Group>
- </DropdownMenu.Content>
-</DropdownMenu.Root>
diff --git a/src/lib/components/universal-modal.svelte b/src/lib/components/universal-modal.svelte
deleted file mode 100644
index fa66287e2..000000000
--- a/src/lib/components/universal-modal.svelte
+++ /dev/null
@@ -1,81 +0,0 @@
-<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();
-
- 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/universal-table.svelte b/src/lib/components/universal-table.svelte
index d86befba2..a524770d1 100644
--- a/src/lib/components/universal-table.svelte
+++ b/src/lib/components/universal-table.svelte
@@ -11,8 +11,23 @@
import { ChevronDown } from '@lucide/svelte';
import { cn } from '$lib/utils';
import type { UniversalTableProps } from '$lib/types/table-types';
+ import type { Snippet } from 'svelte';
+
+ let {
+ data,
+ columns,
+ idKey,
+ features = {},
+ display = {},
+ pagination = {},
+ sort = {},
+ selectedIds = $bindable<string[]>([]),
+ rows
+ }: UniversalTableProps<TData> & {
+ idKey?: keyof TData;
+ rows?: Snippet<[{ item: TData }]>;
+ } = $props();
- let { data, columns, idKey, features = {}, display = {}, pagination = {}, sort = {}, selectedIds = $bindable<string[]>([]) }: UniversalTableProps<TData> & { idKey?: keyof TData } = $props();
let { sorting: enableSorting = true, filtering: enableFiltering = true, selection: enableSelection = true } = features;
let { pageSize: initialPageSize = 10, pageSizeOptions = [10, 20, 50, 100], itemsPerPageLabel = 'Items per page' } = pagination;
let { filterPlaceholder = 'Search...', noResultsMessage = 'No results found', isDashboardTable = false, class: className = '' } = display;
@@ -49,7 +64,7 @@
},
columns,
getRowId: idKey
- ? (originalRow: TData, index: number, parent?: RowData) => {
+ ? (originalRow: TData, _index: number, _parent?: RowData) => {
return String(originalRow[idKey]);
}
: undefined,
@@ -180,11 +195,16 @@
/>
</Table.Cell>
{/if}
- {#each row.getVisibleCells() as cell (cell.id)}
- <Table.Cell>
- <FlexRender content={cell.column.columnDef.cell} context={cell.getContext()} />
- </Table.Cell>
- {/each}
+
+ {#if rows}
+ {@render rows({ item: row.original })}
+ {:else}
+ {#each row.getVisibleCells() as cell (cell.id)}
+ <Table.Cell>
+ <FlexRender content={cell.column.columnDef.cell} context={cell.getContext()} />
+ </Table.Cell>
+ {/each}
+ {/if}
</Table.Row>
{/each}
{:else}
diff --git a/src/lib/components/yaml-editor.svelte b/src/lib/components/yaml-editor.svelte
index a1c9f8d67..2b5e5ee03 100644
--- a/src/lib/components/yaml-editor.svelte
+++ b/src/lib/components/yaml-editor.svelte
@@ -8,9 +8,8 @@
import type { EditorView } from 'codemirror';
// Make value bindable
- let { value = $bindable(''), height = '400px', placeholder = 'Enter YAML content', readOnly = false } = $props();
+ let { value = $bindable(''), placeholder = 'Enter YAML content', readOnly = false } = $props();
- // Reference to the CodeMirror instance (for debugging if needed)
let editorView: EditorView;
// YAML linting function
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 0bd4ecf30..ad68b06b2 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -1 +1,2 @@
export const isDev = process.env.NODE_ENV === 'development';
+export const isTest = process.env.APP_ENV === 'TEST';
diff --git a/src/lib/services/api/api-service.ts b/src/lib/services/api/api-service.ts
new file mode 100644
index 000000000..363812ff4
--- /dev/null
+++ b/src/lib/services/api/api-service.ts
@@ -0,0 +1,13 @@
+import axios from 'axios';
+
+abstract class BaseAPIService {
+ api = axios.create({
+ withCredentials: true
+ });
+
+ constructor() {
+ this.api.defaults.baseURL = '/api';
+ }
+}
+
+export default BaseAPIService;
diff --git a/src/lib/services/api/container-api-service.ts b/src/lib/services/api/container-api-service.ts
new file mode 100644
index 000000000..07f928315
--- /dev/null
+++ b/src/lib/services/api/container-api-service.ts
@@ -0,0 +1,49 @@
+import type { ContainerConfig } from '$lib/types/docker';
+import BaseAPIService from './api-service';
+
+export default class ContainerAPIService extends BaseAPIService {
+ async start(id: string) {
+ const res = await this.api.post(`/containers/${id}/start`);
+ return res.data;
+ }
+
+ async stop(id: string) {
+ const res = await this.api.post(`/containers/${id}/stop`);
+ return res.data;
+ }
+
+ async restart(id: string) {
+ const res = await this.api.post(`/containers/${id}/restart`);
+ return res.data;
+ }
+
+ async remove(id: string) {
+ const res = await this.api.delete(`/containers/${id}/remove`);
+ return res.data;
+ }
+
+ async pull(id: string) {
+ const res = await this.api.post(`/containers/${id}/pull`);
+ return res.data;
+ }
+
+ async startAll() {
+ const res = await this.api.post(`/containers/start-all`);
+ return res.data;
+ }
+
+ async stopAll() {
+ const res = await this.api.post(`/containers/stop-all`);
+ return res.data;
+ }
+
+ async create(config: ContainerConfig) {
+ const res = await this.api.post('/containers', config);
+ return res.data;
+ }
+
+ async list() {
+ const res = await this.api.get('');
+ return res.data;
+ }
+}
diff --git a/src/lib/services/api/image-api-service.ts b/src/lib/services/api/image-api-service.ts
new file mode 100644
index 000000000..cd6b81280
--- /dev/null
+++ b/src/lib/services/api/image-api-service.ts
@@ -0,0 +1,24 @@
+import BaseAPIService from './api-service';
+
+export default class ImageAPIService extends BaseAPIService {
+ async remove(id: string) {
+ const res = await this.api.delete(`/images/${id}`);
+ return res.data;
+ }
+
+ async pull(imageRef: string, tag: string) {
+ const encodedImageRef = encodeURIComponent(imageRef);
+ const res = await this.api.post(`/images/pull/${encodedImageRef}`, { tag });
+ return res.data;
+ }
+
+ async prune() {
+ const res = await this.api.post(`/images/prune`);
+ return res.data;
+ }
+
+ async list() {
+ const res = await this.api.get('');
+ return res.data;
+ }
+}
diff --git a/src/lib/services/api/network-api-service.ts b/src/lib/services/api/network-api-service.ts
new file mode 100644
index 000000000..6dfdd452c
--- /dev/null
+++ b/src/lib/services/api/network-api-service.ts
@@ -0,0 +1,14 @@
+import type { NetworkCreateOptions } from 'dockerode';
+import BaseAPIService from './api-service';
+
+export default class NetworkAPIService extends BaseAPIService {
+ async remove(id: string) {
+ const res = await this.api.delete(`/networks/${id}`);
+ return res.data;
+ }
+
+ async create(options: NetworkCreateOptions) {
+ const res = await this.api.post(`/networks/create`, options);
+ return res.data;
+ }
+}
diff --git a/src/lib/services/api/stack-api-service.ts b/src/lib/services/api/stack-api-service.ts
new file mode 100644
index 000000000..e773032b8
--- /dev/null
+++ b/src/lib/services/api/stack-api-service.ts
@@ -0,0 +1,63 @@
+import BaseAPIService from './api-service';
+
+export default class StackAPIService extends BaseAPIService {
+ async start(id: string) {
+ const res = await this.api.post(`/stacks/${id}/start`);
+ return res.data;
+ }
+
+ async stop(id: string) {
+ const res = await this.api.post(`/stacks/${id}/stop`);
+ return res.data;
+ }
+
+ async restart(id: string) {
+ const res = await this.api.post(`/stacks/${id}/restart`);
+ return res.data;
+ }
+
+ async remove(id: string) {
+ const res = await this.api.delete(`/stacks/${id}/remove`);
+ return res.data;
+ }
+
+ async redeploy(id: string) {
+ const res = await this.api.post(`/stacks/${id}/redeploy`);
+ return res.data;
+ }
+
+ async pull(id: string) {
+ const res = await this.api.post(`/stacks/${id}/pull`);
+ return res.data;
+ }
+
+ async import(id: string, name: string) {
+ const res = await this.api.post('/stacks/import', {
+ stackId: id,
+ stackName: name || undefined
+ });
+ return res.data;
+ }
+
+ async save(stackId: string, name: string, composeContent: string, autoUpdate: boolean) {
+ const res = await this.api.put(`/stacks/${stackId}`, {
+ name,
+ composeContent,
+ autoUpdate
+ });
+ return res.data;
+ }
+
+ async create(name: string, content: string) {
+ const res = await this.api.post('/stacks/create', {
+ name,
+ composeContent: content
+ });
+ return res.data;
+ }
+
+ async list() {
+ const res = await this.api.get('');
+ return res.data;
+ }
+}
diff --git a/src/lib/services/api/system-api-service.ts b/src/lib/services/api/system-api-service.ts
new file mode 100644
index 000000000..a37744d01
--- /dev/null
+++ b/src/lib/services/api/system-api-service.ts
@@ -0,0 +1,14 @@
+import type { PruneType } from '$lib/types/actions.type';
+import BaseAPIService from './api-service';
+
+export default class SystemAPIService extends BaseAPIService {
+ async prune(types: PruneType[]) {
+ if (!types || types.length === 0) {
+ throw new Error('No prune types specified');
+ }
+
+ const typesParam = types.join(',');
+ const res = await this.api.post(`/system/prune?types=${typesParam}`);
+ return res.data;
+ }
+}
diff --git a/src/lib/services/api/user-api-service.ts b/src/lib/services/api/user-api-service.ts
new file mode 100644
index 000000000..c36c0313b
--- /dev/null
+++ b/src/lib/services/api/user-api-service.ts
@@ -0,0 +1,17 @@
+import type { User } from '$lib/types/user.type';
+import BaseAPIService from './api-service';
+
+export default class UserAPIService extends BaseAPIService {
+ async update(id: string, user: User) {
+ const res = await this.api.put(`/users/${id}`, user);
+ return res.data;
+ }
+ async create(user: User) {
+ const res = await this.api.post(`/users`, user);
+ return res.data;
+ }
+ async delete(id: string) {
+ const res = await this.api.delete(`/users/${id}`);
+ return res.data;
+ }
+}
diff --git a/src/lib/services/api/volume-api-service.ts b/src/lib/services/api/volume-api-service.ts
new file mode 100644
index 000000000..9e9bccf1f
--- /dev/null
+++ b/src/lib/services/api/volume-api-service.ts
@@ -0,0 +1,14 @@
+import type { VolumeCreateOptions } from 'dockerode';
+import BaseAPIService from './api-service';
+
+export default class VolumeAPIService extends BaseAPIService {
+ async remove(id: string) {
+ const res = await this.api.delete(`/volumes/${id}`);
+ return res.data;
+ }
+
+ async create(volume: VolumeCreateOptions) {
+ const res = await this.api.post('/volumes', volume);
+ return res.data;
+ }
+}
diff --git a/src/lib/services/paths-service.ts b/src/lib/services/paths-service.ts
index 09ee9580e..5c13ee4a9 100644
--- a/src/lib/services/paths-service.ts
+++ b/src/lib/services/paths-service.ts
@@ -1,9 +1,9 @@
-import path from 'node:path';
+import * as path from 'path';
import fs from 'node:fs/promises';
-import { isDev } from '$lib/constants';
+import { isDev, isTest } from '$lib/constants';
// Configure paths based on environment
-export const BASE_PATH = isDev ? path.resolve(process.cwd(), '.dev-data') : '/app/data';
+export const BASE_PATH = isTest ? path.resolve(process.cwd(), '.test-data') : isDev ? path.resolve(process.cwd(), '.dev-data') : '/app/data';
export const SETTINGS_FILE = path.join(BASE_PATH, 'app-settings.json');
export const SETTINGS_DIR = path.join(BASE_PATH, 'settings');
diff --git a/src/lib/services/session-service.ts b/src/lib/services/session-service.ts
index eb95142d7..9f57810b3 100644
--- a/src/lib/services/session-service.ts
+++ b/src/lib/services/session-service.ts
@@ -19,7 +19,7 @@ export async function createSession(userId: string, username: string): Promise<s
// Get session timeout from settings
const { auth } = await import('$lib/services/settings-service').then((m) => m.getSettings());
- const sessionTimeout = auth?.sessionTimeout ?? 60; // minutes
+ const sessionTimeout = auth?.sessionTimeout ?? 1440; // 24 hours in minutes
const expiryTime = Date.now() + sessionTimeout * 60 * 1000;
// Create session data with explicit expiry time
@@ -64,12 +64,12 @@ export async function getSession(sessionId: string): Promise<UserSession | null>
// Get current settings for session timeout
const { auth } = await import('$lib/services/settings-service').then((m) => m.getSettings());
- const sessionTimeout = auth?.sessionTimeout ?? 60; // minutes
+ const sessionTimeout = auth?.sessionTimeout ?? 1440; // 24 hours in minutes
const maxAge = sessionTimeout * 60 * 1000; // Convert to milliseconds
// Check if session has expired - first check explicit expiry if it exists
if (sessionData.expires && Date.now() > sessionData.expires) {
- // Session explicitly expired
+ console.log('Session expired (explicit expiry):', sessionId);
sessions.delete(sessionId);
await removeSessionFromDisk(sessionId);
return null;
@@ -77,22 +77,24 @@ export async function getSession(sessionId: string): Promise<UserSession | null>
// Fall back to lastAccessed-based expiry if no explicit expires field
if (!sessionData.expires && Date.now() - sessionData.lastAccessed > maxAge) {
- // Session expired based on activity
+ console.log('Session expired (activity timeout):', sessionId);
sessions.delete(sessionId);
await removeSessionFromDisk(sessionId);
return null;
}
- // Update last accessed time and possibly extend expiry
+ // Session is valid - update last accessed time and extend expiry
sessionData.lastAccessed = Date.now();
- // Update expiry based on current settings (sliding expiration)
+ // Always update the expiry time on each access (sliding expiration)
sessionData.expires = Date.now() + maxAge;
// Re-encrypt with updated timestamp and store
const updatedEncrypted = await encryptSessionData(sessionData);
sessions.set(sessionId, updatedEncrypted);
- await saveSessionToDisk(sessionId, updatedEncrypted);
+
+ // Save to disk asynchronously
+ saveSessionToDisk(sessionId, updatedEncrypted).catch((err) => console.error('Failed to save session to disk:', err));
return sessionData;
} catch (error) {
diff --git a/src/lib/types/actions.type.ts b/src/lib/types/actions.type.ts
new file mode 100644
index 000000000..5fcdf67e1
--- /dev/null
+++ b/src/lib/types/actions.type.ts
@@ -0,0 +1,3 @@
+export type StackActions = 'start' | 'stop' | 'restart' | 'redeploy' | 'import' | 'destroy' | 'pull';
+export type ContainerActions = 'start' | 'stop' | 'restart' | 'pull' | 'remove';
+export type PruneType = 'containers' | 'images' | 'networks' | 'volumes';
diff --git a/src/lib/types/api-response.type.ts b/src/lib/types/api-response.type.ts
deleted file mode 100644
index 9455ab638..000000000
--- a/src/lib/types/api-response.type.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export type ApiResponse = {
- success?: boolean;
- message?: string;
- error?: string;
- [key: string]: unknown;
-};
diff --git a/src/lib/types/loading-states.type.ts b/src/lib/types/loading-states.type.ts
new file mode 100644
index 000000000..fc1626860
--- /dev/null
+++ b/src/lib/types/loading-states.type.ts
@@ -0,0 +1,9 @@
+export type LoadingStates = {
+ start?: boolean;
+ stop?: boolean;
+ restart?: boolean;
+ pull?: boolean;
+ deploy?: boolean;
+ redeploy?: boolean;
+ remove?: boolean;
+};
diff --git a/src/lib/types/table-columns/user-table-columns.ts b/src/lib/types/table-columns/user-table-columns.ts
deleted file mode 100644
index f403b0e24..000000000
--- a/src/lib/types/table-columns/user-table-columns.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import type { ColumnDef } from '@tanstack/table-core';
-import type { User } from '$lib/types/user.type';
-import { renderComponent } from '$lib/components/ui/data-table/index.js';
-import UserCell from '$lib/components/table-cells/user-name-cell.svelte';
-import EmailCell from '$lib/components/table-cells/user-email-cell.svelte';
-import RolesCell from '$lib/components/table-cells/user-roles.cell.svelte';
-import UserTableActions from '$lib/components/table-cells/user-table-actions.svelte';
-
-// Column definitions for the user management table
-export const userTableColumns = (onRemoveUser: (userId: string, username: string) => void, onEdit: (user: User) => void): ColumnDef<User>[] => [
- {
- id: 'user',
- header: 'User',
- accessorFn: (row) => row.username,
- cell: ({ row }) => {
- return renderComponent(UserCell, {
- displayName: row.original.displayName,
- username: row.original.username
- });
- }
- },
- {
- id: 'email',
- header: 'Email',
- accessorKey: 'email',
- cell: ({ row }) => {
- return renderComponent(EmailCell, {
- email: row.original.email
- });
- }
- },
- {
- id: 'roles',
- header: 'Roles',
- accessorFn: (row) => row.roles.join(', '),
- cell: ({ row }) => {
- return renderComponent(RolesCell, {
- roles: row.original.roles
- });
- }
- },
- {
- id: 'actions',
- header: '',
- cell: ({ row }) => {
- return renderComponent(UserTableActions, {
- userId: row.original.id,
- username: row.original.username,
- user: row.original,
- onRemove: onRemoveUser,
- onEdit: onEdit
- });
- },
- enableSorting: false
- }
-];
diff --git a/src/lib/utils.ts b/src/lib/utils.ts
index 1d9ab947e..404e855e7 100644
--- a/src/lib/utils.ts
+++ b/src/lib/utils.ts
@@ -28,11 +28,6 @@ export function formatBytes(bytes: number, decimals = 2): string {
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 formatDate(dateString: string | undefined | null): string {
if (!dateString) return 'Unknown';
try {
diff --git a/src/lib/utils/api.util.ts b/src/lib/utils/api.util.ts
new file mode 100644
index 000000000..615c6369c
--- /dev/null
+++ b/src/lib/utils/api.util.ts
@@ -0,0 +1,22 @@
+import type { Result } from './try-catch';
+import { toast } from 'svelte-sonner';
+
+/**
+ * Handles the result of an API call, showing errors or executing a success callback.
+ * Optionally sets a loading state to false on error.
+ * @param result The result object from a try-catch utility.
+ * @param errorMessage The base error message for logging and toast if an error occurs.
+ * @param setLoadingState Optional setter function to set a boolean loading state to false specifically on error.
+ * @param onSuccess Optional callback function to execute if there is no error. Receives the data from the result.
+ */
+export function handleApiReponse<T>(result: Result<T, Error>, message: string, setLoadingState: (value: boolean) => void, onSuccess: (data: T) => void) {
+ if (result.error) {
+ console.error(message + ':', result.error);
+ toast.error(`${message}: ${result.error.message}`);
+ setLoadingState(false);
+ return;
+ } else if (result.data) {
+ onSuccess(result.data);
+ setLoadingState(false);
+ }
+}
diff --git a/src/lib/utils/string.utils.ts b/src/lib/utils/string.utils.ts
new file mode 100644
index 000000000..a1ea71ec2
--- /dev/null
+++ b/src/lib/utils/string.utils.ts
@@ -0,0 +1,8 @@
+export function shortId(id: string): string {
+ return id?.substring(0, 12) || '';
+}
+
+export const capitalizeFirstLetter = (text: string) => {
+ if (!text) return '';
+ return text.charAt(0).toUpperCase() + text.slice(1);
+};
diff --git a/src/lib/utils/try-catch.ts b/src/lib/utils/try-catch.ts
new file mode 100644
index 000000000..5668b6773
--- /dev/null
+++ b/src/lib/utils/try-catch.ts
@@ -0,0 +1,21 @@
+type Success<T> = {
+ data: T;
+ error: null;
+};
+
+type Failure<E> = {
+ data: null;
+ error: E;
+};
+
+export type Result<T, E = Error> = Success<T> | Failure<E>;
+
+// Main wrapper function
+export async function tryCatch<T, E = Error>(promise: Promise<T>): Promise<Result<T, E>> {
+ try {
+ const data = await promise;
+ return { data, error: null };
+ } catch (error) {
+ return { data: null, error: error as E };
+ }
+}
diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts
index 6a5075bb3..0d1343dfd 100644
--- a/src/routes/+layout.server.ts
+++ b/src/routes/+layout.server.ts
@@ -4,7 +4,6 @@ import AppConfigService from '$lib/services/app-config-service';
import type { AppVersionInformation } from '$lib/types/application-configuration';
import type { LayoutServerLoad } from './$types';
-// Cache the version information
let versionInformation: AppVersionInformation;
let versionInformationLastUpdated: number;
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index 54cc3a34e..34e4caf17 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -1,32 +1,34 @@
-<!-- @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, page } from '$app/state';
+ import ConfirmDialog from '$lib/components/confirm-dialog/confirm-dialog.svelte';
let { children, data } = $props();
const versionInformation = data.versionInformation;
- const user = $derived(data.user); // Access the user from data
-
- const isNavigating = $derived(navigating !== null);
- const isAuthenticated = $derived(!!user); // Check if user exists
+ const user = $derived(data.user);
+ const isNavigating = $derived(navigating.type !== null);
+ const isAuthenticated = $derived(!!user);
const isOnboardingPage = $derived(page.url.pathname.startsWith('/onboarding'));
- // Only show sidebar when authenticated AND not in onboarding
- const showSidebar = $derived(isAuthenticated && !isOnboardingPage);
+ const isLoginPage = $derived(page.url.pathname === '/login' || page.url.pathname.startsWith('/auth/login') || page.url.pathname === '/auth' || page.url.pathname.includes('/login'));
+ const showSidebar = $derived(isAuthenticated && !isOnboardingPage && !isLoginPage);
</script>
<svelte:head><title>Arcane</title></svelte:head>
<ModeWatcher />
<Toaster />
+<ConfirmDialog />
-<!-- Apply a loading state to the page during navigation -->
+<!-- Loading Indicator -->
{#if isNavigating}
- <!-- add a loading indicator here -->
+ <div class="fixed top-0 left-0 right-0 h-2 z-50">
+ <div class="h-full bg-primary animate-pulse"></div>
+ </div>
{/if}
<div class="flex min-h-screen bg-background">
diff --git a/src/routes/+page.server.ts b/src/routes/+page.server.ts
index 25b4e1d9a..e8c34e719 100644
--- a/src/routes/+page.server.ts
+++ b/src/routes/+page.server.ts
@@ -1,9 +1,9 @@
import type { PageServerLoad } from './$types';
import { listContainers } from '$lib/services/docker/container-service';
import { getDockerInfo } from '$lib/services/docker/core';
-import { listImages } from '$lib/services/docker/image-service';
+import { isImageInUse, listImages } from '$lib/services/docker/image-service';
import { getSettings } from '$lib/services/settings-service';
-import type { ServiceContainer, ServiceImage } from '$lib/types/docker';
+import type { EnhancedImageInfo, ServiceContainer, ServiceImage } from '$lib/types/docker';
type DockerInfoType = Awaited<ReturnType<typeof getDockerInfo>>;
type SettingsType = NonNullable<Awaited<ReturnType<typeof getSettings>>>;
@@ -41,13 +41,22 @@ export const load: PageServerLoad = async (): Promise<DashboardData> => {
})
]);
- // Check if the primary connection failed
+ const enhancedImages = await Promise.all(
+ images.map(async (image): Promise<EnhancedImageInfo> => {
+ const inUse = await isImageInUse(image.id);
+ return {
+ ...image,
+ inUse
+ };
+ })
+ );
+
if (!dockerInfo) {
return {
dockerInfo: null,
containers: [],
- images: [],
- settings: settings ? { pruneMode: settings.pruneMode } : null, // Still return settings if available
+ images: [] as EnhancedImageInfo[],
+ settings: settings ? { pruneMode: settings.pruneMode } : null,
error: 'Failed to connect to Docker Engine. Please check settings and ensure Docker is running.'
};
}
@@ -55,8 +64,8 @@ export const load: PageServerLoad = async (): Promise<DashboardData> => {
return {
dockerInfo,
containers,
- images,
- settings: settings ? { pruneMode: settings.pruneMode } : null // Pass only pruneMode
+ images: enhancedImages,
+ settings: settings ? { pruneMode: settings.pruneMode } : null
};
} catch (err: any) {
console.error('Dashboard: Unexpected error loading data:', err);
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index 9baf096f9..92b3d508b 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -3,131 +3,110 @@
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
import UniversalTable from '$lib/components/universal-table.svelte';
- import { dashboardContainerColumns, dashboardImageColumns } from './columns';
import { AlertCircle, Box, HardDrive, Cpu, MemoryStick, ArrowRight, PlayCircle, StopCircle, Trash2, Settings, RefreshCw, Loader2 } from '@lucide/svelte';
import * as Alert from '$lib/components/ui/alert/index.js';
import { Progress } from '$lib/components/ui/progress/index.js';
+ import { capitalizeFirstLetter } from '$lib/utils/string.utils';
import { formatBytes } from '$lib/utils';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import { invalidateAll } from '$app/navigation';
import { toast } from 'svelte-sonner';
import PruneConfirmationDialog from '$lib/components/dialogs/prune-confirmation-dialog.svelte';
+ import * as Table from '$lib/components/ui/table';
+ import { statusVariantMap } from '$lib/types/statuses';
+ import { shortId } from '$lib/utils/string.utils';
+ import { handleApiReponse } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import ContainerAPIService from '$lib/services/api/container-api-service';
+ import SystemAPIService from '$lib/services/api/system-api-service';
+ import type { EnhancedImageInfo } from '$lib/types/docker';
let { data }: { data: PageData } = $props();
- let dockerInfo = $state(data.dockerInfo);
- let containers = $state(data.containers || []);
- let images = $state(data.images || []);
- let settings = $state(data.settings);
- let error = $state(data.error);
+ const containerApi = new ContainerAPIService();
+ const systemApi = new SystemAPIService();
- let isRefreshing = $state(false);
- let isStartingAll = $state(false);
- let isStoppingAll = $state(false);
- let isPruning = $state(false);
- let isPruneDialogOpen = $state(false);
+ let dashboardStates = $state({
+ dockerInfo: data.dockerInfo,
+ containers: data.containers,
+ images: data.images as EnhancedImageInfo[],
+ settings: data.settings,
+ error: data.error,
+ isPruneDialogOpen: false
+ });
+
+ let isLoading = $state({
+ starting: false,
+ stopping: false,
+ refreshing: false,
+ pruning: false
+ });
- const runningContainers = $derived(containers?.filter((c) => c.state === 'running').length ?? 0);
- const stoppedContainers = $derived(containers?.filter((c) => c.state === 'exited').length ?? 0);
- const totalImageSize = $derived(images?.reduce((sum, image) => sum + (image.size || 0), 0) ?? 0);
+ const runningContainers = $derived(dashboardStates.containers?.filter((c) => c.state === 'running').length ?? 0);
+ const stoppedContainers = $derived(dashboardStates.containers?.filter((c) => c.state === 'exited').length ?? 0);
+ const totalImageSize = $derived(dashboardStates.images?.reduce((sum, image) => sum + (image.size || 0), 0) ?? 0);
$effect(() => {
- dockerInfo = data.dockerInfo;
- containers = data.containers;
- images = data.images;
- settings = data.settings;
- error = data.error;
+ dashboardStates.dockerInfo = data.dockerInfo;
+ dashboardStates.containers = data.containers;
+ dashboardStates.images = data.images as EnhancedImageInfo[];
+ dashboardStates.settings = data.settings;
+ dashboardStates.error = data.error;
});
async function refreshData() {
- if (isRefreshing) return;
- isRefreshing = true;
+ if (isLoading.refreshing) return;
+ isLoading.refreshing = true;
try {
await invalidateAll();
} catch (err) {
console.error('Error during dashboard refresh:', err);
- error = 'Failed to refresh dashboard data.';
+ dashboardStates.error = 'Failed to refresh dashboard data.';
} finally {
- isRefreshing = false;
+ isLoading.refreshing = false;
}
}
async function handleStartAll() {
- if (isStartingAll || !dockerInfo || stoppedContainers === 0) return;
- isStartingAll = true;
- try {
- const response = await fetch('/api/containers/start-all', { method: 'POST' });
- const result = await response.json();
-
- if (!response.ok) {
- throw new Error(result.message || 'Failed to start containers');
+ if (isLoading.starting || !dashboardStates.dockerInfo || stoppedContainers === 0) return;
+ handleApiReponse(
+ await tryCatch(containerApi.startAll()),
+ `Failed to Start All Containers`,
+ (value) => (isLoading.starting = value),
+ async () => {
+ toast.success(`All Containers Started Successfully.`);
+ await invalidateAll();
}
-
- toast.success(result.message || `Successfully started ${result.count} container(s).`);
- await invalidateAll();
- } catch (err: any) {
- console.error('Error starting all containers:', err);
- toast.error(err.message || 'An error occurred while starting containers.');
- } finally {
- isStartingAll = false;
- }
+ );
}
async function handleStopAll() {
- if (isStoppingAll || !dockerInfo || runningContainers === 0) return;
- isStoppingAll = true;
- try {
- const response = await fetch('/api/containers/stop-all', { method: 'POST' });
- const result = await response.json();
-
- if (!response.ok) {
- throw new Error(result.message || 'Failed to stop containers');
+ if (isLoading.stopping || !dashboardStates.dockerInfo || runningContainers === 0) return;
+ handleApiReponse(
+ await tryCatch(containerApi.stopAll()),
+ `Failed to Stop All Running Containers`,
+ (value) => (isLoading.starting = value),
+ async () => {
+ toast.success(`All Containers Stopped Successfully.`);
+ await invalidateAll();
}
-
- toast.success(result.message || `Successfully stopped ${result.count} container(s).`);
- await invalidateAll();
- } catch (err: any) {
- console.error('Error stopping all containers:', err);
- toast.error(err.message || 'An error occurred while stopping containers.');
- } finally {
- isStoppingAll = false;
- }
- }
-
- function openPruneDialog() {
- if (!dockerInfo || isStartingAll || isStoppingAll || isPruning) return;
- isPruneDialogOpen = true;
+ );
}
async function confirmPrune(selectedTypes: string[]) {
- if (isPruning || selectedTypes.length === 0) return;
-
- console.log(`Attempting to prune types: ${selectedTypes.join(', ')}`);
- isPruning = true;
- isPruneDialogOpen = false;
-
- try {
- const apiUrl = `/api/system/prune?types=${encodeURIComponent(selectedTypes.join(','))}`;
- const response = await fetch(apiUrl, { method: 'POST' });
- const result = await response.json();
-
- if (!response.ok && !result.success) {
- throw new Error(result.message || `Failed to prune system (status ${response.status})`);
+ if (isLoading.pruning || selectedTypes.length === 0) return;
+
+ handleApiReponse(
+ await tryCatch(systemApi.prune(['containers', 'images'])),
+ `Failed to Prune ${selectedTypes}`,
+ (value) => (isLoading.pruning = value),
+ async () => {
+ dashboardStates.isPruneDialogOpen = false;
+ const formattedTypes = selectedTypes.map((type) => capitalizeFirstLetter(type)).join(', ');
+ toast.success(`${formattedTypes} ${selectedTypes.length > 1 ? 'were' : 'was'} pruned successfully.`);
+ await invalidateAll();
}
-
- if (!result.success && result.message) {
- toast.warning(result.message);
- } else {
- toast.success(result.message || 'System prune completed.');
- }
-
- await invalidateAll();
- } catch (err: any) {
- console.error('Error pruning system:', err);
- toast.error(err.message || 'An error occurred while pruning the system.');
- } finally {
- isPruning = false;
- }
+ );
}
</script>
@@ -137,8 +116,8 @@
<h1 class="text-3xl font-bold tracking-tight">Dashboard</h1>
<p class="text-sm text-muted-foreground mt-1">Overview of your Docker environment</p>
</div>
- <Button variant="outline" size="sm" class="h-9" onclick={refreshData} disabled={isRefreshing || isStartingAll || isStoppingAll || isPruning}>
- {#if isRefreshing}
+ <Button variant="outline" size="sm" class="h-9" onclick={refreshData} disabled={isLoading.refreshing || isLoading.starting || isLoading.stopping || isLoading.pruning}>
+ {#if isLoading.refreshing}
<Loader2 class="h-4 w-4 mr-2 animate-spin" />
{:else}
<RefreshCw class="h-4 w-4 mr-2" />
@@ -147,12 +126,12 @@
</Button>
</div>
- {#if error}
+ {#if dashboardStates.error}
<Alert.Root variant="destructive">
<AlertCircle class="h-4 w-4 mr-2" />
<Alert.Title>Connection Error</Alert.Title>
<Alert.Description>
- {error} Please check your Docker connection in
+ {dashboardStates.error} Please check your Docker connection in
<a href="/settings" class="underline">Settings</a>.
</Alert.Description>
</Alert.Root>
@@ -172,7 +151,7 @@
<div class="mt-1">
<p class="text-2xl font-bold">
{runningContainers}
- <span class="text-xs font-normal text-muted-foreground ml-1">/ {containers?.length || 0}</span>
+ <span class="text-xs font-normal text-muted-foreground ml-1">/ {dashboardStates.containers?.length || 0}</span>
</p>
</div>
</div>
@@ -180,8 +159,8 @@
<Box class="h-5 w-5 text-green-500" />
</div>
</div>
- {#if containers?.length}
- <Progress value={(runningContainers / containers.length) * 100} class="h-1 mt-4" />
+ {#if dashboardStates.containers?.length}
+ <Progress value={(runningContainers / dashboardStates.containers.length) * 100} class="h-1 mt-4" />
{/if}
</Card.Content>
</Card.Root>
@@ -191,7 +170,7 @@
<div class="flex justify-between items-start">
<div>
<p class="text-sm font-medium text-muted-foreground">Images</p>
- <p class="text-2xl font-bold mt-1">{dockerInfo?.Images || 0}</p>
+ <p class="text-2xl font-bold mt-1">{dashboardStates.dockerInfo?.Images || 0}</p>
</div>
<div class="bg-blue-500/10 p-2 rounded-full">
<HardDrive class="h-5 w-5 text-blue-500" />
@@ -201,7 +180,7 @@
<div class="mt-4 text-xs text-muted-foreground">
Total size: {formatBytes(totalImageSize)}
</div>
- {:else if dockerInfo?.Images === 0}
+ {:else if dashboardStates.dockerInfo?.Images === 0}
<div class="mt-4 text-xs text-muted-foreground">No images stored</div>
{/if}
</Card.Content>
@@ -212,14 +191,14 @@
<div class="flex justify-between items-start">
<div>
<p class="text-sm font-medium text-muted-foreground">CPU</p>
- <p class="text-2xl font-bold mt-1">{dockerInfo?.NCPU || 'N/A'}</p>
+ <p class="text-2xl font-bold mt-1">{dashboardStates.dockerInfo?.NCPU || 'N/A'}</p>
</div>
<div class="bg-purple-500/10 p-2 rounded-full">
<Cpu class="h-5 w-5 text-purple-500" />
</div>
</div>
<div class="mt-4 text-xs text-muted-foreground">
- {dockerInfo?.Architecture || 'Unknown architecture'}
+ {dashboardStates.dockerInfo?.Architecture || 'Unknown architecture'}
</div>
</Card.Content>
</Card.Root>
@@ -230,7 +209,7 @@
<div>
<p class="text-sm font-medium text-muted-foreground">Memory</p>
<p class="text-2xl font-bold mt-1">
- {formatBytes(dockerInfo?.MemTotal, 0)}
+ {formatBytes(dashboardStates.dockerInfo?.MemTotal, 0)}
</p>
</div>
<div class="bg-amber-500/10 p-2 rounded-full">
@@ -238,9 +217,9 @@
</div>
</div>
<div class="mt-4 text-xs text-muted-foreground">
- {dockerInfo?.OperatingSystem || 'Unknown OS'}
- {#if dockerInfo?.ServerVersion}
- <span class="ml-1">• v{dockerInfo.ServerVersion}</span>
+ {dashboardStates.dockerInfo?.OperatingSystem || 'Unknown OS'}
+ {#if dashboardStates.dockerInfo?.ServerVersion}
+ <span class="ml-1">• v{dashboardStates.dockerInfo.ServerVersion}</span>
{/if}
</div>
</Card.Content>
@@ -252,8 +231,8 @@
<h2 class="text-lg font-semibold tracking-tight mb-4">Quick Actions</h2>
<div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
<Card.Root class="flex flex-col justify-center items-center p-5 h-full">
- <Button onclick={handleStartAll} class="w-full" disabled={!dockerInfo || stoppedContainers === 0 || isStartingAll || isStoppingAll || isPruning} variant="default">
- {#if isStartingAll}
+ <Button onclick={handleStartAll} class="w-full" disabled={!dashboardStates.dockerInfo || stoppedContainers === 0 || isLoading.starting || isLoading.stopping || isLoading.pruning} variant="default">
+ {#if isLoading.starting}
<Loader2 class="h-4 w-4 mr-2 animate-spin" />
{:else}
<PlayCircle class="h-4 w-4 mr-2" />
@@ -265,8 +244,8 @@
</Card.Root>
<Card.Root class="flex flex-col justify-center items-center p-5 h-full">
- <Button onclick={handleStopAll} class="w-full" variant="secondary" disabled={!dockerInfo || runningContainers === 0 || isStartingAll || isStoppingAll || isPruning}>
- {#if isStoppingAll}
+ <Button onclick={handleStopAll} class="w-full" variant="secondary" disabled={!dashboardStates.dockerInfo || runningContainers === 0 || isLoading.starting || isLoading.stopping || isLoading.pruning}>
+ {#if isLoading.stopping}
<Loader2 class="h-4 w-4 mr-2 animate-spin" />
{:else}
<StopCircle class="h-4 w-4 mr-2" />
@@ -278,8 +257,8 @@
</Card.Root>
<Card.Root class="flex flex-col justify-center items-center p-5 h-full">
- <Button onclick={openPruneDialog} class="w-full" variant="destructive" disabled={!dockerInfo || isStartingAll || isStoppingAll || isPruning}>
- {#if isPruning}
+ <Button onclick={() => (dashboardStates.isPruneDialogOpen = true)} class="w-full" variant="destructive" disabled={!dashboardStates.dockerInfo || isLoading.starting || isLoading.stopping || isLoading.pruning}>
+ {#if isLoading.pruning}
<Loader2 class="h-4 w-4 mr-2 animate-spin" />
{:else}
<Trash2 class="h-4 w-4 mr-2" />
@@ -301,19 +280,25 @@
<Card.Title>Containers</Card.Title>
<Card.Description class="pb-3">Recent containers</Card.Description>
</div>
- <Button variant="ghost" size="sm" href="/containers" disabled={!dockerInfo}>
+ <Button variant="ghost" size="sm" href="/containers" disabled={!dashboardStates.dockerInfo}>
View All
<ArrowRight class="ml-2 h-4 w-4" />
</Button>
</div>
</Card.Header>
<Card.Content class="p-0 flex-1">
- {#if containers?.length > 0}
+ {#if dashboardStates.containers?.length > 0}
<div class="flex flex-col h-full">
<div class="flex-1">
<UniversalTable
- data={containers.slice(0, 5)}
- columns={dashboardContainerColumns}
+ data={dashboardStates.containers.slice(0, 5)}
+ columns={[
+ { accessorKey: 'name', header: 'Name' },
+ { accessorKey: 'id', header: 'ID' },
+ { accessorKey: 'image', header: 'Image' },
+ { accessorKey: 'state', header: 'State' },
+ { accessorKey: 'status', header: 'Status' }
+ ]}
features={{
filtering: false,
selection: false
@@ -325,15 +310,24 @@
display={{
isDashboardTable: true
}}
- />
+ >
+ {#snippet rows({ item })}
+ {@const stateVariant = statusVariantMap[item.state.toLowerCase()]}
+ <Table.Cell><a class="font-medium hover:underline" href="/containers/{item.id}/">{item.name}</a></Table.Cell>
+ <Table.Cell>{shortId(item.id)}</Table.Cell>
+ <Table.Cell>{item.image}</Table.Cell>
+ <Table.Cell><StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.state)} /></Table.Cell>
+ <Table.Cell>{item.status}</Table.Cell>
+ {/snippet}
+ </UniversalTable>
</div>
- {#if containers.length > 5}
+ {#if dashboardStates.containers.length > 5}
<div class="bg-muted/40 py-2 px-6 text-xs text-muted-foreground border-t">
- Showing 5 of {containers.length} containers
+ Showing 5 of {dashboardStates.containers.length} containers
</div>
{/if}
</div>
- {:else if !error}
+ {:else if !dashboardStates.error}
<div class="flex flex-col items-center justify-center py-10 px-6 text-center">
<Box class="h-8 w-8 text-muted-foreground mb-2 opacity-40" />
<p class="text-sm text-muted-foreground">No containers found</p>
@@ -350,19 +344,24 @@
<Card.Title>Images</Card.Title>
<Card.Description class="pb-3">Recent images</Card.Description>
</div>
- <Button variant="ghost" size="sm" href="/images" disabled={!dockerInfo}>
+ <Button variant="ghost" size="sm" href="/images" disabled={!dashboardStates.dockerInfo}>
View All
<ArrowRight class="ml-2 h-4 w-4" />
</Button>
</div>
</Card.Header>
<Card.Content class="p-0 flex-1">
- {#if images?.length > 0}
+ {#if dashboardStates.images?.length > 0}
<div class="flex flex-col h-full">
<div class="flex-1">
<UniversalTable
- data={images.slice(0, 5)}
- columns={dashboardImageColumns}
+ data={dashboardStates.images.slice(0, 5)}
+ columns={[
+ { accessorKey: 'repo', header: 'Name' },
+ { accessorKey: 'tag', header: 'Tag' },
+ { accessorKey: 'id', header: 'Image ID', enableSorting: false },
+ { accessorKey: 'size', header: 'Size' }
+ ]}
features={{
filtering: false,
selection: false
@@ -377,15 +376,33 @@
sort={{
defaultSort: { id: 'repo', desc: false }
}}
- />
+ >
+ {#snippet rows({ item })}
+ <Table.Cell>
+ <div class="flex items-center gap-2">
+ <span class="truncate">
+ <a class="font-medium hover:underline" href="/images/{item.id}/">
+ {item.repo}
+ </a>
+ </span>
+ {#if !item.inUse}
+ <StatusBadge text="Unused" variant="amber" />
+ {/if}
+ </div>
+ </Table.Cell>
+ <Table.Cell>{item.tag}</Table.Cell>
+ <Table.Cell>{shortId(item.id)}</Table.Cell>
+ <Table.Cell>{formatBytes(item.size)}</Table.Cell>
+ {/snippet}
+ </UniversalTable>
</div>
- {#if images.length > 5}
+ {#if dashboardStates.images.length > 5}
<div class="bg-muted/40 py-2 px-6 text-xs text-muted-foreground border-t">
- Showing 5 of {images.length} images
+ Showing 5 of {dashboardStates.images.length} images
</div>
{/if}
</div>
- {:else if !error}
+ {:else if !dashboardStates.error}
<div class="flex flex-col items-center justify-center py-10 px-6 text-center">
<HardDrive class="h-8 w-8 text-muted-foreground mb-2 opacity-40" />
<p class="text-sm text-muted-foreground">No images found</p>
@@ -415,11 +432,9 @@
<span class="sr-only">GitHub</span>
</a>
</div>
- <div>
- <!-- Optional: Add version or other info here -->
- </div>
+ <div></div>
</div>
</section>
- <PruneConfirmationDialog bind:open={isPruneDialogOpen} {isPruning} imagePruneMode={settings?.pruneMode || 'dangling'} onConfirm={confirmPrune} onCancel={() => (isPruneDialogOpen = false)} />
+ <PruneConfirmationDialog bind:open={dashboardStates.isPruneDialogOpen} isPruning={isLoading.pruning} imagePruneMode={dashboardStates.settings?.pruneMode || 'dangling'} onConfirm={confirmPrune} onCancel={() => (dashboardStates.isPruneDialogOpen = false)} />
</div>
diff --git a/src/routes/api/containers/+server.ts b/src/routes/api/containers/+server.ts
index 55855e094..3ff7ae9d6 100644
--- a/src/routes/api/containers/+server.ts
+++ b/src/routes/api/containers/+server.ts
@@ -7,7 +7,6 @@ export const POST: RequestHandler = async ({ request }) => {
try {
const config = (await request.json()) as ContainerConfig;
- // Validate required fields
if (!config.name || !config.image) {
return json({ success: false, error: 'Container name and image are required' }, { status: 400 });
}
diff --git a/src/routes/api/docker/containers/+server.ts b/src/routes/api/docker/containers/+server.ts
deleted file mode 100644
index a45511a85..000000000
--- a/src/routes/api/docker/containers/+server.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { json } from '@sveltejs/kit';
-import type { RequestHandler } from './$types';
-import { listContainers } from '$lib/services/docker/container-service';
-
-export const GET: RequestHandler = async () => {
- try {
- const containers = await listContainers(true); // Get all containers
- return json(containers);
- } catch (error: any) {
- console.error('API Error fetching containers:', error);
- // Return an appropriate error response
- return json({ error: error.message || 'Failed to fetch containers' }, { status: 500 });
- }
-};
-
-export const POST: RequestHandler = async ({ request }) => {
- const data = await request.json();
- // Create a new container using the service
- // try {
- // const newContainer = await createContainer(data); // Assuming you add createContainer to docker.ts
- // return json(newContainer, { status: 201 });
- // } catch (error: any) {
- // return json({ error: error.message || 'Failed to create container' }, { status: 500 });
- // }
-
- // Placeholder response for now
- return json({
- message: 'Create endpoint not fully implemented',
- id: 'new_container_id',
- name: data.name
- });
-};
diff --git a/src/routes/api/images/prune/+server.ts b/src/routes/api/images/prune/+server.ts
index d07b9dc1d..9afe863aa 100644
--- a/src/routes/api/images/prune/+server.ts
+++ b/src/routes/api/images/prune/+server.ts
@@ -9,7 +9,7 @@ export const POST: RequestHandler = async () => {
const settings = await getSettings();
const pruneMode = settings.pruneMode;
- const result = await pruneImages(pruneMode); // Pass the mode
+ const result = await pruneImages(pruneMode);
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}.`;
diff --git a/src/routes/api/images/pull-stream/[...name]/+server.ts b/src/routes/api/images/pull-stream/[...name]/+server.ts
index a14914633..f6531d2e2 100644
--- a/src/routes/api/images/pull-stream/[...name]/+server.ts
+++ b/src/routes/api/images/pull-stream/[...name]/+server.ts
@@ -1,6 +1,6 @@
import type { RequestHandler } from './$types';
import { getDockerClient } from '$lib/services/docker/core';
-import { URL } from 'url'; // Import URL
+import { URL } from 'url';
export const GET: RequestHandler = async ({ params, request }) => {
const imageName = params.name;
@@ -8,7 +8,6 @@ export const GET: RequestHandler = async ({ params, request }) => {
const tag = url.searchParams.get('tag') || 'latest';
const platform = url.searchParams.get('platform');
- // Set up SSE headers
const headers = new Headers({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
@@ -35,7 +34,11 @@ export const GET: RequestHandler = async ({ params, request }) => {
// Pass options to docker.pull
const pullStream = await docker.pull(fullImageRef, pullOptions);
- let layers: Record<string, any> = {};
+ type LayerProgress = {
+ current: number;
+ total: number;
+ };
+ const layers: Record<string, LayerProgress> = {};
let totalProgress = 0;
docker.modem.followProgress(
diff --git a/src/routes/api/images/pull/[...name]/+server.ts b/src/routes/api/images/pull/[...name]/+server.ts
index 294e102f9..3bc3a6eee 100644
--- a/src/routes/api/images/pull/[...name]/+server.ts
+++ b/src/routes/api/images/pull/[...name]/+server.ts
@@ -14,7 +14,7 @@ export const POST: RequestHandler = async ({ params, request }) => {
const platform = body?.platform;
const tag = body?.tag || 'latest';
- let imageRef = fullPath.includes(':') ? fullPath : `${fullPath}:${tag}`;
+ const imageRef = fullPath.includes(':') ? fullPath : `${fullPath}:${tag}`;
console.log(`API: Pulling image "${imageRef}"...`);
await pullImage(imageRef, platform);
diff --git a/src/routes/api/stacks/[stackId]/+server.ts b/src/routes/api/stacks/[stackId]/+server.ts
index 87a8db3fd..be3d34f71 100644
--- a/src/routes/api/stacks/[stackId]/+server.ts
+++ b/src/routes/api/stacks/[stackId]/+server.ts
@@ -2,11 +2,12 @@ import type { RequestHandler } from './$types';
import { json } from '@sveltejs/kit';
import { updateStack } from '$lib/services/docker/stack-service';
-export const PATCH: RequestHandler = async ({ params, request }) => {
+export const PUT: RequestHandler = async ({ params, request }) => {
const { stackId } = params;
const { name, composeContent, autoUpdate } = await request.json();
try {
+ // From your API endpoint
await updateStack(stackId, { name, composeContent, autoUpdate });
return json({ success: true, message: 'Stack updated successfully' });
} catch (error: any) {
diff --git a/src/routes/api/stacks/create/+server.ts b/src/routes/api/stacks/create/+server.ts
index c516eeafe..23fe2946e 100644
--- a/src/routes/api/stacks/create/+server.ts
+++ b/src/routes/api/stacks/create/+server.ts
@@ -9,11 +9,11 @@ export const POST: RequestHandler = async ({ request }) => {
const composeContent = body.composeContent?.toString();
if (!name) {
- throw error(400, 'Stack name is required');
+ throw error(502, 'Stack name is required');
}
if (!composeContent) {
- throw error(400, 'Compose file content is required');
+ throw error(503, 'Compose file content is required');
}
const newStack = await createStack(name, composeContent);
diff --git a/src/routes/api/stacks/import/+server.ts b/src/routes/api/stacks/import/+server.ts
index 52b78475a..0320322f1 100644
--- a/src/routes/api/stacks/import/+server.ts
+++ b/src/routes/api/stacks/import/+server.ts
@@ -3,9 +3,7 @@ import type { RequestHandler } from './$types';
import { importExternalStack } from '$lib/services/docker/stack-service';
export const POST: RequestHandler = async ({ request }) => {
- const data = await request.formData();
- const stackId = data.get('stackId')?.toString();
- const stackName = data.get('stackName')?.toString();
+ const { stackId, stackName } = await request.json();
if (!stackId) {
return json({ success: false, error: 'Stack ID is required' }, { status: 400 });
diff --git a/src/routes/api/system/prune/+server.ts b/src/routes/api/system/prune/+server.ts
index 98e37480a..4e39940ff 100644
--- a/src/routes/api/system/prune/+server.ts
+++ b/src/routes/api/system/prune/+server.ts
@@ -2,9 +2,10 @@ import { json, error as serverError } from '@sveltejs/kit';
import { pruneSystem } from '$lib/services/docker/system-service';
import type { RequestHandler } from './$types';
import { formatBytes } from '$lib/utils'; // Import formatBytes
+import type { PruneType } from '$lib/types/actions.type';
// Define allowed types
-type PruneType = 'containers' | 'images' | 'networks' | 'volumes';
+
const allowedPruneTypes: PruneType[] = ['containers', 'images', 'networks', 'volumes'];
export const POST: RequestHandler = async ({ url }) => {
diff --git a/src/routes/api/volumes/+server.ts b/src/routes/api/volumes/+server.ts
index 5a08615a5..45428f88c 100644
--- a/src/routes/api/volumes/+server.ts
+++ b/src/routes/api/volumes/+server.ts
@@ -5,27 +5,20 @@ import type { VolumeCreateOptions } from 'dockerode';
export const POST: RequestHandler = async ({ request }) => {
try {
- const body = await request.json();
+ const body: VolumeCreateOptions = await request.json();
- if (!body.name || typeof body.name !== 'string' || body.name.trim() === '') {
- return json({ error: 'Volume name is required.' }, { status: 400 });
+ if (!body.Name) {
+ return json({ error: 'Volume name is required.' }, { status: 409 });
}
- const options: VolumeCreateOptions = {
- Name: body.name.trim(),
- Driver: body.driver || 'local',
- Labels: body.labels || {},
- DriverOpts: body.driverOpts || {}
- };
-
- const volumeInfo = await createVolume(options);
+ const volumeInfo = await createVolume(body);
return json(
{
success: true,
volume: {
...volumeInfo,
- Name: body.name.trim() // Ensure Name is set correctly
+ Name: volumeInfo.name
}
},
{ status: 201 }
diff --git a/src/routes/columns.ts b/src/routes/columns.ts
deleted file mode 100644
index f43185531..000000000
--- a/src/routes/columns.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import type { ColumnDef } from '@tanstack/table-core';
-import type { ServiceContainer, ServiceImage } from '$lib/types/docker';
-import { formatBytes } from '$lib/utils';
-import { capitalizeFirstLetter } from '$lib/utils';
-import { statusVariantMap } from '$lib/types/statuses';
-import { renderComponent } from '$lib/components/ui/data-table/index.js';
-import StatusBadge from '$lib/components/badges/status-badge.svelte';
-
-// Column definitions for the dashboard containers table
-export const dashboardContainerColumns: ColumnDef<ServiceContainer>[] = [
- {
- accessorKey: 'name',
- header: 'Name',
- cell: ({ row }) => row.original.name
- },
- {
- accessorKey: 'image',
- header: 'Image',
- cell: ({ row }) => row.original.image
- },
- {
- accessorKey: 'state',
- header: 'Status',
- cell: ({ row }) => {
- const variant = statusVariantMap[row.original.state.toLowerCase()] || 'gray';
-
- return renderComponent(StatusBadge, {
- variant: variant,
- text: capitalizeFirstLetter(row.original.state)
- });
- }
- },
- {
- accessorKey: 'status',
- header: 'Status',
- cell: ({ row }) => row.original.status
- }
-];
-
-// Column definitions for the dashboard images table
-export const dashboardImageColumns: ColumnDef<ServiceImage>[] = [
- {
- accessorKey: 'repo',
- header: 'Name',
- cell: ({ row }) => row.original.repo
- },
- {
- accessorKey: 'tag',
- header: 'Tag',
- cell: ({ row }) => row.original.tag
- },
- {
- accessorKey: 'size',
- header: 'Size',
- cell: ({ row }) => formatBytes(row.original.size)
- }
-];
diff --git a/src/routes/containers/+page.server.ts b/src/routes/containers/+page.server.ts
index f5c2e8cfd..58947311d 100644
--- a/src/routes/containers/+page.server.ts
+++ b/src/routes/containers/+page.server.ts
@@ -28,43 +28,3 @@ export const load: PageServerLoad = async () => {
};
}
};
-
-export const actions: Actions = {
- create: async ({ request }) => {
- try {
- const formData = await request.formData();
- const containerDataString = formData.get('containerData');
-
- if (!containerDataString) {
- return fail(400, {
- success: false,
- error: 'No container data provided'
- });
- }
-
- const containerData = JSON.parse(containerDataString.toString()) as ContainerConfig;
-
- // Validate required fields
- if (!containerData.name || !containerData.image) {
- return fail(400, {
- success: false,
- error: 'Container name and image are required'
- });
- }
-
- // Create the container
- const container = await createContainer(containerData);
-
- return {
- success: true,
- container
- };
- } catch (error: any) {
- console.error('Error creating container:', error);
- return fail(500, {
- success: false,
- error: error.message || 'Failed to create container'
- });
- }
- }
-};
diff --git a/src/routes/containers/+page.svelte b/src/routes/containers/+page.svelte
index d01cd3f5e..09bd330c0 100644
--- a/src/routes/containers/+page.svelte
+++ b/src/routes/containers/+page.svelte
@@ -1,28 +1,39 @@
<script lang="ts">
+ import { ScanSearch, Play, RotateCcw, StopCircle, Trash2, Loader2, Plus, Box, RefreshCw, Ellipsis } from '@lucide/svelte';
import { Button } from '$lib/components/ui/button/index.js';
import * as Card from '$lib/components/ui/card/index.js';
- import { columns } from './columns';
- import { Plus, Box, RefreshCw } from '@lucide/svelte';
import UniversalTable from '$lib/components/universal-table.svelte';
- import { invalidateAll } from '$app/navigation';
- import { toast } from 'svelte-sonner';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import * as Table from '$lib/components/ui/table';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
import CreateContainerDialog from './create-container-dialog.svelte';
- import type { ContainerConfig, ServiceContainer } from '$lib/types/docker/container.type';
- import { enhance } from '$app/forms';
+ import { goto, invalidateAll } from '$app/navigation';
+ import { toast } from 'svelte-sonner';
+ import type { ServiceContainer } from '$lib/types/docker/container.type';
+ import ContainerAPIService from '$lib/services/api/container-api-service';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { statusVariantMap } from '$lib/types/statuses';
+ import { capitalizeFirstLetter } from '$lib/utils/string.utils';
+ import { handleApiReponse } from '$lib/utils/api.util';
+ import { shortId } from '$lib/utils/string.utils';
- let { data, form } = $props();
+ const containerApi = new ContainerAPIService();
+
+ let { data } = $props();
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);
- let formRef: HTMLFormElement;
-
+ let isLoading = $state({
+ start: false,
+ stop: false,
+ restart: false,
+ remove: false
+ });
+ const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
const runningContainers = $derived(containers?.filter((c: ServiceContainer) => c.state === 'running').length || 0);
const stoppedContainers = $derived(containers?.filter((c: ServiceContainer) => c.state === 'exited').length || 0);
-
- // Calculate total containers
const totalContainers = $derived(containers?.length || 0);
$effect(() => {
@@ -32,18 +43,6 @@
}
});
- // Success message handling based on form action result
- $effect(() => {
- if (form?.success) {
- toast.success(`Container "${form.container?.name || 'Unknown'}" created successfully.`);
- isCreateDialogOpen = false;
- isCreatingContainer = false;
- } else if (form?.error) {
- toast.error(`Failed to create container: ${form.error}`);
- isCreatingContainer = false;
- }
- });
-
async function refreshData() {
isRefreshing = true;
try {
@@ -59,31 +58,78 @@
function openCreateDialog() {
isCreateDialogOpen = true;
}
- // This now prepares data for form action and submits the form
- async function handleCreateContainerSubmit(config: ContainerConfig) {
- isCreatingContainer = true;
- containerData = config;
-
- // This is key - explicitly submit the form after setting the data
- setTimeout(() => {
- formRef.requestSubmit();
- }, 0);
+
+ async function handleRemoveContainer(id: string) {
+ // const endpoint = `/api/containers/${id}/remove${force ? '?force=true' : ''}`;
+ openConfirmDialog({
+ title: 'Delete Container',
+ message: 'Are you sure you want to delete this container? This action cannot be undone.',
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ handleApiReponse(
+ await tryCatch(containerApi.remove(id)),
+ 'Failed to Remove Container',
+ (value) => (isLoading.remove = value),
+ async () => {
+ toast.success('Container Removed Successfully.');
+ await invalidateAll();
+ }
+ );
+ }
+ }
+ });
+ }
+
+ async function performContainerAction(action: 'start' | 'stop' | 'restart', id: string) {
+ isLoading[action] = true;
+
+ if (action === 'start') {
+ handleApiReponse(
+ await tryCatch(containerApi.start(id)),
+ 'Failed to Start Container',
+ (value) => (isLoading.start = value),
+ async () => {
+ toast.success('Container Started Successfully.');
+ await invalidateAll();
+ }
+ );
+ } else if (action === 'stop') {
+ handleApiReponse(
+ await tryCatch(containerApi.stop(id)),
+ 'Failed to Stop Container',
+ (value) => (isLoading.stop = value),
+ async () => {
+ toast.success('Container Stopped Successfully.');
+ await invalidateAll();
+ }
+ );
+ } else if (action === 'restart') {
+ handleApiReponse(
+ await tryCatch(containerApi.restart(id)),
+ 'Failed to Restart Container',
+ (value) => (isLoading.stop = value),
+ async () => {
+ toast.success('Container Restarted Successfully.');
+ await invalidateAll();
+ }
+ );
+ } else {
+ console.error('An Unknown Error Occurred');
+ toast.error('An Unknown Error Occurred');
+ }
}
</script>
<div class="space-y-6">
- <!-- Header with refresh button -->
<div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">
<div>
<h1 class="text-3xl font-bold tracking-tight">Containers</h1>
<p class="text-sm text-muted-foreground mt-1">Manage your Docker containers</p>
</div>
- <div class="flex gap-2">
- <!-- put buttons here -->
- </div>
</div>
- <!-- Container 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">
@@ -139,7 +185,6 @@
</div>
</div>
{:else}
- <!-- Main container table -->
<Card.Root class="border shadow-sm">
<Card.Header class="px-6">
<div class="flex items-center justify-between">
@@ -158,33 +203,95 @@
<Card.Content>
<UniversalTable
data={containers}
- {columns}
+ columns={[
+ { accessorKey: 'name', header: 'Name' },
+ { accessorKey: 'id', header: 'ID' },
+ { accessorKey: 'image', header: 'Image' },
+ { accessorKey: 'state', header: 'State' },
+ { accessorKey: 'status', header: 'Status' },
+ { accessorKey: 'actions', header: ' ', enableSorting: false }
+ ]}
+ features={{
+ selection: false
+ }}
display={{
filterPlaceholder: 'Search containers...',
noResultsMessage: 'No containers found'
}}
bind:selectedIds
- />
+ >
+ {#snippet rows({ item })}
+ {@const stateVariant = statusVariantMap[item.state.toLowerCase()]}
+ <Table.Cell><a class="font-medium hover:underline" href="/containers/{item.id}/">{item.name}</a></Table.Cell>
+ <Table.Cell>{shortId(item.id)}</Table.Cell>
+ <Table.Cell>{item.image}</Table.Cell>
+ <Table.Cell><StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.state)} /></Table.Cell>
+ <Table.Cell>{item.status}</Table.Cell>
+ <Table.Cell>
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
+ <span class="sr-only">Open menu</span>
+ <Ellipsis />
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <DropdownMenu.Item onclick={() => goto(`/containers/${item.id}`)} disabled={isAnyLoading}>
+ <ScanSearch class="w-4 h-4" />
+ Inspect
+ </DropdownMenu.Item>
+
+ {#if item.state !== 'running'}
+ <DropdownMenu.Item onclick={() => performContainerAction('start', item.id)} disabled={isLoading.start || isAnyLoading}>
+ {#if isLoading.start}
+ <Loader2 class="w-4 h-4 animate-spin" />
+ {:else}
+ <Play class="w-4 h-4" />
+ {/if}
+ Start
+ </DropdownMenu.Item>
+ {:else}
+ <DropdownMenu.Item onclick={() => performContainerAction('restart', item.id)} disabled={isLoading.restart || isAnyLoading}>
+ {#if isLoading.restart}
+ <Loader2 class="w-4 h-4 animate-spin" />
+ {:else}
+ <RotateCcw class="w-4 h-4" />
+ {/if}
+ Restart
+ </DropdownMenu.Item>
+
+ <DropdownMenu.Item onclick={() => performContainerAction('stop', item.id)} disabled={isLoading.stop || isAnyLoading}>
+ {#if isLoading.stop}
+ <Loader2 class="w-4 h-4 animate-spin" />
+ {:else}
+ <StopCircle class="w-4 h-4" />
+ {/if}
+ Stop
+ </DropdownMenu.Item>
+ {/if}
+
+ <DropdownMenu.Separator />
+
+ <DropdownMenu.Item class="text-red-500 focus:!text-red-700" onclick={() => handleRemoveContainer(item.id)} disabled={isLoading.remove || isAnyLoading}>
+ {#if isLoading.remove}
+ <Loader2 class="w-4 h-4 animate-spin" />
+ {:else}
+ <Trash2 class="w-4 h-4" />
+ {/if}
+ Remove
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </UniversalTable>
</Card.Content>
</Card.Root>
{/if}
- <form
- bind:this={formRef}
- method="POST"
- action="?/create"
- use:enhance={() => {
- return async ({ result }) => {
- isCreatingContainer = false;
- if (result.type === 'success') {
- isCreateDialogOpen = false;
- await refreshData();
- }
- };
- }}
- >
- <input type="hidden" name="containerData" value={containerData ? JSON.stringify(containerData) : ''} />
-
- <CreateContainerDialog bind:open={isCreateDialogOpen} isCreating={isCreatingContainer} volumes={data.volumes || []} networks={data.networks || []} images={data.images || []} onSubmit={handleCreateContainerSubmit} />
- </form>
+ <CreateContainerDialog bind:open={isCreateDialogOpen} volumes={data.volumes || []} networks={data.networks || []} images={data.images || []} />
</div>
diff --git a/src/routes/containers/ContainerActions.svelte b/src/routes/containers/ContainerActions.svelte
deleted file mode 100644
index f1b412bfd..000000000
--- a/src/routes/containers/ContainerActions.svelte
+++ /dev/null
@@ -1,143 +0,0 @@
-<script lang="ts">
- import Ellipsis from '@lucide/svelte/icons/ellipsis';
- import { Button } from '$lib/components/ui/button/index.js';
- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
- import { goto, invalidateAll } from '$app/navigation';
- import { ScanSearch, Play, RotateCcw, StopCircle, Trash2, Loader2 } from '@lucide/svelte';
- import { toast } from 'svelte-sonner';
- import ConfirmDialog from '$lib/components/confirm-dialog.svelte';
-
- let { id, itemState }: { id: string; itemState: string } = $props();
-
- let isLoading = $state({
- start: false,
- stop: false,
- restart: false,
- remove: false
- });
- let showRemoveConfirm = $state(false);
-
- function viewContainer() {
- goto(`/containers/${id}`);
- }
-
- async function performContainerAction(action: 'start' | 'stop' | 'restart' | 'remove') {
- if (action === 'remove') {
- showRemoveConfirm = true;
- return;
- }
-
- isLoading[action] = true;
- const method = 'POST';
- const endpoint = `/api/containers/${id}/${action}`;
-
- try {
- const response = await fetch(endpoint, { method });
- const result = await response.json();
-
- if (!response.ok) {
- throw new Error(result.error?.message || `Failed to ${action} container`);
- }
-
- toast.success(`Container ${action}ed successfully.`);
- await invalidateAll();
- } catch (error: any) {
- console.error(`Failed to ${action} container ${id}:`, error);
- toast.error(`Failed to ${action} container: ${error.message}`);
- } finally {
- isLoading[action] = false;
- }
- }
-
- async function handleRemoveConfirm(force?: boolean) {
- showRemoveConfirm = false;
- isLoading.remove = true;
- const method = 'DELETE';
- const endpoint = `/api/containers/${id}/remove${force ? '?force=true' : ''}`;
-
- console.log(`Attempting to remove container ${id} at endpoint: ${endpoint}`);
-
- try {
- const response = await fetch(endpoint, { method });
- const result = await response.json();
-
- if (!response.ok) {
- throw new Error(result.error?.message || `Failed to remove container`);
- }
-
- toast.success(`Container removed successfully.`);
- await invalidateAll();
- } catch (error: any) {
- console.error(`Failed to remove container ${id}:`, error);
- toast.error(`Failed to remove container: ${error.message}`);
- } finally {
- isLoading.remove = false;
- }
- }
-
- const isRunning = $derived(itemState === 'running');
- const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
- const removeDescription = $derived(`Are you sure you want to remove container ${id}? This action cannot be undone.`);
-</script>
-
-<!-- Confirmation Dialog for Remove -->
-<ConfirmDialog bind:open={showRemoveConfirm} itemType={'container'} {isRunning} title="Confirm Removal" description={removeDescription} confirmLabel="Remove" variant="destructive" onConfirm={handleRemoveConfirm} />
-
-<DropdownMenu.Root>
- <DropdownMenu.Trigger>
- {#snippet child({ props })}
- <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
- <span class="sr-only">Open menu</span>
- <Ellipsis />
- </Button>
- {/snippet}
- </DropdownMenu.Trigger>
- <DropdownMenu.Content>
- <DropdownMenu.Group>
- <DropdownMenu.Item onclick={viewContainer} disabled={isAnyLoading}>
- <ScanSearch class="w-4 h-4" />
- Inspect
- </DropdownMenu.Item>
-
- {#if !isRunning}
- <DropdownMenu.Item onclick={() => performContainerAction('start')} disabled={isLoading.start || isAnyLoading}>
- {#if isLoading.start}
- <Loader2 class="w-4 h-4 animate-spin" />
- {:else}
- <Play class="w-4 h-4" />
- {/if}
- Start
- </DropdownMenu.Item>
- {:else}
- <DropdownMenu.Item onclick={() => performContainerAction('restart')} disabled={isLoading.restart || isAnyLoading}>
- {#if isLoading.restart}
- <Loader2 class="w-4 h-4 animate-spin" />
- {:else}
- <RotateCcw class="w-4 h-4" />
- {/if}
- Restart
- </DropdownMenu.Item>
-
- <DropdownMenu.Item onclick={() => performContainerAction('stop')} disabled={isLoading.stop || isAnyLoading}>
- {#if isLoading.stop}
- <Loader2 class="w-4 h-4 animate-spin" />
- {:else}
- <StopCircle class="w-4 h-4" />
- {/if}
- Stop
- </DropdownMenu.Item>
- {/if}
-
- <DropdownMenu.Separator />
-
- <DropdownMenu.Item class="text-red-500 focus:!text-red-700" onclick={() => performContainerAction('remove')} disabled={isLoading.remove || isAnyLoading}>
- {#if isLoading.remove}
- <Loader2 class="w-4 h-4 animate-spin" />
- {:else}
- <Trash2 class="w-4 h-4" />
- {/if}
- Remove
- </DropdownMenu.Item>
- </DropdownMenu.Group>
- </DropdownMenu.Content>
-</DropdownMenu.Root>
diff --git a/src/routes/containers/[id]/+page.server.ts b/src/routes/containers/[id]/+page.server.ts
index e587a715f..c7db6540b 100644
--- a/src/routes/containers/[id]/+page.server.ts
+++ b/src/routes/containers/[id]/+page.server.ts
@@ -1,24 +1,19 @@
-import type { PageServerLoad, Actions } from './$types';
-// Import getContainerStats
-import { getContainer, startContainer, stopContainer, restartContainer, removeContainer, getContainerLogs, getContainerStats } from '$lib/services/docker/container-service';
-import { error, fail, redirect } from '@sveltejs/kit';
-import type Docker from 'dockerode'; // Import Docker type for stats
+import type { PageServerLoad } from './$types';
+import { getContainer, getContainerLogs, getContainerStats } from '$lib/services/docker/container-service';
+import { error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ params }) => {
const containerId = params.id;
try {
- // Fetch container, logs, and stats in parallel
const [container, logs, stats] = await Promise.all([
getContainer(containerId),
getContainerLogs(containerId, { tail: 100 }).catch((err) => {
console.error(`Failed to retrieve logs for ${containerId}:`, err);
- return 'Failed to load logs. Container might not be running or logs are unavailable.'; // Updated message
+ return 'Failed to load logs. Container might not be running or logs are unavailable.';
}),
getContainerStats(containerId).catch((err) => {
- // Fetch stats
console.error(`Failed to retrieve stats for ${containerId}:`, err);
- // Don't fail the page load for stats errors, just return null
return null;
})
]);
@@ -36,8 +31,6 @@ export const load: PageServerLoad = async ({ params }) => {
};
} catch (err: any) {
console.error(`Failed to load container ${containerId}:`, err);
- // If the error is NotFoundError from getContainerStats, it should have been caught above.
- // This handles errors from getContainer primarily.
if (err.name === 'NotFoundError') {
error(404, { message: err.message });
} else {
@@ -47,50 +40,3 @@ export const load: PageServerLoad = async ({ params }) => {
}
}
};
-
-// Actions remain the same
-export const actions: Actions = {
- start: async ({ params }) => {
- const containerId = params.id;
- try {
- await startContainer(containerId);
- return { success: true, message: 'Container started.' };
- } catch (err: any) {
- return fail(500, { error: err.message });
- }
- },
- stop: async ({ params }) => {
- const containerId = params.id;
- try {
- await stopContainer(containerId);
- return { success: true, message: 'Container stopped.' };
- } catch (err: any) {
- return fail(500, { error: err.message });
- }
- },
- restart: async ({ params }) => {
- const containerId = params.id;
- try {
- await restartContainer(containerId);
- return { success: true, message: 'Container restarted.' };
- } catch (err: any) {
- return fail(500, { error: err.message });
- }
- },
- remove: async ({ params, url }) => {
- // Read 'force' from URL
- const containerId = params.id;
- const force = url.searchParams.get('force') === 'true'; // Get force param
- try {
- await removeContainer(containerId, force); // Pass force param
- redirect(303, '/containers');
- } catch (err: any) {
- // Handle specific errors from removeContainer
- if (err.name === 'NotFoundError' || err.name === 'ConflictError' || err.name === 'DockerApiError') {
- return fail(err.status || 500, { error: err.message });
- }
- // Fallback for unexpected errors
- return fail(500, { error: err.message || 'An unexpected error occurred during removal.' });
- }
- }
-};
diff --git a/src/routes/containers/[id]/+page.svelte b/src/routes/containers/[id]/+page.svelte
index 6bf134042..76db2f4e6 100644
--- a/src/routes/containers/[id]/+page.svelte
+++ b/src/routes/containers/[id]/+page.svelte
@@ -1,12 +1,10 @@
<script lang="ts">
- import type { PageData, ActionData } from './$types';
+ 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 { ArrowLeft, AlertCircle, RefreshCw, HardDrive, Clock, Network, Terminal, Cpu, MemoryStick } from '@lucide/svelte';
import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
- import { enhance } from '$app/forms';
import { invalidateAll } from '$app/navigation';
- import * as Alert from '$lib/components/ui/alert/index.js';
import { Badge } from '$lib/components/ui/badge/index.js';
import ActionButtons from '$lib/components/action-buttons.svelte';
import { formatDate, formatLogLine, formatBytes } from '$lib/utils';
@@ -15,7 +13,7 @@
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import * as Tabs from '$lib/components/ui/tabs/index.js';
- let { data, form }: { data: PageData; form: ActionData } = $props();
+ let { data }: { data: PageData } = $props();
let { container, logs, stats } = $derived(data);
let starting = $state(false);
@@ -23,9 +21,7 @@
let restarting = $state(false);
let removing = $state(false);
let isRefreshing = $state(false);
-
- let formattedLogLines = $derived(logs ? logs.split('\n').map(formatLogLine) : []);
-
+ let formattedLogHtml = $derived(logs ? logs.split('\n').map(formatLogLine).join('<br />') : '');
let logsContainer = $state<HTMLDivElement | undefined>(undefined);
// --- Stats Calculation ---
@@ -76,13 +72,6 @@
const primaryIpAddress = $derived(getPrimaryIpAddress(container?.networkSettings));
// --- End Helper ---
- $effect(() => {
- starting = false;
- stopping = false;
- restarting = false;
- removing = false;
- });
-
$effect(() => {
if (logsContainer && logs) {
const shouldScroll = logsContainer.scrollHeight - logsContainer.scrollTop <= logsContainer.clientHeight + 50;
@@ -90,6 +79,11 @@
logsContainer.scrollTop = logsContainer.scrollHeight;
}
}
+
+ starting = false;
+ stopping = false;
+ restarting = false;
+ removing = false;
});
async function refreshData() {
@@ -136,45 +130,21 @@
{#if container}
<div class="flex gap-2 flex-wrap">
- <form
- method="POST"
- action={container.state?.Running ? '?/stop' : '?/start'}
- use:enhance={() => {
- if (container.state?.Running) {
- stopping = true;
- } else {
- starting = true;
- }
- return async ({ update }) => {
- await update({ reset: false });
- };
+ <ActionButtons
+ id={container.id}
+ type="container"
+ itemState={container.state?.Running ? 'running' : 'stopped'}
+ loading={{
+ start: starting,
+ stop: stopping,
+ restart: restarting,
+ remove: removing
}}
- >
- <ActionButtons
- id={container.id}
- type="container"
- itemState={container.state?.Running ? 'running' : 'stopped'}
- loading={{
- start: starting,
- stop: stopping,
- restart: restarting,
- remove: removing
- }}
- />
- </form>
+ />
</div>
{/if}
</div>
- <!-- Error Alert -->
- {#if form?.error}
- <Alert.Root variant="destructive">
- <AlertCircle class="h-4 w-4 mr-2" />
- <Alert.Title>Action Failed</Alert.Title>
- <Alert.Description>{form.error}</Alert.Description>
- </Alert.Root>
- {/if}
-
{#if container}
<Tabs.Root value={activeTab} onValueChange={(val) => (activeTab = val)} class="space-y-4">
<Tabs.List>
@@ -539,7 +509,7 @@
<div class="text-center py-8 border rounded-md border-dashed">
<div class="mb-3 w-12 h-12 rounded-full bg-muted/50 flex items-center justify-center mx-auto">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-muted-foreground">
- <path d="M21 5c0-1.1-.9-2-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5Z"></path>
+ <path d="M21 5c0-1.1-.9-2-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0-2-2H5a2 2 0 0 0-2-2V5Z"></path>
<path d="M2 10h20"></path>
</svg>
</div>
@@ -569,10 +539,8 @@
<Card.Content>
<div class="bg-muted/50 text-foreground p-4 rounded-md font-mono text-xs h-[500px] overflow-auto whitespace-pre-wrap border" bind:this={logsContainer} id="logs-container" style="word-break: break-all;">
- {#if formattedLogLines.length > 0}
- {#each formattedLogLines as line, index (index)}
- {@html line}
- {/each}
+ {#if formattedLogHtml}
+ {@html formattedLogHtml}
{:else}
<div class="flex flex-col items-center justify-center h-full text-center">
<Terminal class="h-8 w-8 text-muted-foreground mb-3 opacity-40" />
@@ -581,10 +549,6 @@
{/if}
</div>
</Card.Content>
-
- <Card.Footer class="flex justify-end border-t pt-4">
- <Button variant="outline" size="sm" href="/containers/{container.id}/logs" class="text-sm">View full logs</Button>
- </Card.Footer>
</Card.Root>
</Tabs.Content>
diff --git a/src/routes/containers/columns.ts b/src/routes/containers/columns.ts
deleted file mode 100644
index 358f0a472..000000000
--- a/src/routes/containers/columns.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import type { ServiceContainer } from '$lib/types/docker';
-import type { ColumnDef } from '@tanstack/table-core';
-import { renderComponent } from '$lib/components/ui/data-table/index.js';
-import DataTableActions from './ContainerActions.svelte';
-import { capitalizeFirstLetter } from '$lib/utils';
-import IdCell from './components/IdCell.svelte';
-import CellName from './components/NameCell.svelte';
-import StatusBadge from '$lib/components/badges/status-badge.svelte';
-import { statusVariantMap } from '$lib/types/statuses';
-
-export const columns: ColumnDef<ServiceContainer>[] = [
- {
- accessorKey: 'name',
- header: 'Name',
- cell: ({ row }) => {
- return renderComponent(CellName, {
- id: row.original.id,
- name: row.original.name
- });
- }
- },
- {
- accessorKey: 'id',
- header: 'ID',
- cell: ({ row }) => {
- return renderComponent(IdCell, { id: row.original.id });
- },
- enableSorting: false
- },
- {
- accessorKey: 'image',
- header: 'Image'
- },
- {
- accessorKey: 'state',
- header: 'Status',
- cell: ({ row }) => {
- const variant = statusVariantMap[row.original.state.toLowerCase()] || 'gray';
-
- return renderComponent(StatusBadge, {
- variant: variant,
- text: capitalizeFirstLetter(row.original.state)
- });
- }
- },
- {
- accessorKey: 'status',
- header: 'Status'
- },
- {
- id: 'actions',
- header: '',
- cell: ({ row }) => {
- return renderComponent(DataTableActions, {
- id: row.original.id,
- itemState: row.original.state
- });
- },
- enableSorting: false
- }
-];
diff --git a/src/routes/containers/components/IdCell.svelte b/src/routes/containers/components/IdCell.svelte
deleted file mode 100644
index ab3d08f32..000000000
--- a/src/routes/containers/components/IdCell.svelte
+++ /dev/null
@@ -1,6 +0,0 @@
-<script lang="ts">
- let { id }: { id: string } = $props();
- let shortId = $derived(id.substring(0, 12));
-</script>
-
-<span class="font-mono text-xs">{shortId}</span>
diff --git a/src/routes/containers/components/NameCell.svelte b/src/routes/containers/components/NameCell.svelte
deleted file mode 100644
index 26bc73b82..000000000
--- a/src/routes/containers/components/NameCell.svelte
+++ /dev/null
@@ -1,12 +0,0 @@
-<script lang="ts">
- interface Props {
- id: string;
- name: string;
- }
-
- let { id, name }: Props = $props();
-</script>
-
-<a href="/containers/{id}" class="font-medium hover:underline">
- {name}
-</a>
diff --git a/src/routes/containers/create-container-dialog.svelte b/src/routes/containers/create-container-dialog.svelte
index a388a6825..24309beb5 100644
--- a/src/routes/containers/create-container-dialog.svelte
+++ b/src/routes/containers/create-container-dialog.svelte
@@ -1,8 +1,6 @@
<script lang="ts">
- import { preventDefault } from 'svelte/legacy';
import type { ContainerConfig } from '$lib/types/docker/container.type';
- import type { HealthConfig } from 'dockerode';
-
+ import { type HealthConfig } from 'dockerode';
import { Button } from '$lib/components/ui/button/index.js';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import { Input } from '$lib/components/ui/input/index.js';
@@ -11,28 +9,27 @@
import * as Select from '$lib/components/ui/select/index.js';
import * as Tabs from '$lib/components/ui/tabs/index.js';
import { parseBytes } from '$lib/utils/bytes';
-
- import { createEventDispatcher } from 'svelte';
+ import { toast } from 'svelte-sonner';
+ import { invalidateAll } from '$app/navigation';
import Switch from '$lib/components/ui/switch/switch.svelte';
- const dispatch = createEventDispatcher();
+ import { handleApiReponse } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import ContainerAPIService from '$lib/services/api/container-api-service';
- // Functions for events
- export function onClose() {
- open = false;
- dispatch('close');
- }
interface Props {
open?: boolean;
- isCreating?: boolean;
volumes?: { name: string }[];
networks?: { name: string; driver: string }[];
images?: { id: string; repo: string; tag: string }[];
- onSubmit?: (data: ContainerConfig) => void;
+ onClose?: () => void;
}
- let { open = $bindable(false), isCreating = false, volumes = [], networks = [], images = [], onSubmit = (_data: ContainerConfig) => {} }: Props = $props();
+ let { open = $bindable(false), volumes = [], networks = [], images = [], onClose: onCloseProp = () => {} }: Props = $props();
+
+ const containerApi = new ContainerAPIService();
// Internal state
+ let isCreating = $state(false);
let containerName = $state('');
let selectedImage = $state('');
let selectedTab = $state('basic');
@@ -90,41 +87,40 @@
// Add state for Auto-update
let autoUpdate = $state(false);
+ function handleClose() {
+ open = false;
+ if (onCloseProp) {
+ onCloseProp();
+ }
+ }
+
// Port validation - improved
function validatePortNumber(port: string | number): {
isValid: boolean;
error?: string;
} {
- // Convert to string if it's not already one
const portStr = typeof port === 'number' ? port.toString() : port;
- // Check if empty
if (!portStr || !portStr.trim()) return { isValid: true };
const portNum = parseInt(portStr, 10);
- // Check if it's a valid number
if (isNaN(portNum) || portNum.toString() !== portStr.trim()) {
return { isValid: false, error: 'Invalid port number' };
}
- // Check port range (1-65535)
if (portNum < 1 || portNum > 65535) {
return { isValid: false, error: 'Port must be between 1-65535' };
}
- // Warning for privileged ports
if (portNum < 1024) {
return { isValid: true, error: 'Privileged port (<1024)' };
}
return { isValid: true };
}
- // Auto-validate on input
$effect(() => {
- // Validate all ports when they change
ports.forEach((port, index) => {
- // Only validate if there's content
if (port.hostPort !== undefined && port.hostPort !== '') {
const hostValidation = validatePortNumber(port.hostPort);
ports[index].hostError = hostValidation.error;
@@ -141,7 +137,6 @@
});
});
- // Add/remove functions for arrays
function addPort() {
ports = [...ports, { hostPort: '', containerPort: '' }];
}
@@ -174,32 +169,26 @@
labels = labels.filter((_, i) => i !== index);
}
- // Reactive check to see if the selected network is user-defined
const isUserDefinedNetwork = $derived(network && network !== '' && network !== 'host' && network !== 'none' && network !== 'bridge');
- function handleSubmit() {
- if (!selectedImage || !containerName.trim()) return;
+ async function handleSubmit() {
+ if (!selectedImage || !containerName.trim() || isCreating) return;
- // Validate all ports
let hasInvalidPort = false;
ports.forEach((port) => {
- // Check for invalid ports with content
if ((port.hostPort && !validatePortNumber(port.hostPort).isValid) || (port.containerPort && !validatePortNumber(port.containerPort).isValid)) {
hasInvalidPort = true;
}
});
if (hasInvalidPort) {
- return; // Stop submission if there are invalid ports
+ toast.error('Please fix invalid port numbers before submitting.');
+ return;
}
- // Filter out empty entries
- const filteredPorts = ports.filter((p) => p.hostPort.trim() && p.containerPort.trim()).map(({ hostPort, containerPort }) => ({ hostPort, containerPort })); // Remove error properties
-
+ const filteredPorts = ports.filter((p) => p.hostPort.trim() && p.containerPort.trim()).map(({ hostPort, containerPort }) => ({ hostPort, containerPort }));
const filteredVolumes = volumeMounts.filter((v) => v.source.trim() && v.target.trim());
const filteredEnvVars = envVars.filter((e) => e.key.trim());
-
- // Filter and format labels
const filteredLabels = labels
.filter((l) => l.key.trim())
.reduce(
@@ -210,17 +199,13 @@
{} as { [key: string]: string }
);
- // Add auto-update label if enabled
if (autoUpdate) {
filteredLabels['arcane.auto-update'] = 'true';
}
- // Prepare healthcheck config if enabled and test command is provided
let healthcheckConfig: HealthConfig | undefined = undefined;
if (enableHealthcheck && healthcheckTest.length > 0 && healthcheckTest[0].trim() !== '') {
- // Convert seconds to nanoseconds for Docker API
const toNano = (seconds: number | undefined) => (seconds ? seconds * 1_000_000_000 : undefined);
-
healthcheckConfig = {
Test: healthcheckTest,
Interval: toNano(healthcheckInterval),
@@ -230,16 +215,15 @@
};
}
- // Parse command override (split by space, respecting quotes if needed - simple split for now)
const commandArray = commandOverride.trim() ? commandOverride.trim().split(/\s+/) : undefined;
- // Parse resource limits
let memoryBytes: number | undefined;
try {
memoryBytes = memoryLimitStr.trim() ? parseBytes(memoryLimitStr.trim()) : undefined;
} catch (e) {
console.error('Invalid memory format:', e);
- return; // Stop submission on invalid format
+ toast.error(`Invalid memory format: ${memoryLimitStr}`);
+ return;
}
let cpuUnits: number | undefined;
@@ -250,7 +234,8 @@
}
} catch (e) {
console.error('Invalid CPU format:', e);
- return; // Stop submission on invalid format
+ toast.error(`Invalid CPU format: ${cpuLimitStr}`);
+ return;
}
const containerConfig: ContainerConfig = {
@@ -276,7 +261,18 @@
cpuLimit: cpuUnits
};
- onSubmit(containerConfig);
+ isCreating = true;
+
+ handleApiReponse(
+ await tryCatch(containerApi.create(containerConfig)),
+ 'Failed to Create Container',
+ (value) => (isCreating = value),
+ async () => {
+ toast.success(`Container "${containerConfig.name}" created successfully!`);
+ await invalidateAll();
+ handleClose();
+ }
+ );
}
</script>
@@ -299,7 +295,7 @@
</Tabs.List>
<div class="p-4 max-h-[60vh] overflow-y-auto">
- <form onsubmit={preventDefault(handleSubmit)} class="space-y-6">
+ <div class="space-y-6">
<!-- Basic Settings -->
<Tabs.Content value="basic">
<div class="space-y-4">
@@ -611,12 +607,12 @@
</div>
</div>
</Tabs.Content>
- </form>
+ </div>
</div>
</Tabs.Root>
<Dialog.Footer class="pt-4">
- <Button variant="outline" onclick={onClose} disabled={isCreating} class="mr-2">Cancel</Button>
+ <Button variant="outline" onclick={handleClose} disabled={isCreating} class="mr-2">Cancel</Button>
<Button type="button" onclick={handleSubmit} disabled={isCreating || !containerName.trim() || !selectedImage}>
{#if isCreating}
<Loader2 class="h-4 w-4 mr-2 animate-spin" /> Creating...
diff --git a/src/routes/images/+page.server.ts b/src/routes/images/+page.server.ts
index 91d67b4ae..89925dc45 100644
--- a/src/routes/images/+page.server.ts
+++ b/src/routes/images/+page.server.ts
@@ -11,7 +11,6 @@ export const load: PageServerLoad = async (): Promise<ImageData> => {
try {
const images = await listImages();
- // Enhance images with usage information
const enhancedImages = await Promise.all(
images.map(async (image): Promise<EnhancedImageInfo> => {
const inUse = await isImageInUse(image.id);
diff --git a/src/routes/images/+page.svelte b/src/routes/images/+page.svelte
index d5c4b7177..887db713e 100644
--- a/src/routes/images/+page.svelte
+++ b/src/routes/images/+page.svelte
@@ -2,46 +2,49 @@
import type { PageData } from './$types';
import type { EnhancedImageInfo } from '$lib/types/docker';
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, Trash2, Loader2, ChevronDown, CopyX } from '@lucide/svelte';
+ import { Download, AlertCircle, HardDrive, Trash2, Loader2, ChevronDown, CopyX, Ellipsis, ScanSearch, Plus } 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 { goto, invalidateAll } from '$app/navigation';
import { toast } from 'svelte-sonner';
import PullImageDialog from './pull-image-dialog.svelte';
- import { formatBytes, cn } from '$lib/utils';
+ import { formatBytes } from '$lib/utils';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import * as Table from '$lib/components/ui/table';
import * as Dialog from '$lib/components/ui/dialog/index.js';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import ImageAPIService from '$lib/services/api/image-api-service';
+ import { handleApiReponse } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
let { data }: { data: PageData } = $props();
let images = $state<EnhancedImageInfo[]>(data.images || []);
let error = $state(data.error);
let selectedIds = $state<string[]>([]);
- let isRefreshing = $state(false);
+ let isLoading = $state({
+ pulling: false,
+ removing: false,
+ refreshing: false,
+ pruning: false
+ });
+
+ const imageApi = new ImageAPIService();
+
let isPullDialogOpen = $state(false);
- let isPullingImage = $state(false);
let pullProgress = $state(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);
async function handlePullImageSubmit(event: { imageRef: string; tag?: string; platform?: string }) {
const { imageRef, tag = 'latest', platform } = event;
- isPullingImage = true;
+ isLoading.pulling = true;
try {
const encodedImageRef = encodeURIComponent(imageRef);
@@ -53,7 +56,7 @@
if (data.error) {
eventSource.close();
toast.error(`Pull failed: ${data.error}`);
- isPullingImage = false;
+ isLoading.pulling = false;
return;
}
@@ -68,9 +71,9 @@
isPullDialogOpen = false;
setTimeout(async () => {
- await refreshData();
+ await invalidateAll();
}, 500);
- isPullingImage = false;
+ isLoading.pulling = false;
}
};
@@ -78,115 +81,130 @@
console.error('EventSource error:', err);
eventSource.close();
toast.error('Connection to server lost while pulling image');
- isPullingImage = false;
+ isLoading.pulling = false;
};
} catch (err: any) {
console.error('Failed to pull image:', err);
toast.error(`Failed to pull image: ${err.message}`);
- isPullingImage = false;
+ isLoading.pulling = false;
}
}
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' };
+ openConfirmDialog({
+ title: 'Delete Selected Images',
+ message: `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.
+`,
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+
+ let successCount = 0;
+ let failureCount = 0;
+
+ for (const id of selectedIds) {
+ const image = images.find((img) => img.id === id);
+ const imageIdentifier = image?.repoTags?.[0] || id.substring(0, 12);
+
+ if (image?.inUse) {
+ toast.error(`Image "${imageIdentifier}" is in use and cannot be deleted.`);
+ failureCount++;
+ continue;
+ }
+
+ const result = await tryCatch(imageApi.remove(id));
+ handleApiReponse(
+ result,
+ `Failed to delete image "${imageIdentifier}"`,
+ (value) => (isLoading.removing = value),
+ async () => {
+ toast.success(`Image "${imageIdentifier}" deleted successfully.`);
+ successCount++;
+ }
+ );
+
+ if (result.error) {
+ failureCount++;
+ }
+ }
+
+ console.log(`Finished deleting. Success: ${successCount}, Failed: ${failureCount}`);
+ if (successCount > 0) {
+ setTimeout(async () => {
+ await invalidateAll();
+ selectedIds = [];
+ }, 500);
+ } else {
+ selectedIds = [];
+ }
}
-
- 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}`);
+ handleApiReponse(
+ await tryCatch(imageApi.prune()),
+ 'Failed to Prune Images',
+ (value) => (isLoading.pruning = value),
+ async (result) => {
+ isConfirmPruneDialogOpen = false;
+ toast.success(result.message);
+ await invalidateAll();
}
-
- 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;
- 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);
+ async function pullImageByRepoTag(repoTag: string | undefined) {
+ if (!repoTag) {
+ toast.error('Cannot pull image without a repository tag');
+ return;
}
+
+ let [imageRef, tag] = repoTag.split(':');
+ tag = tag || 'latest';
+
+ handleApiReponse(
+ await tryCatch(imageApi.pull(imageRef, tag)),
+ `Failed to pull image "${repoTag}"`,
+ (value) => (isLoading.pulling = value),
+ async () => {
+ toast.success(`Image "${repoTag}" pulled successfully.`);
+ await invalidateAll();
+ }
+ );
}
- function openPullDialog() {
- isPullDialogOpen = true;
+ async function handleImageRemove(id: string) {
+ const image = images.find((img) => img.id === id);
+ const imageIdentifier = image?.repoTags?.[0] || id.substring(0, 12);
+
+ openConfirmDialog({
+ title: 'Delete Image',
+ message: `Are you sure you want to delete ${imageIdentifier}? This action cannot be undone.`,
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ handleApiReponse(
+ await tryCatch(imageApi.remove(id)),
+ 'Failed to Remove Image',
+ (value) => (isLoading.removing = value),
+ async () => {
+ toast.success(`Image "${imageIdentifier}" deleted successfully.`);
+ await invalidateAll();
+ }
+ );
+ }
+ }
+ });
}
+
+ $effect(() => {
+ images = data.images;
+ });
</script>
<div class="space-y-6">
@@ -195,26 +213,6 @@
<h1 class="text-3xl font-bold tracking-tight">Docker Images</h1>
<p class="text-sm text-muted-foreground mt-1">Manage your Docker images</p>
</div>
- <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>
{#if error}
@@ -224,7 +222,6 @@
<Alert.Description>{error}</Alert.Description>
</Alert.Root>
{/if}
-
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<Card.Root>
<Card.Content class="p-4 flex items-center justify-between">
@@ -259,13 +256,14 @@
<Card.Title>Image List</Card.Title>
<Card.Description>View and manage your Docker images</Card.Description>
</div>
+
<div class="flex items-center gap-2">
{#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}
+ <Button {...props} variant="outline" disabled={isLoading.removing} aria-label={`Group actions for ${selectedIds.length} selected image(s)`}>
+ {#if isLoading.removing}
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
Processing...
{:else}
@@ -275,21 +273,41 @@
</Button>
{/snippet}
</DropdownMenu.Trigger>
- <DropdownMenu.Content>
- <DropdownMenu.Item onclick={() => (isConfirmDeleteDialogOpen = true)} class="text-red-500 focus:!text-red-700" disabled={isDeletingSelected}>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Item onclick={() => handleDeleteSelected()} class="text-red-500 focus:!text-red-700" disabled={isLoading.removing}>
<Trash2 class="w-4 h-4" />
Delete Selected
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
{/if}
+ <Button variant="secondary" onclick={() => (isConfirmPruneDialogOpen = true)} disabled={isLoading.pruning}>
+ {#if isLoading.pruning}
+ <Loader2 class="w-4 h-4 animate-spin" /> Pruning...
+ {:else}
+ <CopyX class="w-4 h-4" /> Prune Unused
+ {/if}
+ </Button>
+ <Button variant="secondary" onclick={() => (isPullDialogOpen = true)} disabled={isLoading.pulling}>
+ {#if isLoading.pulling}
+ <Loader2 class="w-4 h-4 animate-spin" /> Pulling...
+ {:else}
+ <Download class="w-4 h-4" /> Pull Image
+ {/if}
+ </Button>
</div>
</div>
</Card.Header>
<Card.Content>
<UniversalTable
data={images}
- {columns}
+ columns={[
+ { accessorKey: 'repo', header: 'Name' },
+ { accessorKey: 'tag', header: 'Tag' },
+ { accessorKey: 'id', header: 'Image ID', enableSorting: false },
+ { accessorKey: 'size', header: 'Size' },
+ { accessorKey: 'actions', header: ' ', enableSorting: false }
+ ]}
idKey="id"
display={{
filterPlaceholder: 'Search images...',
@@ -299,7 +317,58 @@
defaultSort: { id: 'repo', desc: false }
}}
bind:selectedIds
- />
+ >
+ {#snippet rows({ item })}
+ <Table.Cell>
+ <div class="flex items-center gap-2">
+ <span class="truncate">
+ <a class="font-medium hover:underline" href="/images/{item.id}/">
+ {item.repo}
+ </a>
+ </span>
+ {#if !item.inUse}
+ <StatusBadge text="Unused" variant="amber" />
+ {/if}
+ </div>
+ </Table.Cell>
+ <Table.Cell>{item.tag}</Table.Cell>
+ <Table.Cell class="truncate">{item.id}</Table.Cell>
+ <Table.Cell>{formatBytes(item.size)}</Table.Cell>
+ <Table.Cell>
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
+ <span class="sr-only">Open menu</span>
+ <Ellipsis />
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <DropdownMenu.Item onclick={() => goto(`/images/${item.id}`)}>
+ <ScanSearch class="h-4 w-4" />
+ Inspect
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => pullImageByRepoTag(item.repoTags?.[0])} disabled={isLoading.pulling || !item.repoTags?.[0]}>
+ {#if isLoading.pulling}
+ <Loader2 class="h-4 w-4 animate-spin" />
+ Pulling...
+ {:else}
+ <Download class="h-4 w-4" />
+ Pull
+ {/if}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item class="text-red-500 focus:!text-red-700" onclick={() => handleImageRemove(item.id)}>
+ <Trash2 class="h-4 w-4" />
+ Remove
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </UniversalTable>
</Card.Content>
</Card.Root>
{:else if !error}
@@ -308,11 +377,7 @@
<p class="text-lg font-medium">No images found</p>
<p class="text-sm text-muted-foreground mt-1 max-w-md">Pull a new image using the "Pull Image" button above or use the Docker CLI</p>
<div class="flex gap-3 mt-4">
- <Button variant="outline" size="sm" onclick={refreshData}>
- <RefreshCw class="h-4 w-4" />
- Refresh
- </Button>
- <Button variant="outline" size="sm" onclick={openPullDialog}>
+ <Button variant="outline" size="sm" onclick={() => (isPullDialogOpen = true)}>
<Download class="h-4 w-4" />
Pull Image
</Button>
@@ -320,28 +385,7 @@
</div>
{/if}
- <PullImageDialog bind:open={isPullDialogOpen} isPulling={isPullingImage} {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>
+ <PullImageDialog bind:open={isPullDialogOpen} isPulling={isLoading.pulling} {pullProgress} onSubmit={handlePullImageSubmit} />
<Dialog.Root bind:open={isConfirmPruneDialogOpen}>
<Dialog.Content>
@@ -350,9 +394,9 @@
<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}
+ <Button variant="outline" onclick={() => (isConfirmPruneDialogOpen = false)} disabled={isLoading.pruning}>Cancel</Button>
+ <Button variant="destructive" onclick={handlePruneImages} disabled={isLoading.pruning}>
+ {#if isLoading.pruning}
<Loader2 class="w-4 h-4 mr-2 animate-spin" /> Pruning...
{:else}
Prune Images
diff --git a/src/routes/images/ImageActions.svelte b/src/routes/images/ImageActions.svelte
deleted file mode 100644
index 6954acc42..000000000
--- a/src/routes/images/ImageActions.svelte
+++ /dev/null
@@ -1,139 +0,0 @@
-<script lang="ts">
- import { Button } from '$lib/components/ui/button/index.js';
- import * as Dialog from '$lib/components/ui/dialog/index.js';
- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
- import { Trash2, Download, Ellipsis, Loader2, ScanSearch } from '@lucide/svelte';
- import { toast } from 'svelte-sonner';
-
- let { id, repoTag, inUse = true }: { id: string; repoTag?: string; inUse: boolean } = $props();
-
- let isPulling = $state(false);
- let isDeleting = $state(false);
- let isConfirmDialogOpen = $state(false);
-
- async function handleDelete() {
- if (inUse) {
- toast.error('Cannot delete image that is in use by containers');
- return;
- }
-
- isDeleting = true;
- try {
- 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}`);
- }
-
- toast.success(`Image ${repoTag || id.substring(0, 12)} deleted successfully.`);
- isConfirmDialogOpen = false;
-
- window.location.href = `${window.location.pathname}?t=${Date.now()}`;
- } catch (err: any) {
- console.error(`Failed to delete image:`, err);
- toast.error(`Failed to delete image: ${err.message}`);
- } finally {
- isDeleting = false;
- }
- }
-
- async function pullImage() {
- if (!repoTag) {
- toast.error('Cannot pull image without a repository tag');
- return;
- }
-
- isPulling = true;
- try {
- let [imageRef, tag] = repoTag.split(':');
- tag = tag || 'latest';
-
- const encodedImageRef = encodeURIComponent(imageRef);
-
- const response = await fetch(`/api/images/pull/${encodedImageRef}`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- tag
- })
- });
-
- if (!response.ok) {
- const result = await response.json();
- throw new Error(result.error || `HTTP error! status: ${response.status}`);
- }
-
- toast.success(`Image "${repoTag}" pulled successfully.`);
-
- window.location.href = `${window.location.pathname}?t=${Date.now()}`;
- } catch (err: any) {
- console.error(`Failed to pull image "${repoTag}":`, err);
- toast.error(`Failed to pull image: ${err.message}`);
- } finally {
- isPulling = false;
- }
- }
- function handleView(id: string) {
- window.location.href = `/images/${id}`;
- }
-</script>
-
-<DropdownMenu.Root>
- <DropdownMenu.Trigger>
- {#snippet child({ props })}
- <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
- <span class="sr-only">Open menu</span>
- <Ellipsis />
- </Button>
- {/snippet}
- </DropdownMenu.Trigger>
- <DropdownMenu.Content>
- <DropdownMenu.Group>
- <DropdownMenu.Item onclick={() => handleView(id)}>
- <ScanSearch class="h-4 w-4" />
- Inspect
- </DropdownMenu.Item>
- <DropdownMenu.Item onclick={pullImage} disabled={isPulling || !repoTag}>
- {#if isPulling}
- <Loader2 class="h-4 w-4 animate-spin" />
- Pulling...
- {:else}
- <Download class="h-4 w-4" />
- Pull
- {/if}
- </DropdownMenu.Item>
- <DropdownMenu.Item class="text-red-500 focus:!text-red-700" onclick={() => (isConfirmDialogOpen = true)}>
- <Trash2 class="h-4 w-4" />
- Remove
- </DropdownMenu.Item>
- </DropdownMenu.Group>
- </DropdownMenu.Content>
-</DropdownMenu.Root>
-
-<Dialog.Root open={isConfirmDialogOpen} onOpenChange={(open) => (isConfirmDialogOpen = open)}>
- <Dialog.Content>
- <Dialog.Header>
- <Dialog.Title>Confirm Deletion</Dialog.Title>
- <Dialog.Description>
- Are you sure you want to delete the image <span class="font-bold">{repoTag || id.substring(0, 12)}</span>? This action cannot be undone.
- </Dialog.Description>
- </Dialog.Header>
- <Dialog.Footer>
- <Button variant="ghost" onclick={() => (isConfirmDialogOpen = false)}>Cancel</Button>
- <Button variant="destructive" onclick={handleDelete} disabled={isDeleting}>
- {#if isDeleting}
- <Loader2 class="h-4 w-4 animate-spin" />
- Deleting...
- {:else}
- Delete
- {/if}
- </Button>
- </Dialog.Footer>
- </Dialog.Content>
-</Dialog.Root>
diff --git a/src/routes/images/[imageId]/+page.server.ts b/src/routes/images/[imageId]/+page.server.ts
index 907da135a..c26a2d4fd 100644
--- a/src/routes/images/[imageId]/+page.server.ts
+++ b/src/routes/images/[imageId]/+page.server.ts
@@ -1,24 +1,20 @@
-import type { PageServerLoad, Actions } from './$types';
-import { getImage, removeImage } from '$lib/services/docker/image-service'; // Import getImage and removeImage
-import { error, fail, redirect } from '@sveltejs/kit';
-import { NotFoundError, ConflictError, DockerApiError } from '$lib/types/errors';
+import type { PageServerLoad } from './$types';
+import { getImage } from '$lib/services/docker/image-service';
+import { error } from '@sveltejs/kit';
+import { NotFoundError } from '$lib/types/errors';
export const load: PageServerLoad = async ({ params }) => {
- const imageId = params.imageId; // Use imageId to match the route parameter
+ const imageId = params.imageId;
try {
const image = await getImage(imageId);
- // Optionally, you could fetch related containers here if needed
- // const containersUsingImage = await getContainersUsingImage(imageId);
-
return {
- image // Return the detailed image info
+ image
};
} catch (err: any) {
console.error(`Failed to load image ${imageId}:`, err);
if (err instanceof NotFoundError) {
- // Use instanceof for custom errors
error(404, { message: err.message });
} else {
error(err.status || 500, {
@@ -27,24 +23,3 @@ export const load: PageServerLoad = async ({ params }) => {
}
}
};
-
-// Add action for removing the image from its details page
-export const actions: Actions = {
- remove: async ({ params, url }) => {
- const imageId = params.imageId;
- const force = url.searchParams.get('force') === 'true'; // Check for force parameter
- try {
- await removeImage(imageId, force);
- // Redirect back to the main images list after successful removal
- redirect(303, '/images');
- } catch (err: any) {
- // Handle specific errors from removeImage
- // Note: image-service removeImage needs updating to throw custom errors
- if (err instanceof NotFoundError || err instanceof ConflictError || err instanceof DockerApiError) {
- return fail(err.status || 409, { error: err.message });
- }
- // Fallback for unexpected errors or generic errors from service
- return fail(500, { error: err.message || 'An unexpected error occurred during removal.' });
- }
- }
-};
diff --git a/src/routes/images/[imageId]/+page.svelte b/src/routes/images/[imageId]/+page.svelte
index 94ddfed65..6c06d6018 100644
--- a/src/routes/images/[imageId]/+page.svelte
+++ b/src/routes/images/[imageId]/+page.svelte
@@ -1,63 +1,56 @@
<script lang="ts">
- import type { PageData, ActionData } from './$types';
+ 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 { ArrowLeft, AlertCircle, RefreshCw, HardDrive, Clock, Tag, Layers, Hash, Trash2, Loader2, Cpu } from '@lucide/svelte';
+ import { ArrowLeft, HardDrive, Clock, Tag, Layers, Hash, Trash2, Loader2, Cpu } from '@lucide/svelte';
import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
- import { enhance } from '$app/forms';
- import { invalidateAll } from '$app/navigation';
- import * as Alert from '$lib/components/ui/alert/index.js';
+ import { goto } from '$app/navigation';
import { Separator } from '$lib/components/ui/separator/index.js';
import { Badge } from '$lib/components/ui/badge/index.js';
import { formatDate, formatBytes } from '$lib/utils';
- import ConfirmDialog from '$lib/components/confirm-dialog.svelte';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import { handleApiReponse } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import ImageAPIService from '$lib/services/api/image-api-service';
+ import { toast } from 'svelte-sonner';
- let { data, form }: { data: PageData; form: ActionData } = $props();
+ let { data }: { data: PageData } = $props();
let { image } = $derived(data);
+ const imageApi = new ImageAPIService();
- let isRefreshing = $state(false);
- let isRemoving = $state(false);
- let showRemoveConfirm = $state(false);
- let forceRemove = $state(false); // State for the force remove checkbox
+ let isLoading = $state({
+ pulling: false,
+ removing: false,
+ refreshing: false
+ });
- // Helper to format the image ID
const shortId = $derived(image?.Id.split(':')[1].substring(0, 12) || 'N/A');
const createdDate = $derived(image?.Created ? formatDate(image.Created) : 'N/A');
const imageSize = $derived(formatBytes(image?.Size || 0));
- // Determine if the image is potentially in use (basic check, more robust check might be needed)
- // A more reliable check would involve fetching containers using this image ID in the load function
- const potentiallyInUse = $derived(false); // Placeholder - Needs data from load function
-
- async function refreshData() {
- isRefreshing = true;
- await invalidateAll();
- setTimeout(() => {
- isRefreshing = false;
- }, 500);
- }
-
- function triggerRemove() {
- forceRemove = false; // Reset force state when opening dialog
- showRemoveConfirm = true;
- }
-
- // This function is called by the ConfirmDialog
- function handleRemoveConfirm(forceConfirm: boolean) {
- forceRemove = forceConfirm; // Set the force state based on checkbox
- // Find the form and submit it
- const removeForm = document.getElementById('remove-image-form') as HTMLFormElement;
- if (removeForm) {
- // Optionally add force parameter to form action or hidden input if needed by server action
- // Since we read from URL in server action, just submit
- removeForm.submit();
- }
+ async function handleImageRemove(id: string) {
+ openConfirmDialog({
+ title: 'Delete Image',
+ message: `Are you sure you want to delete this image? This action cannot be undone.`,
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ handleApiReponse(
+ await tryCatch(imageApi.remove(id)),
+ 'Failed to Remove Image',
+ (value) => (isLoading.removing = value),
+ async () => {
+ toast.success('Image Removed Successfully.');
+ goto('/images');
+ }
+ );
+ }
+ }
+ });
}
</script>
-<!-- Confirmation Dialog for Remove -->
-<ConfirmDialog bind:open={showRemoveConfirm} title="Confirm Image Removal" description={`Are you sure you want to remove image ${shortId}? This action cannot be undone.`} confirmLabel="Remove" variant="destructive" onConfirm={handleRemoveConfirm} itemType={'image'} isRunning={potentiallyInUse} />
-
<div class="space-y-6 pb-8">
<!-- Breadcrumb Navigation -->
<div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">
@@ -77,53 +70,21 @@
<h1 class="text-2xl font-bold tracking-tight break-all">
{image?.RepoTags?.[0] || shortId}
</h1>
- <!-- Add badges for tags if needed -->
</div>
</div>
<div class="flex gap-2 flex-wrap">
- <Button variant="outline" size="sm" onclick={refreshData} disabled={isRefreshing}>
- <RefreshCw class={`h-4 w-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`} /> Refresh
- </Button>
- <!-- Remove Button triggers dialog -->
- <Button variant="destructive" size="sm" onclick={triggerRemove} disabled={isRemoving}>
- {#if isRemoving}
+ <Button variant="destructive" size="sm" onclick={() => handleImageRemove(image.Id)} disabled={isLoading.removing}>
+ {#if isLoading.removing}
<Loader2 class="h-4 w-4 mr-2 animate-spin" />
{:else}
<Trash2 class="h-4 w-4 mr-2" />
{/if} Remove
</Button>
- <!-- Hidden form for removal action -->
- <form
- id="remove-image-form"
- method="POST"
- action="?/remove{forceRemove ? '&force=true' : ''}"
- use:enhance={() => {
- isRemoving = true;
- return async ({ update }) => {
- await update({ reset: false });
- // isRemoving will be reset by effect or on navigation
- };
- }}
- class="hidden"
- >
- <input type="hidden" name="imageId" value={image?.Id} />
- <button type="submit">Submit</button>
- </form>
</div>
</div>
- <!-- Error Alert -->
- {#if form?.error}
- <Alert.Root variant="destructive">
- <AlertCircle class="h-4 w-4 mr-2" />
- <Alert.Title>Action Failed</Alert.Title>
- <Alert.Description>{form.error}</Alert.Description>
- </Alert.Root>
- {/if}
-
{#if image}
- <!-- Image Details Section -->
<div class="space-y-6">
<Card.Root class="border shadow-sm">
<Card.Header>
@@ -224,17 +185,8 @@
</Card.Content>
</Card.Root>
{/if}
-
- <!-- Layers/History (Optional - can be large) -->
- <!-- {#if image.RootFS?.Layers}
- <Card.Root>
- <Card.Header><Card.Title>Layers</Card.Title></Card.Header>
- <Card.Content>...</Card.Content>
- </Card.Root>
- {/if} -->
</div>
{:else}
- <!-- Image Not Found Section -->
<div class="text-center py-12">
<p class="text-lg font-medium text-muted-foreground">Image not found.</p>
<Button href="/images" variant="outline" size="sm" class="mt-4">
diff --git a/src/routes/images/columns.ts b/src/routes/images/columns.ts
deleted file mode 100644
index f0c4b0008..000000000
--- a/src/routes/images/columns.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import type { ServiceImage } from '$lib/types/docker';
-import type { ColumnDef } from '@tanstack/table-core';
-import { renderComponent } from '$lib/components/ui/data-table/index.js';
-import ImageActions from './ImageActions.svelte';
-import { formatBytes } from '$lib/utils';
-import UnusedTextBadge from '$lib/components/badges/unused-text-badge.svelte';
-
-// Enhanced type with usage info
-export type EnhancedImage = ServiceImage & { inUse?: boolean };
-
-export const columns: ColumnDef<EnhancedImage>[] = [
- {
- accessorKey: 'repo',
- header: 'Name',
- cell: ({ row }) => {
- return renderComponent(UnusedTextBadge, {
- name: row.original.repo,
- inUse: row.original.inUse,
- link: `/images/${row.original.id}`
- });
- }
- },
- {
- accessorKey: 'tag',
- header: 'Tag',
- cell: ({ row }) => {
- return row.original.tag;
- }
- },
- {
- accessorKey: 'id',
- header: 'Image ID',
- cell: ({ row }) => {
- const shortId = row.original.id.split(':')[1]?.substring(0, 12) || row.original.id.substring(0, 12);
- return shortId;
- },
- enableSorting: false
- },
- {
- accessorKey: 'size',
- header: 'Size',
- cell: ({ row }) => {
- return formatBytes(row.original.size);
- }
- },
- {
- id: 'actions',
- header: '',
- cell: ({ row }) => {
- return renderComponent(ImageActions, {
- id: row.original.id,
- repoTag: row.original.repoTags?.[0],
- inUse: !!row.original.inUse
- });
- },
- enableSorting: false
- }
-];
diff --git a/src/routes/images/pull-image-dialog.svelte b/src/routes/images/pull-image-dialog.svelte
index 67cc1fb88..c5ba17dc1 100644
--- a/src/routes/images/pull-image-dialog.svelte
+++ b/src/routes/images/pull-image-dialog.svelte
@@ -62,8 +62,8 @@
<Dialog.Root bind:open>
<Dialog.Content class="sm:max-w-[500px]">
- <Dialog.Header>
- <Dialog.Title>Pull Docker Image</Dialog.Title>
+ <Dialog.Header data-testid="pull-docker-image-header">
+ <Dialog.Title data-testid="pull-docker-image-header">Pull Docker Image</Dialog.Title>
<Dialog.Description>Enter the image reference you want to pull from a registry.</Dialog.Description>
</Dialog.Header>
diff --git a/src/routes/networks/+page.svelte b/src/routes/networks/+page.svelte
index ee0215c79..c2c884580 100644
--- a/src/routes/networks/+page.svelte
+++ b/src/routes/networks/+page.svelte
@@ -1,125 +1,145 @@
<script lang="ts">
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
- import { Plus, AlertCircle, Network, RefreshCw, Trash2, Loader2, ChevronDown } from '@lucide/svelte';
+ import { Plus, AlertCircle, Network, Trash2, Loader2, ChevronDown, ScanSearch, Ellipsis } 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 { goto, 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 * as Table from '$lib/components/ui/table';
import type { NetworkCreateOptions } from 'dockerode';
+ import { handleApiReponse } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import NetworkAPIService from '$lib/services/api/network-api-service';
let { data }: { data: PageData } = $props();
- 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);
+ let networkPageStates = $state({
+ networks: data.networks,
+ selectedNetworks: <string[]>[],
+ error: data.error,
+ isCreateDialogOpen: false
+ });
- $effect(() => {
- networks = data.networks;
- error = data.error;
+ let isLoading = $state({
+ create: false,
+ remove: false,
+ refresh: false
});
- const totalNetworks = $derived(networks?.length || 0);
- const bridgeNetworks = $derived(networks?.filter((n) => n.driver === 'bridge').length || 0);
- const overlayNetworks = $derived(networks?.filter((n) => n.driver === 'overlay').length || 0);
+ const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
- function openCreateDialog() {
- isCreateDialogOpen = true;
- }
+ $effect(() => {
+ networkPageStates.networks = data.networks;
+ networkPageStates.error = data.error;
+ });
- 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 totalNetworks = $derived(networkPageStates.networks.length);
+ const bridgeNetworks = $derived(networkPageStates.networks.filter((n) => n.driver === 'bridge').length);
+ const overlayNetworks = $derived(networkPageStates.networks.filter((n) => n.driver === 'overlay').length);
- const result = await response.json();
+ const networkApi = new NetworkAPIService();
- if (!response.ok) {
- throw new Error(result.message || `HTTP error! status: ${response.status}`);
+ async function handleCreateNetworkSubmit(options: NetworkCreateOptions) {
+ handleApiReponse(
+ await tryCatch(networkApi.create(options)),
+ 'Failed to Create Network',
+ (value) => (isLoading.create = value),
+ async () => {
+ toast.success('Network Created Successfully.');
+ await invalidateAll();
+ networkPageStates.isCreateDialogOpen = false;
}
-
- 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;
- 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 handleDeleteNetwork(id: string) {
+ openConfirmDialog({
+ title: 'Delete Network',
+ message: 'Are you sure you want to delete this network? This action cannot be undone.',
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ handleApiReponse(
+ await tryCatch(networkApi.remove(encodeURIComponent(id))),
+ 'Failed to Remove Container',
+ (value) => (isLoading.remove = value),
+ async () => {
+ toast.success('Network Removed Successfully.');
+ await invalidateAll();
+ }
+ );
+ }
+ }
+ });
}
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 };
- }
+ // Check if any selected networks are default networks
+ const selectedNetworks = networkPageStates.selectedNetworks.map((id) => {
+ const network = networkPageStates.networks.find((n) => n.id === id);
+ return {
+ id,
+ name: network?.name || id.substring(0, 12),
+ isDefault: network?.driver === 'host' || network?.name === 'bridge' || network?.name === 'none'
+ };
});
- const results = await Promise.all(deletePromises);
- const successfulDeletes = results.filter((r) => r.success);
- const failedDeletes = results.filter((r) => !r.success);
+ const defaultNetworks = selectedNetworks.filter((n) => n.isDefault);
- if (successfulDeletes.length > 0) {
- toast.success(`Successfully deleted ${successfulDeletes.length} network(s).`);
- setTimeout(async () => {
- await refreshData();
- selectedIds = [];
- }, 500);
+ if (defaultNetworks.length > 0) {
+ const names = defaultNetworks.map((n) => n.name).join(', ');
+ toast.error(`Cannot delete default networks: ${names}`);
+ return;
}
- failedDeletes.forEach((r) => {
- toast.error(`Failed to delete network "${r.name}": ${r.error}`);
- });
+ openConfirmDialog({
+ title: 'Delete Selected Networks',
+ message: `Are you sure you want to delete ${networkPageStates.selectedNetworks.length} selected network(s)? This action cannot be undone. Networks currently in use by containers cannot be deleted.`,
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ isLoading.remove = true;
+
+ let successCount = 0;
+ let failureCount = 0;
+
+ for (const network of selectedNetworks) {
+ const result = await tryCatch(networkApi.remove(encodeURIComponent(network.id)));
+ handleApiReponse(
+ result,
+ `Failed to delete network "${network.name}"`,
+ (value) => (isLoading.remove = value),
+ async () => {
+ toast.success(`Network "${network.name}" deleted successfully.`);
+ successCount++;
+ }
+ );
- isDeletingSelected = false;
- isConfirmDeleteDialogOpen = false;
+ if (result.error) {
+ failureCount++;
+ }
+ }
+
+ console.log(`Finished deleting. Success: ${successCount}, Failed: ${failureCount}`);
+ if (successCount > 0) {
+ setTimeout(async () => {
+ await invalidateAll();
+ networkPageStates.selectedNetworks = [];
+ }, 500);
+ } else {
+ networkPageStates.selectedNetworks = [];
+ }
+ }
+ }
+ });
}
</script>
@@ -130,22 +150,18 @@
<p class="text-sm text-muted-foreground mt-1">Manage Docker container networking</p>
</div>
<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}>
+ <Button variant="secondary" data-testid="create-network-button" onclick={() => (networkPageStates.isCreateDialogOpen = true)} disabled={isLoading.create}>
<Plus class="w-4 h-4" />
Create Network
</Button>
</div>
</div>
- {#if error}
+ {#if networkPageStates.error}
<Alert.Root variant="destructive">
<AlertCircle class="h-4 w-4 mr-2" />
<Alert.Title>Error Loading Networks</Alert.Title>
- <Alert.Description>{error}</Alert.Description>
+ <Alert.Description>{networkPageStates.error}</Alert.Description>
</Alert.Root>
{/if}
@@ -195,23 +211,23 @@
<Card.Description>Manage container communication</Card.Description>
</div>
<div class="flex items-center gap-2">
- {#if selectedIds.length > 0}
+ {#if networkPageStates.selectedNetworks.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}
+ <Button {...props} variant="outline" size="sm" disabled={isLoading.remove} aria-label={`Group actions for ${networkPageStates.selectedNetworks.length} selected network(s)`}>
+ {#if isLoading.remove}
<Loader2 class="w-4 h-4 animate-spin" />
Processing...
{:else}
- Actions ({selectedIds.length})
+ Actions ({networkPageStates.selectedNetworks.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}>
+ <DropdownMenu.Item onclick={() => handleDeleteSelected()} class="text-red-500 focus:!text-red-700" disabled={isLoading.remove}>
<Trash2 class="w-4 h-4" />
Delete Selected
</DropdownMenu.Item>
@@ -222,10 +238,16 @@
</div>
</Card.Header>
<Card.Content>
- {#if networks && networks.length > 0}
+ {#if networkPageStates.networks && networkPageStates.networks.length > 0}
<UniversalTable
- data={networks}
- {columns}
+ data={networkPageStates.networks}
+ columns={[
+ { accessorKey: 'name', header: 'Name' },
+ { accessorKey: 'driver', header: 'Driver' },
+ { accessorKey: 'scope', header: 'Scope' },
+ { accessorKey: 'subnet', header: 'Subnet' },
+ { accessorKey: 'actions', header: ' ', enableSorting: false }
+ ]}
idKey="id"
display={{
filterPlaceholder: 'Search networks...',
@@ -234,19 +256,55 @@
sort={{
defaultSort: { id: 'name', desc: false }
}}
- bind:selectedIds
- />
- {:else if !error}
+ bind:selectedIds={networkPageStates.selectedNetworks}
+ >
+ {#snippet rows({ item })}
+ {@const isDefaultNetwork = item.driver === 'host' || item.name === 'bridge' || item.name === 'none'}
+ <Table.Cell><a class="font-medium hover:underline" href="/networks/{item.id}/">{item.name}</a></Table.Cell>
+ <Table.Cell>{item.driver}</Table.Cell>
+ <Table.Cell>{item.scope}</Table.Cell>
+ <Table.Cell>{item.subnet}</Table.Cell>
+ <Table.Cell>
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
+ <span class="sr-only">Open menu</span>
+ <Ellipsis />
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <DropdownMenu.Item onclick={() => goto(`/networks/${item.id}`)} disabled={isAnyLoading}>
+ <ScanSearch class="w-4 h-4" />
+ Inspect
+ </DropdownMenu.Item>
+ {#if !isDefaultNetwork}
+ <DropdownMenu.Separator />
+
+ <DropdownMenu.Item class="text-red-500 focus:!text-red-700" onclick={() => handleDeleteNetwork(item.id)} disabled={isLoading.remove || isAnyLoading}>
+ {#if isLoading.remove}
+ <Loader2 class="w-4 h-4 animate-spin" />
+ {:else}
+ <Trash2 class="w-4 h-4" />
+ {/if}
+ Remove
+ </DropdownMenu.Item>
+ {/if}
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </UniversalTable>
+ {:else if !networkPageStates.error}
<div class="flex flex-col items-center justify-center py-12 px-6 text-center">
<Network class="h-12 w-12 text-muted-foreground mb-4 opacity-40" />
<p class="text-lg font-medium">No networks found</p>
<p class="text-sm text-muted-foreground mt-1 max-w-md">Create a new network using the "Create Network" button above or use the Docker CLI</p>
<div class="flex gap-3 mt-4">
- <Button variant="outline" size="sm" onclick={refreshData}>
- <RefreshCw class="h-4 w-4" />
- Refresh
- </Button>
- <Button variant="outline" size="sm" onclick={openCreateDialog}>
+ <Button variant="outline" size="sm" onclick={() => (networkPageStates.isCreateDialogOpen = true)}>
<Plus class="h-4 w-4" />
Create Network
</Button>
@@ -256,26 +314,5 @@
</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>
+ <CreateNetworkDialog bind:open={networkPageStates.isCreateDialogOpen} isCreating={isLoading.create} onSubmit={handleCreateNetworkSubmit} />
</div>
diff --git a/src/routes/networks/CreateNetworkDialog.svelte b/src/routes/networks/CreateNetworkDialog.svelte
index 7fc97512c..dd81a5372 100644
--- a/src/routes/networks/CreateNetworkDialog.svelte
+++ b/src/routes/networks/CreateNetworkDialog.svelte
@@ -98,7 +98,7 @@
<Dialog.Root bind:open>
<Dialog.Content class="sm:max-w-[600px]">
<Dialog.Header>
- <Dialog.Title>Create Network</Dialog.Title>
+ <Dialog.Title data-testid="create-network-dialog-header">Create Network</Dialog.Title>
<Dialog.Description>Configure and create a new Docker network.</Dialog.Description>
</Dialog.Header>
diff --git a/src/routes/networks/NetworkActions.svelte b/src/routes/networks/NetworkActions.svelte
deleted file mode 100644
index fe5899f61..000000000
--- a/src/routes/networks/NetworkActions.svelte
+++ /dev/null
@@ -1,83 +0,0 @@
-<script lang="ts">
- import { Button } from '$lib/components/ui/button/index.js';
- 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;
- name: string;
- }
-
- let { id, name }: Props = $props();
-
- 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) {
- console.error(`Failed to delete network ${id}:`, err);
- const message = err instanceof Error ? err.message : String(err); // Get message safely
- toast.error(`Failed to delete network "${name}": ${message}`);
- // Keep dialog open on error? Optional.
- // isConfirmDeleteDialogOpen = false;
- } finally {
- isDeleting = false;
- }
- }
-</script>
-
-{#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
deleted file mode 100644
index d44e182d2..000000000
--- a/src/routes/networks/SubnetCell.svelte
+++ /dev/null
@@ -1,14 +0,0 @@
-<!-- filepath: /Users/kylemendell/dev/ofkm/arcane/src/routes/networks/SubnetCell.svelte -->
-<script lang="ts">
- interface Props {
- subnet: string | null;
- }
-
- let { subnet }: Props = $props();
-</script>
-
-{#if subnet}
- <span class="font-mono text-xs">{subnet}</span>
-{:else}
- <span>N/A</span>
-{/if}
diff --git a/src/routes/networks/[networkId]/+page.svelte b/src/routes/networks/[networkId]/+page.svelte
index 28f6b5986..bb301eed5 100644
--- a/src/routes/networks/[networkId]/+page.svelte
+++ b/src/routes/networks/[networkId]/+page.svelte
@@ -9,8 +9,8 @@
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 { formatDate } from '$lib/utils'; // #file:/Users/kylemendell/dev/ofkm/arcane/src/lib/utils.ts
- import ConfirmDialog from '$lib/components/confirm-dialog.svelte'; // #file:/Users/kylemendell/dev/ofkm/arcane/src/lib/components/confirm-dialog.svelte
+ import { formatDate } from '$lib/utils';
+ // import ConfirmDialog from '$lib/components/confirm-dialog/confirm-dialog-old.svelte';
import type { NetworkInspectInfo } from 'dockerode';
let { data, form }: { data: PageData; form: ActionData } = $props();
@@ -57,7 +57,7 @@
</script>
<!-- Confirmation Dialog for Remove -->
-<ConfirmDialog bind:open={showRemoveConfirm} title="Confirm Network Removal" description={`Are you sure you want to remove network "${network?.Name}" (${shortId})? This action cannot be undone. Ensure no containers are connected.`} confirmLabel="Remove" variant="destructive" onConfirm={handleRemoveConfirm} itemType="network" isRunning={inUse} />
+<!-- <ConfirmDialog bind:open={showRemoveConfirm} title="Confirm Network Removal" description={`Are you sure you want to remove network "${network?.Name}" (${shortId})? This action cannot be undone. Ensure no containers are connected.`} confirmLabel="Remove" variant="destructive" onConfirm={handleRemoveConfirm} itemType="network" isRunning={inUse} /> -->
<div class="space-y-6 pb-8">
<!-- Breadcrumb Navigation -->
@@ -88,9 +88,6 @@
</div>
<div class="flex gap-2 flex-wrap">
- <Button variant="outline" size="sm" onclick={refreshData} disabled={isRefreshing}>
- <RefreshCw class={`h-4 w-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`} /> Refresh
- </Button>
<!-- Remove Button triggers dialog -->
<Button variant="destructive" size="sm" onclick={triggerRemove} disabled={isRemoving || isPredefined} title={isPredefined ? 'Cannot remove predefined networks' : ''}>
{#if isRemoving}
diff --git a/src/routes/networks/columns.ts b/src/routes/networks/columns.ts
deleted file mode 100644
index 9ffc07486..000000000
--- a/src/routes/networks/columns.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import type { ColumnDef } from '@tanstack/table-core';
-import { renderComponent } from '$lib/components/ui/data-table/index.js';
-import NetworkActions from './NetworkActions.svelte';
-import SubnetCell from './SubnetCell.svelte';
-import type { ServiceNetwork } from '$lib/types/docker';
-import NameCell from '$lib/components/badges/name-cell.svelte';
-
-// Use the ServiceNetwork type directly
-export type NetworkInfo = ServiceNetwork;
-
-export const columns: ColumnDef<NetworkInfo>[] = [
- {
- accessorKey: 'name',
- header: 'Name',
- cell: ({ row }) => {
- return renderComponent(NameCell, { name: row.original.name, link: `/networks/${row.original.id}` });
- }
- },
- {
- accessorKey: 'driver',
- header: 'Driver'
- },
- {
- accessorKey: 'scope',
- header: 'Scope'
- },
- {
- accessorKey: 'subnet',
- header: 'Subnet',
- cell: ({ row }) => {
- return renderComponent(SubnetCell, { subnet: row.original.subnet });
- }
- },
- // Optional: Add Gateway column if needed
- // {
- // accessorKey: "gateway",
- // header: "Gateway",
- // cell: ({ row }) => row.original.gateway ?? 'N/A'
- // },
- // Optional: Add Created column if needed
- // {
- // accessorKey: "created",
- // header: "Created",
- // cell: ({ row }) => new Date(row.original.created).toLocaleString() // Format date
- // },
- {
- id: 'actions',
- header: '',
- cell: ({ row }) => {
- return renderComponent(NetworkActions, {
- id: row.original.id, // Pass the actual ID
- name: row.original.name
- });
- },
- enableSorting: false
- }
-];
diff --git a/src/routes/settings/+page.svelte b/src/routes/settings/+page.svelte
index 13761a368..39693c28d 100644
--- a/src/routes/settings/+page.svelte
+++ b/src/routes/settings/+page.svelte
@@ -9,6 +9,8 @@
import UserManagement from './tabs/user-management.svelte';
import Authentication from './tabs/authentication.svelte';
import { saveSettingsToServer, updateSettingsStore } from '$lib/stores/settings-store';
+ import { handleApiReponse } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
let { data } = $props<{ data: PageData }>();
@@ -18,9 +20,15 @@
}
});
- let activeTab = $state('app-settings');
- let saving = $state(false);
- let error = $state<string | null>(null);
+ let settingsPageStates = $state({
+ start: false,
+ error: <string | null>null,
+ activeTab: 'app-settings'
+ });
+
+ let isLoading = $state({
+ saving: false
+ });
const tabs = [
{ id: 'app-settings', label: 'General', component: AppSettings },
@@ -29,21 +37,19 @@
];
async function saveSettings() {
- if (saving) return;
- saving = true;
- error = null;
+ if (isLoading.saving) return;
+ isLoading.saving = true;
+ settingsPageStates.error = null;
- try {
- await saveSettingsToServer();
- toast.success('Settings saved successfully');
- await invalidateAll();
- } catch (err: unknown) {
- console.error('Error saving settings:', err);
- error = err instanceof Error ? err.message : 'An error occurred while saving settings';
- if (error) toast.error(error);
- } finally {
- saving = false;
- }
+ handleApiReponse(
+ await tryCatch(saveSettingsToServer()),
+ 'Error Saving Settings',
+ (value) => (isLoading.saving = value),
+ async () => {
+ toast.success(`Settings Saved Successfully`);
+ await invalidateAll();
+ }
+ );
}
</script>
@@ -54,8 +60,8 @@
<p class="text-sm text-muted-foreground mt-1">Configure Arcane's settings and permissions</p>
</div>
- <Button onclick={saveSettings} disabled={saving} class="h-10">
- {#if saving}
+ <Button onclick={saveSettings} disabled={isLoading.saving} class="h-10">
+ {#if isLoading.saving}
<RefreshCw class="mr-2 h-4 w-4 animate-spin" />
Saving...
{:else}
@@ -65,7 +71,7 @@
</Button>
</div>
- <Tabs.Root value={activeTab} onValueChange={(val) => (activeTab = val)} class="w-full">
+ <Tabs.Root value={settingsPageStates.activeTab} onValueChange={(val) => (settingsPageStates.activeTab = val)} class="w-full">
<Tabs.List class="grid grid-cols-3 md:w-full md:max-w-3xl mb-4">
{#each tabs as tab, i (tab.id)}
<Tabs.Trigger value={tab.id} class="whitespace-nowrap">
diff --git a/src/routes/settings/tabs/user-management.svelte b/src/routes/settings/tabs/user-management.svelte
index a2191bd59..9b6fdd41c 100644
--- a/src/routes/settings/tabs/user-management.svelte
+++ b/src/routes/settings/tabs/user-management.svelte
@@ -2,141 +2,95 @@
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 { UserPlus, UserCheck } from '@lucide/svelte';
+ import { UserPlus, UserCheck, Ellipsis, Pencil, UserX, Mail } from '@lucide/svelte';
import type { PageData } from '../$types';
- import type { UniversalTableProps } from '$lib/types/table-types';
import UniversalTable from '$lib/components/universal-table.svelte';
- import { userTableColumns } from '$lib/types/table-columns/user-table-columns';
import type { User } from '$lib/types/user.type';
import UserFormDialog from '$lib/components/dialogs/user-form-dialog.svelte';
+ import * as Table from '$lib/components/ui/table';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import { handleApiReponse } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import UserAPIService from '$lib/services/api/user-api-service';
+ import { invalidateAll } from '$app/navigation';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
- // Get data from server
let { data } = $props<{ data: PageData }>();
- let users = $state<User[]>(data.users || []);
+ const userApi = new UserAPIService();
- $effect(() => {
- users = data.users || [];
+ let userPageStates = $state({
+ users: <User[]>data.users,
+ isUserDialogOpen: false,
+ userToEdit: <User | null>null
+ });
+
+ let isLoading = $state({
+ saving: false
});
- // Dialog state
- let isUserDialogOpen = $state(false);
- let userToEdit = $state<User | null>(null);
let userDialogRef: UserFormDialog | null = $state(null);
- // Available roles
+ $effect(() => {
+ userPageStates.users = data.users;
+ });
+
const roles = [
{ id: 'admin', name: 'Administrator' },
{ id: 'user', name: 'Standard User' },
{ id: 'viewer', name: 'Viewer (read-only)' }
];
- // Function to open dialog for creating
function openCreateUserDialog() {
- userToEdit = null;
- isUserDialogOpen = true;
+ userPageStates.userToEdit = null;
+ userPageStates.isUserDialogOpen = true;
}
- // Function to open dialog for editing
function openEditUserDialog(user: User) {
- userToEdit = user;
- isUserDialogOpen = true;
+ userPageStates.userToEdit = user;
+ userPageStates.isUserDialogOpen = true;
}
- // Handle submission from the dialog
- async function handleDialogSubmit(event: CustomEvent) {
- const { user: userData, isEditMode, userId } = event.detail;
-
- const url = isEditMode ? `/api/users/${userId}` : '/api/users';
- const method = isEditMode ? 'PUT' : 'POST';
-
- try {
- const response = await fetch(url, {
- method: method,
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(userData)
- });
-
- const result = await response.json();
-
- if (response.ok) {
- if (isEditMode) {
- users = users.map((u) => (u.id === userId ? { ...u, ...result.user } : u));
- toast.success('User updated successfully');
- } else {
- users = [...users, result.user];
- toast.success('User created successfully');
- }
- isUserDialogOpen = false;
- } else {
- userDialogRef?.setSaveError(result.error || `Failed to ${isEditMode ? 'update' : 'create'} user`);
+ async function handleDialogSubmit({ user: userData, isEditMode, userId }: { user: Partial<User> & { password?: string }; isEditMode: boolean; userId?: string }) {
+ isLoading.saving = true;
+
+ handleApiReponse(
+ await tryCatch(isEditMode ? userApi.update(userId || '', userData as User) : userApi.create(userData as User)),
+ isEditMode ? 'Error Updating User' : 'Error Creating User',
+ (value) => (isLoading.saving = value),
+ async () => {
+ userPageStates.isUserDialogOpen = false;
+ toast.success(isEditMode ? 'User Updated Successfully' : 'User Created Successfully');
+ await invalidateAll();
}
- } catch (error) {
- console.error(`Error ${isEditMode ? 'updating' : 'creating'} user:`, error);
- userDialogRef?.setSaveError(`An unexpected error occurred.`);
- } finally {
- userDialogRef?.resetSavingState();
- }
+ );
}
- // Handle user removal via API
- async function handleRemoveUser(userId: string, username: string) {
- if (!confirm(`Are you sure you want to remove user "${username}"?`)) {
- return;
- }
-
- try {
- const response = await fetch(`/api/users/${userId}`, {
- method: 'DELETE'
- });
-
- if (response.ok) {
- users = users.filter((user) => user.id !== userId);
- toast.success(`User ${username} removed successfully`);
- } else {
- const result = await response.json();
- toast.error(result.error || 'Failed to remove user');
+ async function handleRemoveUser(userId: string) {
+ openConfirmDialog({
+ title: 'Delete Container',
+ message: 'Are you sure you want to delete this container? This action cannot be undone.',
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ handleApiReponse(
+ await tryCatch(userApi.delete(userId)),
+ 'Failed to Delete User',
+ (value) => (isLoading.saving = value),
+ async () => {
+ toast.success('User Deleted Successfully.');
+ await invalidateAll();
+ }
+ );
+ }
}
- } catch (error) {
- console.error('Error removing user:', error);
- toast.error('An unexpected error occurred');
- }
+ });
}
-
- // Configure the table columns, passing edit handler
- const columns = userTableColumns(handleRemoveUser, openEditUserDialog);
-
- // Create table props
- const tableProps: UniversalTableProps<User> = {
- columns,
- get data() {
- return users;
- },
- features: {
- sorting: true,
- filtering: true,
- selection: false
- },
- display: {
- filterPlaceholder: 'Filter users...',
- noResultsMessage: 'No users found'
- },
- pagination: {
- pageSize: 10,
- pageSizeOptions: [5, 10, 15, 20]
- },
- sort: {
- defaultSort: {
- id: 'user',
- desc: false
- }
- }
- };
</script>
-<UserFormDialog bind:open={isUserDialogOpen} bind:userToEdit {roles} on:submit={handleDialogSubmit} bind:this={userDialogRef} />
+<UserFormDialog bind:open={userPageStates.isUserDialogOpen} bind:userToEdit={userPageStates.userToEdit} {roles} onSubmit={handleDialogSubmit} bind:this={userDialogRef} />
<div class="grid grid-cols-1 gap-6 h-full">
<!-- User List Card -->
@@ -151,16 +105,84 @@
<Card.Description>Manage local user accounts</Card.Description>
</div>
</div>
- <!-- Add Create User Button -->
<Button size="sm" onclick={openCreateUserDialog}>
<UserPlus class="mr-2 h-4 w-4" />
Create User
</Button>
</Card.Header>
<Card.Content class="flex-1 flex flex-col">
- {#if users.length > 0}
+ {#if userPageStates.users.length > 0}
<div class="flex-1 flex flex-col h-full">
- <UniversalTable {...tableProps} />
+ <UniversalTable
+ data={userPageStates.users}
+ columns={[
+ { accessorKey: 'user', header: 'User' },
+ { accessorKey: 'email', header: 'Email' },
+ { accessorKey: 'roles', header: 'Roles' },
+ { accessorKey: 'actions', header: ' ' }
+ ]}
+ features={{
+ sorting: true,
+ filtering: true,
+ selection: false
+ }}
+ pagination={{
+ pageSize: 10,
+ pageSizeOptions: [5, 10, 15, 20]
+ }}
+ display={{
+ filterPlaceholder: 'Filter users...',
+ noResultsMessage: 'No users found'
+ }}
+ sort={{
+ defaultSort: {
+ id: 'user',
+ desc: false
+ }
+ }}
+ >
+ {#snippet rows({ item })}
+ <Table.Cell>
+ {item.displayName}
+ </Table.Cell>
+ <Table.Cell>
+ <div class="flex items-center gap-1.5">
+ <Mail class="h-3.5 w-3.5 text-muted-foreground" />
+ {item.email}
+ </div>
+ </Table.Cell>
+ <Table.Cell>
+ <div class="flex flex-wrap">
+ {#each item.roles as role (role)}
+ {@const isAdmin = role === 'admin'}
+ <StatusBadge text={isAdmin ? 'Admin' : 'User'} variant={isAdmin ? 'amber' : 'blue'} />
+ {/each}
+ </div>
+ </Table.Cell>
+ <Table.Cell>
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ <Button variant="ghost" size="icon" class="h-8 w-8">
+ <Ellipsis class="h-4 w-4" />
+ <span class="sr-only">Open menu</span>
+ </Button>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <DropdownMenu.Item onclick={() => openEditUserDialog(item)}>
+ <Pencil class="h-4 w-4" />
+ Edit
+ </DropdownMenu.Item>
+ <DropdownMenu.Item class="text-red-500 focus:!text-red-700" onclick={() => handleRemoveUser(item.id)}>
+ <UserX class="h-4 w-4" />
+ Remove User
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </UniversalTable>
</div>
{:else}
<div class="text-center py-8 text-muted-foreground italic">No local users found</div>
diff --git a/src/routes/stacks/+page.svelte b/src/routes/stacks/+page.svelte
index b0c82aa81..e9de1527d 100644
--- a/src/routes/stacks/+page.svelte
+++ b/src/routes/stacks/+page.svelte
@@ -2,65 +2,135 @@
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 { Plus, AlertCircle, Layers, RefreshCw, Upload, FileStack } from '@lucide/svelte';
+ import { Plus, AlertCircle, Layers, Upload, FileStack, Loader2, Play, RotateCcw, StopCircle, Trash2, Ellipsis, Pen, Import } from '@lucide/svelte';
import UniversalTable from '$lib/components/universal-table.svelte';
- import { columns } from './columns';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import * as Table from '$lib/components/ui/table';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
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';
+ import { goto, invalidateAll } from '$app/navigation';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { capitalizeFirstLetter } from '$lib/utils/string.utils';
+ import { statusVariantMap } from '$lib/types/statuses';
+ import { toast } from 'svelte-sonner';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import StackAPIService from '$lib/services/api/stack-api-service';
+ import { handleApiReponse } from '$lib/utils/api.util';
+ import type { StackActions } from '$lib/types/actions.type';
let { data }: { data: PageData } = $props();
- let { error } = data;
let stacks = $state(data.stacks);
let selectedIds = $state([]);
-
let isRefreshing = $state(false);
- let id = $state('');
-
- let dialogOpen = $state(false);
- let dialogProps = $state({
- type: 'info' as const,
- title: '',
- message: '',
- okText: 'OK',
- cancelText: 'Cancel',
- showCancel: false
+ let isLoading = $state({
+ start: false,
+ stop: false,
+ restart: false,
+ remove: false,
+ import: false,
+ redeploy: false,
+ destroy: false,
+ pull: false
});
+ const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
- let modalOpen = $state(false);
- let modalProps = $state({
- type: 'info' as 'info' | 'success' | 'error',
- title: '',
- message: ''
- });
+ const stackApi = new StackAPIService();
const totalStacks = $derived(stacks?.length || 0);
const runningStacks = $derived(stacks?.filter((s) => s.status === 'running').length || 0);
const partialStacks = $derived(stacks?.filter((s) => s.status === 'partially running').length || 0);
- function createStack() {
- window.location.href = '/stacks/new';
- }
+ async function performStackAction(action: StackActions, id: string) {
+ isLoading[action] = true;
- async function importStack() {
- dialogOpen = true;
- dialogProps = {
- type: 'info',
- title: 'Import Stack',
- message: 'This feature is not yet implemented. Check back soon!',
- okText: 'Close',
- cancelText: 'Cancel',
- showCancel: false
- };
+ if (action === 'start') {
+ handleApiReponse(
+ await tryCatch(stackApi.start(id)),
+ 'Failed to Start Stack',
+ (value) => (isLoading.start = value),
+ async () => {
+ toast.success('Stack Started Successfully.');
+ await invalidateAll();
+ }
+ );
+ } else if (action === 'stop') {
+ handleApiReponse(
+ await tryCatch(stackApi.stop(id)),
+ 'Failed to Stop Stack',
+ (value) => (isLoading.stop = value),
+ async () => {
+ toast.success('Stack Stopped Successfully.');
+ await invalidateAll();
+ }
+ );
+ } else if (action === 'restart') {
+ handleApiReponse(
+ await tryCatch(stackApi.restart(id)),
+ 'Failed to Restart Stack',
+ (value) => (isLoading.restart = value),
+ async () => {
+ toast.success('Stack Restarted Successfully.');
+ await invalidateAll();
+ }
+ );
+ } else if (action === 'redeploy') {
+ handleApiReponse(
+ await tryCatch(stackApi.redeploy(id)),
+ 'Failed to Redeploy Stack',
+ (value) => (isLoading.redeploy = value),
+ async () => {
+ toast.success('Stack redeployed successfully.');
+ await invalidateAll();
+ }
+ );
+ } else if (action === 'pull') {
+ handleApiReponse(
+ await tryCatch(stackApi.pull(id)),
+ 'Failed to pull Stack',
+ (value) => (isLoading.pull = value),
+ async () => {
+ toast.success('Stack Pulled successfully.');
+ await invalidateAll();
+ }
+ );
+ } else if (action === 'destroy') {
+ openConfirmDialog({
+ title: `Confirm Removal`,
+ message: `Are you sure you want to remove this Stack? This action cannot be undone.`,
+ confirm: {
+ label: 'Remove',
+ destructive: true,
+ action: async () => {
+ handleApiReponse(
+ await tryCatch(stackApi.remove(id)),
+ 'Failed to Remove Stack',
+ (value) => (isLoading.destroy = value),
+ async () => {
+ toast.success('Stack Removed Successfully');
+ await invalidateAll();
+ }
+ );
+ }
+ }
+ });
+ } else {
+ console.error('An Unknown Error Occurred');
+ toast.error('An Unknown Error Occurred');
+ }
}
- async function refreshData() {
- isRefreshing = true;
+ async function handleImportStack(id: string, name: string) {
+ isLoading['import'] = true;
+ const result = await tryCatch(stackApi.import(id, name));
+ if (result.error) {
+ console.error(`Failed to import Stack ${id}:`, result.error);
+ toast.error(`Failed to import Stack: ${result.error.message}`);
+ isLoading['import'] = false;
+ return;
+ }
+ toast.success('Stack Imported successfully.');
await invalidateAll();
- setTimeout(() => {
- isRefreshing = false;
- }, 500);
+ isLoading['import'] = false;
}
$effect(() => {
@@ -74,18 +144,13 @@
<h1 class="text-3xl font-bold tracking-tight">Stacks</h1>
<p class="text-sm text-muted-foreground mt-1">Manage Docker Compose stacks</p>
</div>
- <div class="flex gap-2">
- <Button variant="outline" size="icon" onclick={refreshData} disabled={isRefreshing}>
- <RefreshCw class={isRefreshing ? 'w-4 h-4 animate-spin' : 'w-4 h-4'} />
- </Button>
- </div>
</div>
- {#if error}
+ {#if data.error}
<Alert.Root variant="destructive">
<AlertCircle class="h-4 w-4" />
<Alert.Title>Error Loading Stacks</Alert.Title>
- <Alert.Description>{error}</Alert.Description>
+ <Alert.Description>{data.error}</Alert.Description>
</Alert.Root>
{/if}
@@ -135,11 +200,7 @@
<Card.Description>Manage Docker Compose stacks</Card.Description>
</div>
<div class="flex items-center gap-2">
- <Button variant="secondary" onclick={importStack}>
- <Upload class="w-4 h-4" />
- Import
- </Button>
- <Button variant="secondary" onclick={createStack}>
+ <Button variant="secondary" onclick={() => goto(`/stacks/new`)}>
<Plus class="w-4 h-4" />
Create Stack
</Button>
@@ -150,7 +211,14 @@
{#if stacks && stacks.length > 0}
<UniversalTable
data={stacks}
- {columns}
+ columns={[
+ { accessorKey: 'name', header: 'Name' },
+ { accessorKey: 'serviceCount', header: 'Services' },
+ { accessorKey: 'status', header: 'Status' },
+ { accessorKey: 'source', header: 'Source' },
+ { accessorKey: 'createdAt', header: 'Created' },
+ { accessorKey: 'actions', header: ' ', enableSorting: false }
+ ]}
features={{
selection: false
}}
@@ -159,8 +227,88 @@
noResultsMessage: 'No stacks found'
}}
bind:selectedIds
- />
- {:else if !error}
+ >
+ {#snippet rows({ item })}
+ {@const stateVariant = statusVariantMap[item.status.toLowerCase()]}
+ <Table.Cell><a class="font-medium hover:underline" href="/stacks/{item.id}/">{item.name}</a></Table.Cell>
+ <Table.Cell>{item.serviceCount}</Table.Cell>
+ <Table.Cell><StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.status)} /></Table.Cell>
+ <Table.Cell><StatusBadge variant={item.isExternal ? 'amber' : 'green'} text={item.isExternal ? 'External' : 'Managed'} /></Table.Cell>
+ <Table.Cell>{item.createdAt}</Table.Cell>
+ <Table.Cell>
+ {#if item.isExternal}
+ <Button onclick={() => handleImportStack(item.id, item.name)} variant="outline" title="Import Stack to Arcane" disabled={isLoading.import} class="flex items-center">
+ {#if isLoading.import}
+ <Loader2 class="h-4 w-4 mr-2 animate-spin" />
+ {:else}
+ <Import class="h-4 w-4 mr-2" />
+ {/if}
+ Import
+ </Button>
+ {:else}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
+ <span class="sr-only">Open menu</span>
+ <Ellipsis />
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <DropdownMenu.Item onclick={() => goto(`/stacks/${item.id}`)} disabled={isAnyLoading}>
+ <Pen class="w-4 h-4" />
+ Edit
+ </DropdownMenu.Item>
+
+ {#if item.status !== 'running'}
+ <DropdownMenu.Item onclick={() => performStackAction('start', item.id)} disabled={isLoading.start || isAnyLoading}>
+ {#if isLoading.start}
+ <Loader2 class="w-4 h-4 animate-spin" />
+ {:else}
+ <Play class="w-4 h-4" />
+ {/if}
+ Start
+ </DropdownMenu.Item>
+ {:else}
+ <DropdownMenu.Item onclick={() => performStackAction('restart', item.id)} disabled={isLoading.restart || isAnyLoading}>
+ {#if isLoading.restart}
+ <Loader2 class="w-4 h-4 animate-spin" />
+ {:else}
+ <RotateCcw class="w-4 h-4" />
+ {/if}
+ Restart
+ </DropdownMenu.Item>
+
+ <DropdownMenu.Item onclick={() => performStackAction('stop', item.id)} disabled={isLoading.stop || isAnyLoading}>
+ {#if isLoading.stop}
+ <Loader2 class="w-4 h-4 animate-spin" />
+ {:else}
+ <StopCircle class="w-4 h-4" />
+ {/if}
+ Stop
+ </DropdownMenu.Item>
+ {/if}
+
+ <DropdownMenu.Separator />
+
+ <DropdownMenu.Item class="text-red-500 focus:!text-red-700" onclick={() => performStackAction('destroy', item.id)} disabled={isLoading.remove || isAnyLoading}>
+ {#if isLoading.remove}
+ <Loader2 class="w-4 h-4 animate-spin" />
+ {:else}
+ <Trash2 class="w-4 h-4" />
+ {/if}
+ Destroy
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ {/if}
+ </Table.Cell>
+ {/snippet}
+ </UniversalTable>
+ {:else if !data.error}
<div class="flex flex-col items-center justify-center py-12 px-6 text-center">
<FileStack class="h-12 w-12 text-muted-foreground mb-4 opacity-40" />
<p class="text-lg font-medium">No stacks found</p>
@@ -169,51 +317,4 @@
{/if}
</Card.Content>
</Card.Root>
-
- <form
- method="POST"
- action={`/stacks/${id}?/remove`}
- use:enhance={() => {
- let isRemoving = true;
- let 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') {
- window.location.href = '/stacks';
- } else {
- console.error('Error removing stack:', result);
- await invalidateAll();
- }
- };
- }}
- ></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/StackActions.svelte b/src/routes/stacks/StackActions.svelte
deleted file mode 100644
index 284fe4fda..000000000
--- a/src/routes/stacks/StackActions.svelte
+++ /dev/null
@@ -1,175 +0,0 @@
-<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';
- import type { ActionResult } from '@sveltejs/kit';
-
- interface Props {
- id: string;
- status: string;
- name?: string;
- isExternal?: boolean;
- }
-
- let { id, status, name = id, isExternal = false }: Props = $props();
-
- const isRunning = status === 'running' || status === 'partially running';
-
- let isStarting = $state(false);
- let isStopping = $state(false);
- let isRestarting = $state(false);
- let isRemoving = $state(false);
- let isImporting = $state(false);
-
- let deleteDialogOpen = $state(false);
-
- let isStackDetailPage = $derived($page.route.id === '/stacks/[stackId]');
-
- const handleDeleteSubmit = () => {
- isRemoving = true;
- deleteDialogOpen = false;
-
- return async ({ result }: { result: ActionResult }) => {
- if (result.type === 'success') {
- if (isStackDetailPage && result.data?.redirectTo) {
- goto(result.data.redirectTo);
- } else {
- await invalidateAll();
- }
- } else {
- console.error('Error removing stack:', result);
- }
- isRemoving = false;
- };
- };
-
- const handleImport = () => {
- isImporting = true;
- return async () => {
- await invalidateAll();
- isImporting = false;
- };
- };
-</script>
-
-<div class="flex items-center gap-2 justify-end">
- {#if isExternal}
- <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}
- {#if isRunning}
- <form
- method="POST"
- action="/stacks/{id}?/stop"
- use:enhance={() => {
- isStopping = true;
- return async () => {
- 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 () => {
- 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={() => {
- isRestarting = true;
- return async () => {
- await invalidateAll();
- isRestarting = false;
- };
- }}
- >
- <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>
-
- <Button type="button" size="icon" variant="destructive" title="Remove Stack" onclick={() => (deleteDialogOpen = true)}>
- <Trash2 class="h-4 w-4" />
- </Button>
- {/if}
-
- {#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/StackDateCell.svelte b/src/routes/stacks/StackDateCell.svelte
deleted file mode 100644
index 43a3cb50a..000000000
--- a/src/routes/stacks/StackDateCell.svelte
+++ /dev/null
@@ -1,29 +0,0 @@
-<script lang="ts">
- interface Props {
- date: string;
- }
-
- let { date }: Props = $props();
-
- // Format the date with a nice relative format
- function formatDate(date: string): string {
- const dateObj = new Date(date);
- const now = new Date();
- const diff = now.getTime() - dateObj.getTime();
- const diffDays = Math.floor(diff / (1000 * 3600 * 24));
-
- if (diffDays === 0) {
- return 'Today, ' + dateObj.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
- } else if (diffDays === 1) {
- return 'Yesterday';
- } else if (diffDays < 7) {
- return `${diffDays} days ago`;
- } else {
- return dateObj.toLocaleDateString();
- }
- }
-</script>
-
-<span title={new Date(date).toLocaleString()}>
- {formatDate(date)}
-</span>
diff --git a/src/routes/stacks/StackNameCell.svelte b/src/routes/stacks/StackNameCell.svelte
deleted file mode 100644
index 76fb6fff2..000000000
--- a/src/routes/stacks/StackNameCell.svelte
+++ /dev/null
@@ -1,12 +0,0 @@
-<script lang="ts">
- interface Props {
- id: string;
- name: string;
- }
-
- let { id, name }: Props = $props();
-</script>
-
-<a href="/stacks/{id}" class="font-medium hover:underline">
- {name}
-</a>
diff --git a/src/routes/stacks/[stackId]/+page.svelte b/src/routes/stacks/[stackId]/+page.svelte
index 4df459085..1ce1aa835 100644
--- a/src/routes/stacks/[stackId]/+page.svelte
+++ b/src/routes/stacks/[stackId]/+page.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import type { PageData, ActionData } from './$types';
+ 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 { ArrowLeft, Loader2, AlertCircle, Save, FileStack, Layers, ArrowRight } from '@lucide/svelte';
@@ -10,17 +10,21 @@
import ActionButtons from '$lib/components/action-buttons.svelte';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import { statusVariantMap } from '$lib/types/statuses';
- import { capitalizeFirstLetter } from '$lib/utils';
+ import { capitalizeFirstLetter } from '$lib/utils/string.utils';
import { invalidateAll } from '$app/navigation';
import { toast } from 'svelte-sonner';
- import { enhance } from '$app/forms';
import YamlEditor from '$lib/components/yaml-editor.svelte';
import { Switch } from '$lib/components/ui/switch/index.js';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import StackAPIService from '$lib/services/api/stack-api-service';
+ import { handleApiReponse } from '$lib/utils/api.util';
+
+ const stackApi = new StackAPIService();
let { data }: { data: PageData } = $props();
let { stack, editorState } = $derived(data);
- let depoloying = $state(false);
+ let deploying = $state(false);
let stopping = $state(false);
let restarting = $state(false);
let removing = $state(false);
@@ -28,14 +32,15 @@
let name = $derived(editorState.name);
let composeContent = $derived(editorState.composeContent);
+ let autoUpdate = $derived(editorState.autoUpdate);
let originalName = $derived(editorState.originalName);
let originalComposeContent = $derived(editorState.originalComposeContent);
let originalAutoUpdate = $derived(editorState.autoUpdate);
- let hasChanges = $derived(name !== originalName || composeContent !== originalComposeContent || editorState.autoUpdate !== originalAutoUpdate);
+ let hasChanges = $derived(name !== originalName || composeContent !== originalComposeContent || autoUpdate !== originalAutoUpdate);
$effect(() => {
- depoloying = false;
+ deploying = false;
stopping = false;
restarting = false;
removing = false;
@@ -45,43 +50,22 @@
async function handleSaveChanges() {
if (!stack || !hasChanges) return;
- saving = true;
- console.log('Saving stack via API...');
-
- try {
- const response = await fetch(`/api/stacks/${stack.id}`, {
- method: 'PATCH',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- name,
- composeContent,
- autoUpdate: editorState.autoUpdate
- })
- });
+ handleApiReponse(
+ await tryCatch(stackApi.save(stack.id, name, composeContent, autoUpdate)),
+ 'Failed to Save Stack',
+ (value) => (saving = value),
+ async (data) => {
+ originalName = name;
+ originalComposeContent = composeContent;
+ originalAutoUpdate = autoUpdate;
- const result = await response.json();
+ console.log('Stack save successful:', data);
+ toast.success('Stack updated successfully!');
- if (!response.ok) {
- throw new Error(result.error || `HTTP error! status: ${response.status}`);
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ await invalidateAll();
}
-
- console.log('Stack save successful:', result);
- toast.success('Stack updated successfully!');
-
- originalName = name;
- originalComposeContent = composeContent;
- originalAutoUpdate = editorState.autoUpdate;
-
- await invalidateAll();
- } catch (error: unknown) {
- console.error('Error saving stack:', error);
- const message = error instanceof Error ? error.message : String(error);
- toast.error(`Failed to update stack: ${message}`);
- } finally {
- saving = false;
- }
+ );
}
</script>
@@ -113,31 +97,17 @@
{#if stack}
<div class="flex gap-2 flex-wrap">
- <form
- method="POST"
- action={stack.status === 'running' || stack.status === 'partially running' ? '?/stop' : '?/start'}
- use:enhance={() => {
- const isStarting = stack.status !== 'running' && stack.status !== 'partially running';
- if (isStarting) depoloying = true;
- else stopping = true;
- return async ({ update }) => {
- await update({ reset: false });
- };
+ <ActionButtons
+ id={stack.id}
+ type="stack"
+ itemState={stack.status}
+ loading={{
+ start: deploying,
+ stop: stopping,
+ restart: restarting,
+ remove: removing
}}
- >
- <input type="hidden" name="action" value={stack.status === 'running' || stack.status === 'partially running' ? 'stop' : 'start'} />
- <ActionButtons
- id={stack.id}
- type="stack"
- itemState={stack.status}
- loading={{
- start: depoloying,
- stop: stopping,
- restart: restarting,
- remove: removing
- }}
- />
- </form>
+ />
</div>
{/if}
</div>
@@ -207,7 +177,7 @@
<div class="grid w-full items-center gap-1.5">
<Label for="compose-editor">Docker Compose File</Label>
<div class="border rounded-md overflow-hidden">
- <YamlEditor bind:value={composeContent} readOnly={saving || depoloying || stopping || restarting || removing} />
+ <YamlEditor bind:value={composeContent} readOnly={saving || deploying || stopping || restarting || removing} />
</div>
<p class="text-xs text-muted-foreground">
Edit your <span class="font-bold">compose.yaml</span> file directly. Syntax errors will be highlighted.
@@ -215,7 +185,7 @@
</div>
<div class="flex items-center space-x-2 mt-4">
- <Switch id="auto-update" name="autoUpdate" bind:checked={editorState.autoUpdate} />
+ <Switch id="auto-update" name="autoUpdate" bind:checked={autoUpdate} />
<Label for="auto-update" class="font-medium">Enable auto-update</Label>
<div class="inline-block">
<p class="text-xs text-muted-foreground">When enabled, Arcane will periodically check for newer versions of all images in this stack and automatically redeploy it.</p>
diff --git a/src/routes/stacks/columns.ts b/src/routes/stacks/columns.ts
deleted file mode 100644
index 995aa1518..000000000
--- a/src/routes/stacks/columns.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import type { Stack } from '$lib/types/docker/stack.type';
-import type { ColumnDef } from '@tanstack/table-core';
-import { renderComponent } from '$lib/components/ui/data-table/index.js';
-import StackActions from './StackActions.svelte';
-import StackNameCell from './StackNameCell.svelte';
-import StackDateCell from './StackDateCell.svelte';
-import StatusBadge from '$lib/components/badges/status-badge.svelte';
-import { capitalizeFirstLetter } from '$lib/utils';
-import { statusVariantMap } from '$lib/types/statuses';
-
-export const columns: ColumnDef<Stack>[] = [
- {
- accessorKey: 'name',
- header: 'Name',
- cell: ({ row }) => {
- return renderComponent(StackNameCell, {
- id: row.original.id,
- name: row.original.name
- });
- }
- },
- {
- accessorKey: 'serviceCount',
- header: 'Services'
- },
- {
- accessorKey: 'status',
- header: 'Status',
- cell: ({ row }) => {
- const status = row.getValue('status') as string;
- const variant = statusVariantMap[status.toLowerCase()] || 'gray';
-
- return renderComponent(StatusBadge, {
- variant: variant,
- text: capitalizeFirstLetter(status)
- });
- }
- },
- {
- accessorKey: 'createdAt',
- header: 'Created',
- cell: ({ row }) => {
- return renderComponent(StackDateCell, {
- date: row.original.createdAt
- });
- }
- },
- {
- header: 'Source',
- accessorKey: 'isExternal',
- cell: ({ row }) => {
- const isExternal = row.getValue('isExternal');
- return renderComponent(StatusBadge, {
- variant: isExternal ? 'amber' : 'green',
- text: isExternal ? 'External' : 'Managed'
- });
- }
- },
- {
- id: 'actions',
- header: '',
- cell: ({ row }) => {
- 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.svelte b/src/routes/stacks/new/+page.svelte
index 92683ee59..0c746659e 100644
--- a/src/routes/stacks/new/+page.svelte
+++ b/src/routes/stacks/new/+page.svelte
@@ -1,24 +1,20 @@
<script lang="ts">
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
- import { ArrowLeft, Loader2, AlertCircle, Save, FileStack } from '@lucide/svelte';
+ import { ArrowLeft, Loader2, Save, FileStack } from '@lucide/svelte';
import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
- 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 YamlEditor from '$lib/components/yaml-editor.svelte';
+ import StackAPIService from '$lib/services/api/stack-api-service';
+ import { preventDefault } from '$lib/utils/form.utils';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import { handleApiReponse } from '$lib/utils/api.util';
+ const stackApi = new StackAPIService();
let saving = $state(false);
- let apiError = $state<string | null>(null);
-
- function preventDefault(fn: (event: Event) => void) {
- return function (this: unknown, event: Event) {
- event.preventDefault();
- fn.call(this, event);
- };
- }
const defaultComposeTemplate = `services:
nginx:
@@ -40,34 +36,17 @@ volumes:
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}`);
+ handleApiReponse(
+ await tryCatch(stackApi.create(name, composeContent)),
+ 'Failed to Create Stack',
+ (value) => (saving = value),
+ async (data) => {
+ toast.success(`Stack "${data.stack.name}" created.`);
+ await invalidateAll();
+ goto(`/stacks/${data.stack.id}`);
}
-
- toast.success(result.message || `Stack "${result.stack.name}" created.`);
- await invalidateAll();
- goto(`/stacks/${result.stack.id}`);
- } catch (err: unknown) {
- console.error('Failed to create stack:', err);
- const message = err instanceof Error ? err.message : 'An unknown error occurred.';
- apiError = message;
- toast.error(`Failed to create stack: ${apiError}`);
- } finally {
- saving = false;
- }
+ );
}
</script>
@@ -94,14 +73,6 @@ volumes:
</div>
</div>
- {#if apiError}
- <Alert.Root variant="destructive">
- <AlertCircle class="h-4 w-4 mr-2" />
- <Alert.Title>Failed to Create Stack</Alert.Title>
- <Alert.Description>{apiError}</Alert.Description>
- </Alert.Root>
- {/if}
-
<form class="space-y-6" onsubmit={preventDefault(handleSubmit)}>
<Card.Root class="border shadow-sm">
<Card.Header>
diff --git a/src/routes/volumes/+page.server.ts b/src/routes/volumes/+page.server.ts
index 8070b3aeb..88dfcf5e3 100644
--- a/src/routes/volumes/+page.server.ts
+++ b/src/routes/volumes/+page.server.ts
@@ -16,7 +16,6 @@ export const load: PageServerLoad = async (): Promise<VolumePageData> => {
try {
const volumes = await listVolumes();
- // Enhance volumes with usage information
const enhancedVolumes = await Promise.all(
volumes.map(async (volume): Promise<EnhancedVolumeInfo> => {
const inUse = await isVolumeInUse(volume.name);
diff --git a/src/routes/volumes/+page.svelte b/src/routes/volumes/+page.svelte
index aa3fe8622..22be090e4 100644
--- a/src/routes/volumes/+page.svelte
+++ b/src/routes/volumes/+page.svelte
@@ -1,130 +1,171 @@
<script lang="ts">
+ 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 { toast } from 'svelte-sonner';
- import { Plus, AlertCircle, HardDrive, Database, Trash2, Loader2, ChevronDown } from '@lucide/svelte';
+ import { Plus, AlertCircle, HardDrive, Database, Trash2, Loader2, ChevronDown, Ellipsis, ScanSearch } 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 { goto, 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';
+ import * as Table from '$lib/components/ui/table';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import { handleApiReponse } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import VolumeAPIService from '$lib/services/api/volume-api-service';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import type { VolumeCreateOptions } from 'dockerode';
let { data }: { data: PageData } = $props();
- let { error } = $state(data);
- let volumes = $state(data.volumes);
- let selectedIds = $state<string[]>([]);
- let isCreateDialogOpen = $state(false);
- let isCreatingVolume = $state(false);
- let isDeletingSelected = $state(false);
- let isConfirmDeleteDialogOpen = $state(false);
- const totalVolumes = $derived(volumes?.length || 0);
-
- async function handleCreateVolumeSubmit(event: { name: string; driver?: string; driverOpts?: Record<string, string>; labels?: Record<string, string> }) {
- const { name, driver, driverOpts, labels } = event;
+ let volumePageStates = $state({
+ volumes: data.volumes,
+ selectedIds: <string[]>[],
+ error: data.error
+ });
- isCreatingVolume = true;
- try {
- const response = await fetch('/api/volumes', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- name,
- driver,
- driverOpts,
- labels
- })
- });
+ let isDialogOpen = $state({
+ create: false,
+ remove: false
+ });
- const result = await response.json();
+ let isLoading = $state({
+ remove: false,
+ creating: false
+ });
- if (!response.ok) {
- throw new Error(result.error || `HTTP error! status: ${response.status}`);
- }
+ const totalVolumes = $derived(volumePageStates.volumes.length);
- toast.success(`Volume "${result.volume.Name}" created successfully.`);
- isCreateDialogOpen = false;
+ const volumeApi = new VolumeAPIService();
- await refreshData();
- } catch (err: unknown) {
- console.error('Failed to create volume:', err);
- const message = err instanceof Error ? err.message : String(err);
- toast.error(`Failed to create volume: ${message}`);
- } finally {
- isCreatingVolume = false;
- }
+ async function handleRemoveVolumeConfirm(volumeName: string) {
+ openConfirmDialog({
+ title: 'Delete Volume',
+ message: 'Are you sure you want to delete this volume? This action cannot be undone.',
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ handleApiReponse(
+ await tryCatch(volumeApi.remove(volumeName)),
+ 'Failed to Remove Volume',
+ (value) => (isLoading.remove = value),
+ async () => {
+ toast.success('Volume Removed Successfully.');
+ await invalidateAll();
+ }
+ );
+ }
+ }
+ });
}
- async function refreshData() {
- try {
- await invalidateAll();
- volumes = data.volumes;
- } catch (err: unknown) {
- console.error('Failed to refresh volume data:', err);
- const message = err instanceof Error ? err.message : String(err);
- toast.error(`Failed to refresh volumes: ${message}`);
- }
+ async function handleCreateVolume(volumeCreate: VolumeCreateOptions) {
+ handleApiReponse(
+ await tryCatch(volumeApi.create(volumeCreate)),
+ `Failed to Create Volume "${volumeCreate.Name}"`,
+ (value) => (isLoading.creating = value),
+ async () => {
+ toast.success(`Volume "${volumeCreate.Name}" Create successfully.`);
+ await invalidateAll();
+ }
+ );
}
+ // async function handleCreateVolumeSubmit(event: { name: string; driver?: string; driverOpts?: Record<string, string>; labels?: Record<string, string> }) {
+ // const { name, driver, driverOpts, labels } = event;
+
+ // isLoading.creating = true;
+ // try {
+ // const response = await fetch('/api/volumes', {
+ // method: 'POST',
+ // headers: {
+ // 'Content-Type': 'application/json'
+ // },
+ // body: JSON.stringify({
+ // name,
+ // driver,
+ // driverOpts,
+ // labels
+ // })
+ // });
+
+ // const result = await response.json();
+
+ // if (!response.ok) {
+ // throw new Error(result.error || `HTTP error! status: ${response.status}`);
+ // }
+
+ // toast.success(`Volume "${result.volume.Name}" created successfully.`);
+ // isDialogOpen.create = false;
+
+ // await refreshData();
+ // } catch (err: unknown) {
+ // console.error('Failed to create volume:', err);
+ // const message = err instanceof Error ? err.message : String(err);
+ // toast.error(`Failed to create volume: ${message}`);
+ // } finally {
+ // isLoading.creating = false;
+ // }
+ // }
+
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' };
- }
+ openConfirmDialog({
+ title: 'Delete Selected Volumes',
+ message: `Are you sure you want to delete ${volumePageStates.selectedIds.length} selected images? This action cannot be undone. Images currently used by containers will not be deleted.
+`,
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ isLoading.remove = true;
- 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: unknown) {
- console.error(`Failed to delete volume "${name}":`, err);
- const message = err instanceof Error ? err.message : String(err);
- return { name, success: false, error: message };
- }
- });
+ let successCount = 0;
+ let failureCount = 0;
- const results = await Promise.all(deletePromises);
- const successfulDeletes = results.filter((r) => r.success);
- const failedDeletes = results.filter((r) => !r.success);
+ for (const name of volumePageStates.selectedIds) {
+ const volume = volumePageStates.volumes?.find((v) => v.name === name);
- if (successfulDeletes.length > 0) {
- toast.success(`Successfully deleted ${successfulDeletes.length} volume(s).`);
- setTimeout(async () => {
- await refreshData();
- selectedIds = [];
- }, 500);
- }
+ if (volume?.inUse) {
+ toast.error(`Volume "${volume.name}" is in use and cannot be deleted.`);
+ failureCount++;
+ continue;
+ }
- failedDeletes.forEach((r) => {
- if (r.error !== 'Volume in use') {
- toast.error(`Failed to delete volume "${r.name}": ${r.error}`);
- }
- });
+ if (!volume?.name) continue;
+ const result = await tryCatch(volumeApi.remove(volume.name));
+ handleApiReponse(
+ result,
+ `Failed to delete image "${volume.name}"`,
+ (value) => (isLoading.remove = value),
+ async () => {
+ toast.success(`Volume "${volume.name}" deleted successfully.`);
+ successCount++;
+ }
+ );
- isDeletingSelected = false;
- isConfirmDeleteDialogOpen = false;
- }
+ if (result.error) {
+ failureCount++;
+ }
+ }
- function openCreateDialog() {
- isCreateDialogOpen = true;
+ console.log(`Finished deleting. Success: ${successCount}, Failed: ${failureCount}`);
+ if (successCount > 0) {
+ setTimeout(async () => {
+ await invalidateAll();
+ volumePageStates.selectedIds = [];
+ }, 500);
+ } else {
+ volumePageStates.selectedIds = [];
+ }
+ }
+ }
+ });
}
$effect(() => {
- volumes = data.volumes;
- error = data.error;
+ volumePageStates.volumes = data.volumes;
});
</script>
@@ -137,11 +178,11 @@
<div class="flex gap-2"></div>
</div>
- {#if error}
+ {#if volumePageStates.error}
<Alert.Root variant="destructive">
<AlertCircle class="h-4 w-4 mr-2" />
<Alert.Title>Error Loading Volumes</Alert.Title>
- <Alert.Description>{error}</Alert.Description>
+ <Alert.Description>{volumePageStates.error}</Alert.Description>
</Alert.Root>
{/if}
@@ -179,30 +220,30 @@
<Card.Description>Manage persistent data storage</Card.Description>
</div>
<div class="flex items-center gap-2">
- {#if selectedIds.length > 0}
+ {#if volumePageStates.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}
+ <Button {...props} variant="outline" disabled={isLoading.remove} aria-label={`Group actions for ${volumePageStates.selectedIds.length} selected volume(s)`}>
+ {#if isLoading.remove}
<Loader2 class="w-4 h-4 animate-spin" />
Processing...
{:else}
- Actions ({selectedIds.length})
+ Actions ({volumePageStates.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}>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Item onclick={() => handleDeleteSelected()} class="text-red-500 focus:!text-red-700" disabled={isLoading.remove}>
<Trash2 class="w-4 h-4" />
Delete Selected
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
{/if}
- <Button variant="secondary" onclick={openCreateDialog}>
+ <Button variant="secondary" onclick={() => (isDialogOpen.create = true)}>
<Plus class="w-4 h-4" />
Create Volume
</Button>
@@ -210,18 +251,69 @@
</div>
</Card.Header>
<Card.Content>
- {#if volumes && volumes.length > 0}
+ {#if volumePageStates.volumes && volumePageStates.volumes.length > 0}
<UniversalTable
- data={volumes}
- {columns}
+ data={volumePageStates.volumes}
idKey="name"
+ columns={[
+ { accessorKey: 'name', header: 'Name' },
+ { accessorKey: 'mountpoint', header: 'Mountpoint' },
+ { accessorKey: 'driver', header: 'Driver' },
+ { accessorKey: 'actions', header: ' ', enableSorting: false }
+ ]}
display={{
filterPlaceholder: 'Search volumes...',
noResultsMessage: 'No volumes found'
}}
- bind:selectedIds
- />
- {:else if !error}
+ bind:selectedIds={volumePageStates.selectedIds}
+ >
+ {#snippet rows({ item })}
+ <Table.Cell>
+ <div class="flex items-center gap-2">
+ <span class="truncate">
+ <a class="font-medium hover:underline" href="/volumes/{item.name}/">{item.name}</a>
+ </span>
+ {#if !item.inUse}
+ <StatusBadge text="Unused" variant="amber" />
+ {/if}
+ </div>
+ </Table.Cell>
+ <Table.Cell>{item.mountpoint}</Table.Cell>
+ <Table.Cell>{item.driver}</Table.Cell>
+ <Table.Cell>
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
+ <span class="sr-only">Open menu</span>
+ <Ellipsis />
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <DropdownMenu.Item onclick={() => goto(`/volumes/${encodeURIComponent(item.name)}`)} disabled={isLoading.remove}>
+ <ScanSearch class="w-4 h-4" />
+ Inspect
+ </DropdownMenu.Item>
+
+ <DropdownMenu.Separator />
+
+ <DropdownMenu.Item class="text-red-500 focus:!text-red-700" onclick={() => handleRemoveVolumeConfirm(item.name)} disabled={isLoading.remove}>
+ {#if isLoading.remove}
+ <Loader2 class="w-4 h-4 animate-spin" />
+ {:else}
+ <Trash2 class="w-4 h-4" />
+ {/if}
+ Delete
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </UniversalTable>
+ {:else if !volumePageStates.error}
<div class="flex flex-col items-center justify-center py-12 px-6 text-center">
<Database class="h-12 w-12 text-muted-foreground mb-4 opacity-40" />
<p class="text-lg font-medium">No volumes found</p>
@@ -231,27 +323,5 @@
</Card.Content>
</Card.Root>
- <CreateVolumeDialog bind:open={isCreateDialogOpen} 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>
+ <CreateVolumeDialog bind:open={isDialogOpen.create} isCreating={isLoading.creating} onSubmit={(volumeCreateData) => handleCreateVolume(volumeCreateData)} />
</div>
diff --git a/src/routes/volumes/MountpointCell.svelte b/src/routes/volumes/MountpointCell.svelte
deleted file mode 100644
index 1bd2e5450..000000000
--- a/src/routes/volumes/MountpointCell.svelte
+++ /dev/null
@@ -1,14 +0,0 @@
-<script lang="ts">
- interface Props {
- mountpoint: string;
- }
-
- let { mountpoint }: Props = $props();
-
- const MAX_LENGTH = 50;
- let displayValue = $derived(mountpoint.length > MAX_LENGTH ? mountpoint.substring(0, MAX_LENGTH - 3) + '...' : mountpoint);
-</script>
-
-<span class="font-mono text-xs" title={mountpoint}>
- {displayValue}
-</span>
diff --git a/src/routes/volumes/VolumeActions.svelte b/src/routes/volumes/VolumeActions.svelte
deleted file mode 100644
index 7d1a19114..000000000
--- a/src/routes/volumes/VolumeActions.svelte
+++ /dev/null
@@ -1,82 +0,0 @@
-<script lang="ts">
- import { Button } from '$lib/components/ui/button/index.js';
- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
- import { Trash2, Loader2, Ellipsis, ScanSearch } from '@lucide/svelte';
- import { toast } from 'svelte-sonner';
- import { goto, invalidateAll } from '$app/navigation';
- import ConfirmDialog from '$lib/components/confirm-dialog.svelte';
-
- const { name, inUse = false } = $props<{ name: string; inUse: boolean }>();
-
- let showRemoveConfirm = $state(false);
- let isDeleting = $state(false);
-
- function viewVolume() {
- goto(`/volumes/${encodeURIComponent(name)}`);
- }
-
- function triggerRemove() {
- showRemoveConfirm = true;
- }
-
- async function handleRemoveConfirm(force?: boolean) {
- showRemoveConfirm = false;
- isDeleting = true;
- try {
- const endpoint = `/api/volumes/${encodeURIComponent(name)}${force ? '?force=true' : ''}`;
- const response = await fetch(endpoint, {
- method: 'DELETE'
- });
-
- const result = await response.json();
-
- if (!response.ok) {
- throw new Error(result.error || `HTTP error! status: ${response.status}`);
- }
-
- toast.success(`Volume "${name}" deleted successfully.`);
- await invalidateAll();
- } catch (err: unknown) {
- console.error(`Failed to delete volume "${name}":`, err);
- const message = err instanceof Error ? err.message : String(err);
- toast.error(`Failed to delete volume: ${message}`);
- } finally {
- isDeleting = false;
- }
- }
-
- const isAnyLoading = $derived(isDeleting);
- const removeDescription = $derived(`Are you sure you want to delete volume "${name}"? This action cannot be undone.`);
-</script>
-
-<ConfirmDialog bind:open={showRemoveConfirm} itemType="volume" isRunning={inUse} title="Confirm Volume Removal" description={removeDescription} confirmLabel="Delete" variant="destructive" onConfirm={handleRemoveConfirm} />
-
-<DropdownMenu.Root>
- <DropdownMenu.Trigger>
- {#snippet child({ props })}
- <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
- <span class="sr-only">Open menu</span>
- <Ellipsis />
- </Button>
- {/snippet}
- </DropdownMenu.Trigger>
- <DropdownMenu.Content>
- <DropdownMenu.Group>
- <DropdownMenu.Item onclick={viewVolume} disabled={isAnyLoading}>
- <ScanSearch class="w-4 h-4" />
- Inspect
- </DropdownMenu.Item>
-
- <DropdownMenu.Separator />
-
- <DropdownMenu.Item class="text-red-500 focus:!text-red-700" onclick={triggerRemove} disabled={isAnyLoading}>
- {#if isDeleting}
- <Loader2 class="w-4 h-4 animate-spin" />
- {:else}
- <Trash2 class="w-4 h-4" />
- {/if}
- Delete
- </DropdownMenu.Item>
- </DropdownMenu.Group>
- </DropdownMenu.Content>
-</DropdownMenu.Root>
diff --git a/src/routes/volumes/[volumeName]/+page.svelte b/src/routes/volumes/[volumeName]/+page.svelte
index 512df8fbf..75c6cb98a 100644
--- a/src/routes/volumes/[volumeName]/+page.svelte
+++ b/src/routes/volumes/[volumeName]/+page.svelte
@@ -10,7 +10,7 @@
import { Separator } from '$lib/components/ui/separator/index.js';
import { Badge } from '$lib/components/ui/badge/index.js';
import { formatDate } from '$lib/utils';
- import ConfirmDialog from '$lib/components/confirm-dialog.svelte';
+ // import ConfirmDialog from '$lib/components/confirm-dialog/confirm-dialog-old.svelte';
let { data, form }: { data: PageData; form: ActionData } = $props();
let { volume, inUse } = $derived(data);
@@ -44,7 +44,7 @@
}
</script>
-<ConfirmDialog bind:open={showRemoveConfirm} title="Confirm Volume Removal" description={`Are you sure you want to remove volume "${volume?.Name}"? This action cannot be undone.`} confirmLabel="Remove" variant="destructive" onConfirm={handleRemoveConfirm} itemType={'volume'} isRunning={inUse} />
+<!-- <ConfirmDialog bind:open={showRemoveConfirm} title="Confirm Volume Removal" description={`Are you sure you want to remove volume "${volume?.Name}"? This action cannot be undone.`} confirmLabel="Remove" variant="destructive" onConfirm={handleRemoveConfirm} itemType="volume" isRunning={inUse} /> -->
<div class="space-y-6 pb-8">
<div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">
diff --git a/src/routes/volumes/columns.ts b/src/routes/volumes/columns.ts
deleted file mode 100644
index 53918d9bb..000000000
--- a/src/routes/volumes/columns.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import type { ColumnDef } from '@tanstack/table-core';
-import { renderComponent } from '$lib/components/ui/data-table/index.js';
-import VolumeActions from './VolumeActions.svelte';
-import MountpointCell from './MountpointCell.svelte';
-import type { ServiceVolume } from '$lib/types/docker';
-import UnusedTextBadge from '$lib/components/badges/unused-text-badge.svelte';
-
-// Update the type to include the inUse property
-export type VolumeInfo = ServiceVolume & { inUse?: boolean };
-
-export const columns: ColumnDef<VolumeInfo>[] = [
- {
- accessorKey: 'name',
- header: 'Name',
- cell: ({ row }) => {
- return renderComponent(UnusedTextBadge, {
- name: row.original.name,
- inUse: row.original.inUse,
- link: `/volumes/${row.original.name}`
- });
- }
- },
- {
- accessorKey: 'driver',
- header: 'Driver'
- },
- {
- accessorKey: 'scope',
- header: 'Scope'
- },
- {
- accessorKey: 'mountpoint',
- header: 'Mountpoint',
- cell: ({ row }) => {
- return renderComponent(MountpointCell, {
- mountpoint: row.original.mountpoint
- });
- }
- },
- {
- id: 'actions',
- header: '',
- cell: ({ row }) => {
- return renderComponent(VolumeActions, {
- name: row.original.name,
- inUse: !!row.original.inUse
- });
- },
- enableSorting: false
- }
-];
diff --git a/src/routes/volumes/create-volume-dialog.svelte b/src/routes/volumes/create-volume-dialog.svelte
index 628d0bd42..24f303646 100644
--- a/src/routes/volumes/create-volume-dialog.svelte
+++ b/src/routes/volumes/create-volume-dialog.svelte
@@ -8,31 +8,22 @@
import { Textarea } from '$lib/components/ui/textarea/index.js';
import * as Accordion from '$lib/components/ui/accordion/index.js';
import * as Select from '$lib/components/ui/select/index.js';
-
- export function onClose() {
- open = false;
- }
-
- type VolumeSubmitData = {
- name: string;
- driver?: string;
- driverOpts?: Record<string, string>;
- labels?: Record<string, string>;
- };
+ import type { VolumeCreateOptions } from 'dockerode';
interface Props {
open?: boolean;
isCreating?: boolean;
- // Fixed: Use specific function type instead of any
- onSubmit?: (data: VolumeSubmitData) => void;
+ onSubmit?: (data: VolumeCreateOptions) => void;
}
- let { open = $bindable(false), isCreating = false, onSubmit = (_data: VolumeSubmitData) => {} }: Props = $props();
+ let { open = $bindable(false), isCreating = false, onSubmit = (_data: VolumeCreateOptions) => {} }: Props = $props();
- let volumeName = $state('');
- let driver = $state('local');
- let driverOptsText = $state('');
- let labelsText = $state('');
+ let volumeCreateStates = $state({
+ volumeName: '',
+ volumeDriver: 'local',
+ volumeOptText: '',
+ volumeLabels: ''
+ });
const drivers = [
{ label: 'Local', value: 'local' },
@@ -64,17 +55,20 @@
}
function handleSubmit() {
- if (!volumeName.trim()) return;
+ if (!volumeCreateStates.volumeName.trim()) return;
+
+ const driverOpts = parseKeyValuePairs(volumeCreateStates.volumeOptText);
+ const labels = parseKeyValuePairs(volumeCreateStates.volumeLabels);
- const driverOpts = parseKeyValuePairs(driverOptsText);
- const labels = parseKeyValuePairs(labelsText);
+ const volumeOptions: VolumeCreateOptions = {
+ Name: volumeCreateStates.volumeName.trim(),
+ Driver: volumeCreateStates.volumeDriver,
+ DriverOpts: Object.keys(driverOpts).length ? driverOpts : undefined,
+ Labels: Object.keys(labels).length ? labels : undefined
+ };
- onSubmit({
- name: volumeName.trim(),
- driver,
- driverOpts: Object.keys(driverOpts).length ? driverOpts : undefined,
- labels: Object.keys(labels).length ? labels : undefined
- });
+ onSubmit(volumeOptions);
+ open = false;
}
</script>
@@ -88,15 +82,15 @@
<form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-4">
<div class="grid grid-cols-4 items-center gap-4">
<Label for="volume-name" class="text-right">Name</Label>
- <Input id="volume-name" bind:value={volumeName} class="col-span-3" placeholder="e.g., my-app-data" required disabled={isCreating} />
+ <Input id="volume-name" bind:value={volumeCreateStates.volumeName} class="col-span-3" placeholder="e.g., my-app-data" required disabled={isCreating} />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="volume-driver" class="text-right">Driver</Label>
<div class="col-span-3">
- <Select.Root type="single" bind:value={driver} disabled={isCreating}>
+ <Select.Root type="single" bind:value={volumeCreateStates.volumeDriver} disabled={isCreating}>
<Select.Trigger class="w-full">
- <span>{drivers.find((d) => d.value === driver)?.label || 'Select a driver'}</span>
+ <span>{drivers.find((d) => d.value === volumeCreateStates.volumeDriver)?.label || 'Select a driver'}</span>
</Select.Trigger>
<Select.Content>
{#each drivers as driverOption (driverOption.value)}
@@ -116,12 +110,12 @@
<div class="grid gap-4 pt-2">
<div>
<Label for="driver-opts">Driver Options</Label>
- <Textarea id="driver-opts" bind:value={driverOptsText} placeholder="key=value&#10;key2=value2" disabled={isCreating} />
+ <Textarea id="driver-opts" bind:value={volumeCreateStates.volumeOptText} placeholder="key=value&#10;key2=value2" disabled={isCreating} />
<p class="text-xs text-muted-foreground mt-1">Enter driver-specific options as key=value pairs, one per line</p>
</div>
<div>
<Label for="labels">Labels</Label>
- <Textarea id="labels" bind:value={labelsText} placeholder="com.example.description=Production data&#10;com.example.department=Finance" disabled={isCreating} />
+ <Textarea id="labels" bind:value={volumeCreateStates.volumeLabels} placeholder="com.example.description=Production data&#10;com.example.department=Finance" disabled={isCreating} />
<p class="text-xs text-muted-foreground mt-1">Enter metadata labels as key=value pairs, one per line</p>
</div>
</div>
@@ -131,8 +125,8 @@
</form>
<Dialog.Footer>
- <Button variant="outline" onclick={onClose} disabled={isCreating}>Cancel</Button>
- <Button type="submit" onclick={handleSubmit} disabled={isCreating || !volumeName.trim()}>
+ <Button variant="outline" onclick={() => (open = false)} disabled={isCreating}>Cancel</Button>
+ <Button type="submit" onclick={handleSubmit} disabled={isCreating || !volumeCreateStates.volumeName.trim()}>
{#if isCreating}
<Loader2 class="h-4 w-4 mr-2 animate-spin" /> Creating...
{:else}
diff --git a/tests/.auth/login.json b/tests/.auth/login.json
new file mode 100644
index 000000000..b4a42c0ae
--- /dev/null
+++ b/tests/.auth/login.json
@@ -0,0 +1,29 @@
+{
+ "cookies": [
+ {
+ "name": "session_id",
+ "value": "ff3866c740296d5d9d1a1b1137af1908bc29c6b01ba9c79aa766739f5fedd66a",
+ "domain": "localhost",
+ "path": "/",
+ "expires": 1746336862.42101,
+ "httpOnly": true,
+ "secure": true,
+ "sameSite": "Strict"
+ }
+ ],
+ "origins": [
+ {
+ "origin": "http://localhost:3000",
+ "localStorage": [
+ {
+ "name": "mode-watcher-theme",
+ "value": ""
+ },
+ {
+ "name": "mode-watcher-mode",
+ "value": "system"
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/tests/auth.setup.ts b/tests/auth.setup.ts
new file mode 100644
index 000000000..65f748628
--- /dev/null
+++ b/tests/auth.setup.ts
@@ -0,0 +1,15 @@
+import { test as setup, expect } from '@playwright/test';
+
+const authFile = 'tests/.auth/login.json';
+
+setup('authenticate', async ({ page }) => {
+ await page.goto('/auth/login');
+ await page.getByLabel('Username').fill('arcane');
+ await page.getByLabel('Password').fill('arcane-admin');
+ await page.getByRole('button', { name: 'Sign In' }).click();
+
+ await expect(page).toHaveURL('/');
+
+ await page.context().storageState({ path: authFile });
+ console.log(`Authentication state saved to ${authFile}`);
+});
diff --git a/tests/images.spec.ts b/tests/images.spec.ts
new file mode 100644
index 000000000..01d4c69ff
--- /dev/null
+++ b/tests/images.spec.ts
@@ -0,0 +1,241 @@
+import { test, expect, type Page } from '@playwright/test';
+import { formatBytes } from '../src/lib/utils'; // Assuming utils are accessible
+
+// Mock data for images
+const mockImages = [
+ { id: 'sha256:abc123def456', repoTags: ['nginx:latest', 'nginx:1.25'], size: 187000000, inUse: false, repo: 'nginx', tag: 'latest' },
+ { id: 'sha256:ghi789jkl012', repoTags: ['redis:alpine'], size: 32500000, inUse: true, repo: 'redis', tag: 'alpine' }
+];
+
+const mockNoImages: any[] = [];
+
+async function setupImageRoutes(page: Page, images: any[], options: { pruneResult?: any; removeErrorImageId?: string } = {}) {
+ // Mock the initial list response
+ await page.route('/api/images', async (route) => {
+ await route.fulfill({ json: images });
+ });
+
+ // Mock remove response (can simulate errors)
+ await page.route('/api/images/*/remove', async (route, request) => {
+ const url = request.url();
+ const imageId = url.split('/')[url.split('/').length - 2]; // Get ID from URL
+
+ if (options.removeErrorImageId && imageId.includes(options.removeErrorImageId)) {
+ await route.fulfill({ status: 500, json: { message: 'Simulated remove error' } });
+ } else {
+ await route.fulfill({ json: { message: 'Image removed successfully' } });
+ }
+ });
+
+ // Mock prune response
+ await page.route('/api/images/prune', async (route) => {
+ await route.fulfill({ json: options.pruneResult ?? { message: 'Images pruned successfully', spaceReclaimed: 10000 } });
+ });
+
+ // Mock pull response (non-stream)
+ await page.route('/api/images/pull', async (route) => {
+ await route.fulfill({ json: { message: 'Image pulled successfully' } });
+ });
+
+ // Mock pull stream response (EventSource)
+ // Note: Fully mocking EventSource behavior in Playwright routes is complex.
+ // This basic mock sends completion immediately. For progress, more intricate mocking is needed.
+ await page.route('/api/images/pull-stream/**', async (route) => {
+ // Send headers for EventSource
+ await route.fulfill({
+ status: 200,
+ contentType: 'text/event-stream',
+ body: `data: ${JSON.stringify({ complete: true })}\n\n`
+ });
+ });
+}
+
+test.describe('Images Page', () => {
+ test('should display the images page title and description', async ({ page }) => {
+ await setupImageRoutes(page, mockImages);
+ await page.goto('/images');
+
+ await expect(page.getByRole('heading', { name: 'Docker Images', level: 1 })).toBeVisible();
+ await expect(page.getByText('Manage your Docker images').first()).toBeVisible();
+ });
+
+ test('should display stats cards with correct counts and size', async ({ page }) => {
+ await setupImageRoutes(page, mockImages);
+ await page.goto('/images');
+
+ const totalSize = mockImages.reduce((acc, img) => acc + (img.size || 0), 0);
+
+ await expect(page.locator('p:has-text("Total Images") + p')).toHaveText(mockImages.length.toString());
+ await expect(page.locator('p:has-text("Total Size") + p')).toHaveText(formatBytes(totalSize));
+ });
+
+ test('should display the image table when images exist', async ({ page }) => {
+ await page.goto('/images');
+
+ await page.waitForLoadState('networkidle');
+
+ await expect(page.getByText('Image List')).toBeVisible();
+ await expect(page.locator('table')).toBeVisible();
+ });
+
+ test('should open the Pull Image dialog', async ({ page }) => {
+ await page.goto('/images');
+ await page.waitForLoadState('networkidle');
+ await page.locator('button:has-text("Pull Image")').first().click();
+ await expect(page.getByText('Pull Docker Image')).toBeVisible();
+ });
+
+ test('should open the Prune Unused Images dialog', async ({ page }) => {
+ await page.goto('/images');
+ await page.waitForLoadState('networkidle');
+ await page.locator('button:has-text("Prune Unused")').click();
+ await expect(page.getByText('Prune Unused Images')).toBeVisible();
+ });
+
+ test('should navigate to image details on inspect click', async ({ page }) => {
+ await page.goto('/images');
+
+ await page.waitForLoadState('networkidle');
+
+ const firstRow = page.locator('tbody tr').first();
+ await firstRow.getByRole('button', { name: 'Open menu' }).click();
+ await page.getByRole('menuitem', { name: 'Inspect' }).click();
+
+ // await expect(page).toHaveURL(`/images/${mockImages[0].id}`);
+ });
+
+ test('should call pull API on row action pull click', async ({ page }) => {
+ await page.goto('/images');
+
+ await page.waitForLoadState('networkidle');
+
+ const firstRow = page.locator('tbody tr').first();
+ await firstRow.getByRole('button', { name: 'Open menu' }).click();
+
+ const pullPromise = page.waitForRequest((req) => req.url().includes('/api/images/pull') && req.method() === 'POST');
+ await page.getByRole('menuitem', { name: 'Pull' }).click();
+ const pullRequest = await pullPromise;
+
+ expect(pullRequest).toBeTruthy();
+ const postData = pullRequest.postDataJSON();
+ expect(postData.imageRef).toBe(mockImages[0].repo); // e.g., 'nginx'
+ expect(postData.tag).toBe(mockImages[0].tag); // e.g., 'latest'
+ await expect(page.locator('div[role="status"]:has-text("Image \\"nginx:latest\\" pulled successfully.")')).toBeVisible();
+ });
+
+ test('should call remove API on row action remove click and confirmation', async ({ page }) => {
+ await page.goto('/images');
+
+ await page.waitForLoadState('networkidle');
+
+ const firstRow = page.locator('tbody tr').first();
+ await firstRow.getByRole('button', { name: 'Open menu' }).click();
+ await page.getByRole('menuitem', { name: 'Remove' }).click();
+
+ // Confirm the dialog
+ await expect(page.locator('h2:has-text("Delete Image")')).toBeVisible();
+ const removePromise = page.waitForRequest((req) => req.url().includes('/remove') && req.method() === 'DELETE');
+ await page.locator('button:has-text("Delete")').click(); // Confirmation button
+ const removeRequest = await removePromise;
+
+ expect(removeRequest).toBeTruthy();
+ expect(removeRequest.url()).toContain(`/api/images/${mockImages[0].id}/remove`);
+ const expectedIdentifier = mockImages[0].repoTags?.[0] || mockImages[0].id.substring(7, 19);
+ await expect(page.locator(`div[role="status"]:has-text("Image \\"${expectedIdentifier}\\" deleted successfully.")`)).toBeVisible();
+ });
+
+ test('should call remove API for selected images on bulk delete click', async ({ page }) => {
+ await page.goto('/images');
+
+ await page.waitForLoadState('networkidle');
+
+ // Select the first and third (unused) images
+ await page.locator('tbody tr').nth(0).locator('input[type="checkbox"]').check();
+ await page.locator('tbody tr').nth(2).locator('input[type="checkbox"]').check();
+
+ await expect(page.locator('button:has-text("Actions (2)")')).toBeVisible();
+ await page.locator('button:has-text("Actions (2)")').click();
+
+ // Expect API calls for *each* selected, non-in-use image
+ const removePromises = [page.waitForRequest((req) => req.url().includes(`/api/images/${mockImages[0].id}/remove`) && req.method() === 'DELETE'), page.waitForRequest((req) => req.url().includes(`/api/images/${mockImages[2].id}/remove`) && req.method() === 'DELETE')];
+
+ await page.locator('button:has-text("Delete Selected")').click();
+
+ // Confirm the dialog
+ await expect(page.locator('h2:has-text("Delete Selected Images")')).toBeVisible();
+ await page.locator('button:has-text("Delete")').click(); // Confirmation button
+
+ const removeRequests = await Promise.all(removePromises);
+ expect(removeRequests.length).toBe(2); // Both should be called
+
+ // Check toasts (might need slight delay or specific waiting)
+ await expect(page.locator(`div[role="status"]:has-text("Image \\"${mockImages[0].repoTags?.[0]}\\" deleted successfully.")`)).toBeVisible();
+ await expect(page.locator(`div[role="status"]:has-text("Image \\"${mockImages[2].id.substring(7, 19)}\\" deleted successfully.")`)).toBeVisible(); // Dangling image uses ID
+ });
+
+ test('should show error toast when trying to delete an in-use image (bulk)', async ({ page }) => {
+ await page.goto('/images');
+
+ await page.waitForLoadState('networkidle');
+
+ // Select the second (in-use) image
+ await page.locator('tbody tr').nth(1).locator('input[type="checkbox"]').check();
+
+ await page.locator('button:has-text("Actions (1)")').click();
+ await page.locator('button:has-text("Delete Selected")').click();
+
+ // Confirm the dialog
+ await expect(page.locator('h2:has-text("Delete Selected Images")')).toBeVisible();
+ // No API call expected here as it's checked client-side first
+ const removeRequestPromise = page.waitForRequest((req) => req.url().includes('/remove') && req.method() === 'DELETE', { timeout: 100 }); // Short timeout, expect no call
+ await page.locator('button:has-text("Delete")').click(); // Confirmation button
+
+ await expect(removeRequestPromise).rejects.toThrow(); // Expect timeout - no API call
+ const expectedIdentifier = mockImages[1].repoTags?.[0] || mockImages[1].id.substring(7, 19);
+ await expect(page.locator(`div[role="alert"]:has-text("Image \\"${expectedIdentifier}\\" is in use and cannot be deleted.")`)).toBeVisible();
+ });
+
+ test('should call prune API on prune click and confirmation', async ({ page }) => {
+ await setupImageRoutes(page, mockImages, { pruneResult: { message: 'Pruned 1 image', spaceReclaimed: 5500000 } });
+ await page.goto('/images');
+
+ await page.waitForLoadState('networkidle');
+
+ await page.locator('button:has-text("Prune Unused")').click();
+
+ // Confirm the dialog
+
+ await expect(page.getByText('Prune Unused Images')).toBeVisible();
+ const prunePromise = page.waitForRequest((req) => req.url().includes('/api/images/prune') && req.method() === 'POST');
+ await page.locator('button:has-text("Prune Images")').click(); // Confirmation button
+ const pruneRequest = await prunePromise;
+
+ expect(pruneRequest).toBeTruthy();
+ await expect(page.locator('div[role="status"]:has-text("Pruned 1 image")')).toBeVisible();
+ });
+
+ test('should pull image via dialog using EventSource', async ({ page }) => {
+ await page.goto('/images');
+
+ await page.waitForLoadState('networkidle');
+
+ await page.locator('button:has-text("Pull Image")').first().click();
+ await expect(page.getByText('Pull Docker Image')).toBeVisible();
+
+ const imageName = 'busybox';
+ const imageTag = 'latest';
+ await page.locator('input[id="image-ref"]').fill(imageName);
+ await page.locator('input[id="image-tag"]').fill(imageTag);
+
+ // Expect the EventSource request
+ const eventSourcePromise = page.waitForRequest((req) => req.url().includes(`/api/images/pull-stream/${imageName}?tag=${imageTag}`) && req.method() === 'GET');
+ await page.locator('button[type="submit"]:has-text("Pull Image")').click();
+ const eventSourceRequest = await eventSourcePromise;
+
+ expect(eventSourceRequest).toBeTruthy();
+ // Wait for the success toast which indicates the EventSource mock sent 'complete'
+ await expect(page.locator(`div[role="status"]:has-text("Image \\"${imageName}:${imageTag}\\" pulled successfully.")`)).toBeVisible();
+ // Dialog should close on success
+ await expect(page.getByText('Pull Docker Image')).not.toBeVisible();
+ });
+});
diff --git a/tests/networks.spec.ts b/tests/networks.spec.ts
new file mode 100644
index 000000000..6e7899420
--- /dev/null
+++ b/tests/networks.spec.ts
@@ -0,0 +1,92 @@
+import { test, expect } from '@playwright/test';
+
+test.describe('Network Management Page', () => {
+ test.beforeEach(async ({ page }) => {
+ await page.goto('/networks');
+ await expect(page.getByRole('heading', { name: 'Networks', level: 1 })).toBeVisible();
+ await expect(page.getByRole('link', { name: 'bridge' })).toBeVisible({ timeout: 10000 });
+ });
+
+ test('should display the main heading and description', async ({ page }) => {
+ await expect(page.getByRole('heading', { name: 'Networks', level: 1 })).toBeVisible();
+ await expect(page.getByText('Manage Docker container networking')).toBeVisible();
+ });
+
+ test('should display the "Create Network" button', async ({ page }) => {
+ await expect(page.getByRole('button', { name: 'Create Network' })).toBeVisible();
+ });
+
+ test('should display summary cards', async ({ page }) => {
+ await expect(page.getByText('Total Networks')).toBeVisible();
+ await expect(page.getByText('Bridge Networks')).toBeVisible();
+ await expect(page.getByText('Overlay Networks')).toBeVisible();
+ });
+
+ test('should display the network list card title', async ({ page }) => {
+ await expect(page.getByRole('heading', { name: 'Network List' })).toBeVisible();
+ await expect(page.getByText('Manage container communication')).toBeVisible();
+ });
+
+ test('should open the "Create Network" dialog when button is clicked', async ({ page }) => {
+ await page.waitForLoadState('networkidle');
+ await page.getByRole('button', { name: 'Create Network' }).click();
+ const dialogTitle = page.getByTestId('create-network-dialog-header');
+ await expect(dialogTitle).toBeVisible({ timeout: 10000 });
+ await expect(page.getByLabel('Name')).toBeVisible();
+ await page.getByRole('button', { name: 'Cancel' }).click();
+ await expect(dialogTitle).not.toBeVisible({ timeout: 5000 });
+ });
+
+ test('should allow searching/filtering networks', async ({ page }) => {
+ const searchInput = page.getByPlaceholder('Search networks...');
+ await expect(searchInput).toBeVisible();
+ await searchInput.fill('bridge');
+ await expect(page.getByRole('link', { name: 'bridge' })).toBeVisible();
+ await searchInput.clear();
+ await expect(page.getByRole('link', { name: 'host' })).toBeVisible();
+ });
+
+ test('should show actions menu for a network', async ({ page }) => {
+ await page.waitForLoadState('networkidle');
+ const bridgeRow = page.locator('tr', { has: page.getByRole('link', { name: 'bridge' }) });
+ const menuButton = bridgeRow.getByRole('button', { name: 'Open menu' });
+ await expect(menuButton).toBeVisible();
+ await menuButton.click();
+ await expect(page.getByRole('menuitem', { name: 'Inspect' })).toBeVisible({ timeout: 5000 });
+ });
+
+ test('should navigate to inspect page when "Inspect" is clicked', async ({ page }) => {
+ const networkLink = page.getByRole('link', { name: 'bridge' });
+ const networkName = await networkLink.textContent();
+ await expect(networkLink).toBeVisible();
+ await networkLink.click();
+ await expect(page).toHaveURL(new RegExp(`/networks/.+`), { timeout: 10000 });
+ await expect(page.getByRole('heading', { name: new RegExp(`.*${networkName}`) })).toBeVisible();
+ });
+
+ test('should allow selecting networks via checkboxes', async ({ page }) => {
+ await page.waitForLoadState('networkidle');
+ const bridgeRow = page.locator('tr', { has: page.getByRole('link', { name: 'bridge' }) });
+ const firstCheckbox = bridgeRow.getByRole('checkbox');
+ await expect(firstCheckbox).toBeVisible();
+ await firstCheckbox.click();
+ await expect(firstCheckbox).toBeChecked();
+ const actionsButton = page.getByRole('button', { name: /Group actions for 1 selected network/i });
+ await actionsButton.waitFor({ state: 'visible', timeout: 5000 });
+ await expect(actionsButton).toBeVisible();
+ });
+
+ test('should show bulk delete action when networks are selected', async ({ page }) => {
+ await page.waitForLoadState('networkidle');
+ const bridgeRow = page.locator('tr', { has: page.getByRole('link', { name: 'bridge' }) });
+ const checkbox = bridgeRow.getByRole('checkbox');
+ await expect(checkbox).toBeVisible();
+ await checkbox.click();
+ await expect(checkbox).toBeChecked();
+ const actionsButton = page.getByRole('button', { name: /Group actions for 1 selected network/i });
+ await actionsButton.waitFor({ state: 'visible', timeout: 5000 });
+ await expect(actionsButton).toBeVisible();
+ await actionsButton.click();
+ await expect(page.getByRole('menuitem', { name: 'Delete Selected' })).toBeVisible({ timeout: 5000 });
+ });
+});
diff --git a/vite.config.ts b/vite.config.ts
index 2d35c4f5a..0f611916a 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -3,5 +3,16 @@ import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
- plugins: [tailwindcss(), sveltekit()]
+ plugins: [tailwindcss(), sveltekit()],
+ optimizeDeps: {
+ exclude: ['ssh2', 'cpu-features'] // Exclude problematic dependencies
+ },
+ ssr: {
+ noExternal: ['ssh2', 'cpu-features'] // Exclude from SSR bundling
+ },
+ build: {
+ rollupOptions: {
+ external: [/\.node$/] // Explicitly mark .node files as external
+ }
+ }
});