Skip to content

Modern Docker Management, Designed for Everyone

refactor: pagination models and logic (#330)

Kyle Mendell5ad709d64233
diff --git a/backend/internal/api/container_handler.go b/backend/internal/api/container_handler.go
index 63c38f6b8..1d752e7a3 100644
--- a/backend/internal/api/container_handler.go
+++ b/backend/internal/api/container_handler.go
@@ -11,6 +11,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/services"
+ "github.com/ofkm/arcane-backend/internal/utils"
)
type ContainerHandler struct {
@@ -63,20 +64,54 @@ func (h *ContainerHandler) PullImage(c *gin.Context) {
}
func (h *ContainerHandler) List(c *gin.Context) {
- includeAll := c.Query("all") == "true"
+ var req utils.SortedPaginationRequest
+ if err := c.ShouldBindQuery(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "error": "Invalid pagination or sort parameters: " + err.Error(),
+ })
+ return
+ }
+
+ if req.Pagination.Page == 0 {
+ req.Pagination.Page = 1
+ }
+ if req.Pagination.Limit == 0 {
+ req.Pagination.Limit = 20
+ }
+
+ includeAll := true
+
+ if req.Pagination.Page == 0 && req.Pagination.Limit == 0 {
+ containers, err := h.containerService.ListContainers(c.Request.Context(), includeAll)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": err.Error(),
+ })
+ return
+ }
- containers, err := h.containerService.ListContainers(c.Request.Context(), includeAll)
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": containers,
+ })
+ return
+ }
+
+ containers, pagination, err := h.containerService.ListContainersPaginated(c.Request.Context(), req, includeAll)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "error": "Failed to list containers: " + err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": containers,
+ "success": true,
+ "data": containers,
+ "pagination": pagination,
})
}
diff --git a/backend/internal/api/container_registry_handler.go b/backend/internal/api/container_registry_handler.go
index 375b85b09..659edebd7 100644
--- a/backend/internal/api/container_registry_handler.go
+++ b/backend/internal/api/container_registry_handler.go
@@ -32,26 +32,39 @@ func NewContainerRegistryHandler(registryService *services.ContainerRegistryServ
// @Failure 500 {object} models.APIErrorResponse
// @Router /container-registries [get]
func (h *ContainerRegistryHandler) GetRegistries(c *gin.Context) {
- registries, err := h.registryService.GetAllRegistries(c.Request.Context())
+ var req utils.SortedPaginationRequest
+ if err := c.ShouldBindQuery(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "error": "Invalid pagination or sort parameters: " + err.Error(),
+ })
+ return
+ }
+
+ if req.Pagination.Page == 0 {
+ req.Pagination.Page = 1
+ }
+ if req.Pagination.Limit == 0 {
+ req.Pagination.Limit = 20
+ }
+
+ registries, pagination, err := h.registryService.GetRegistriesPaginated(c.Request.Context(), req)
if err != nil {
- apiErr := models.ToAPIError(err)
- c.JSON(apiErr.HTTPStatus(), models.APIErrorResponse{
- Success: false,
- Error: apiErr.Message,
- Code: apiErr.Code,
- Details: apiErr.Details,
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to list registries: " + err.Error(),
})
return
}
- // Don't return the encrypted tokens in the response
for i := range registries {
registries[i].Token = ""
}
- c.JSON(http.StatusOK, models.APISuccessResponse{
- Success: true,
- Data: registries,
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": registries,
+ "pagination": pagination,
})
}
@@ -81,7 +94,6 @@ func (h *ContainerRegistryHandler) GetRegistry(c *gin.Context) {
return
}
- // Don't return the encrypted token
registry.Token = ""
c.JSON(http.StatusOK, models.APISuccessResponse{
@@ -126,7 +138,6 @@ func (h *ContainerRegistryHandler) CreateRegistry(c *gin.Context) {
return
}
- // Don't return the encrypted token
registry.Token = ""
c.JSON(http.StatusCreated, models.APISuccessResponse{
@@ -176,7 +187,6 @@ func (h *ContainerRegistryHandler) UpdateRegistry(c *gin.Context) {
return
}
- // Don't return the encrypted token
registry.Token = ""
c.JSON(http.StatusOK, models.APISuccessResponse{
@@ -232,7 +242,6 @@ func (h *ContainerRegistryHandler) DeleteRegistry(c *gin.Context) {
func (h *ContainerRegistryHandler) TestRegistry(c *gin.Context) {
id := c.Param("id")
- // Get the registry
registry, err := h.registryService.GetRegistryByID(c.Request.Context(), id)
if err != nil {
apiErr := models.ToAPIError(err)
@@ -245,7 +254,6 @@ func (h *ContainerRegistryHandler) TestRegistry(c *gin.Context) {
return
}
- // Get decrypted token
decryptedToken, err := utils.Decrypt(registry.Token)
if err != nil {
apiErr := models.NewInternalServerError("Failed to decrypt token")
@@ -257,7 +265,6 @@ func (h *ContainerRegistryHandler) TestRegistry(c *gin.Context) {
return
}
- // Perform actual registry connection test using the enhanced utils
testResult, err := h.performRegistryTest(c.Request.Context(), registry, decryptedToken)
if err != nil {
apiErr := models.NewInternalServerError(fmt.Sprintf("Registry test failed: %s", err.Error()))
@@ -278,7 +285,6 @@ func (h *ContainerRegistryHandler) TestRegistry(c *gin.Context) {
// performRegistryTest performs the actual registry connection test using registry utils
func (h *ContainerRegistryHandler) performRegistryTest(ctx context.Context, registry *models.ContainerRegistry, decryptedToken string) (map[string]interface{}, error) {
- // Prepare credentials
var creds *utils.RegistryCredentials
if registry.Username != "" && decryptedToken != "" {
creds = &utils.RegistryCredentials{
@@ -287,13 +293,11 @@ func (h *ContainerRegistryHandler) performRegistryTest(ctx context.Context, regi
}
}
- // Use the enhanced registry utils to test the connection
testResult, err := utils.TestRegistryConnection(ctx, registry.URL, creds)
if err != nil {
return nil, fmt.Errorf("registry test failed: %w", err)
}
- // Convert the result to a map for JSON response
result := map[string]interface{}{
"status": getStatusString(testResult.OverallSuccess),
"url": registry.URL,
@@ -314,7 +318,6 @@ func (h *ContainerRegistryHandler) performRegistryTest(ctx context.Context, regi
result["message"] = "All registry tests passed successfully"
}
- // Add detailed test breakdown
result["tests"] = map[string]interface{}{
"connectivity": map[string]interface{}{
"success": testResult.PingSuccess,
diff --git a/backend/internal/api/environment_handler.go b/backend/internal/api/environment_handler.go
index 26a1a4f53..439614823 100644
--- a/backend/internal/api/environment_handler.go
+++ b/backend/internal/api/environment_handler.go
@@ -99,6 +99,9 @@ func (h *EnvironmentHandler) handleContainerEndpoints(c *gin.Context, endpoint s
case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/pull"):
containerHandler.PullImage(c)
return true
+ case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/logs/stream"):
+ containerHandler.GetLogsStream(c)
+ return true
case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/logs"):
containerHandler.GetLogs(c)
return true
@@ -310,13 +313,13 @@ func (h *EnvironmentHandler) handleRemoteRequest(c *gin.Context, environmentID s
req.Header.Set("X-Forwarded-Host", c.Request.Host)
req.Header.Set("X-Forwarded-Proto", c.Request.URL.Scheme)
+ q := req.URL.Query()
for key, values := range c.Request.URL.Query() {
for _, value := range values {
- q := req.URL.Query()
q.Add(key, value)
- req.URL.RawQuery = q.Encode()
}
}
+ req.URL.RawQuery = q.Encode()
resp, err := client.Do(req)
if err != nil {
@@ -612,6 +615,11 @@ func (h *EnvironmentHandler) GetContainerStatsStream(c *gin.Context) {
h.routeRequest(c, "/containers/"+containerID+"/stats/stream")
}
+func (h *EnvironmentHandler) GetContainerLogsStream(c *gin.Context) {
+ containerID := c.Param("containerId")
+ h.routeRequest(c, "/containers/"+containerID+"/logs/stream")
+}
+
// End Containers
// Images
diff --git a/backend/internal/api/image_handler.go b/backend/internal/api/image_handler.go
index 2d02eca6e..ccebef8aa 100644
--- a/backend/internal/api/image_handler.go
+++ b/backend/internal/api/image_handler.go
@@ -1,7 +1,6 @@
package api
import (
- "context"
"fmt"
"log/slog"
"net/http"
@@ -27,59 +26,35 @@ func NewImageHandler(imageService *services.ImageService, imageMaturityService *
}
func (h *ImageHandler) List(c *gin.Context) {
- dbImages, err := h.imageService.ListImagesWithMaturity(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
+ var req utils.SortedPaginationRequest
+ if err := c.ShouldBindQuery(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Failed to list images: " + err.Error(),
+ "error": "Invalid pagination or sort parameters: " + err.Error(),
})
return
}
- var result []map[string]interface{}
-
- for _, img := range dbImages {
- imageData := map[string]interface{}{
- "Id": img.ID,
- "RepoTags": img.RepoTags,
- "RepoDigests": img.RepoDigests,
- "Created": img.Created.Unix(),
- "Size": img.Size,
- "VirtualSize": img.VirtualSize,
- "Labels": img.Labels,
- "InUse": img.InUse,
- }
+ if req.Pagination.Page == 0 {
+ req.Pagination.Page = 1
+ }
+ if req.Pagination.Limit == 0 {
+ req.Pagination.Limit = 20
+ }
- if img.MaturityRecord != nil {
- imageData["maturity"] = map[string]interface{}{
- "updatesAvailable": img.MaturityRecord.UpdatesAvailable,
- "status": img.MaturityRecord.Status,
- "version": img.MaturityRecord.CurrentVersion,
- "date": img.MaturityRecord.CurrentImageDate,
- }
- } else if len(img.RepoTags) > 0 && img.RepoTags[0] != "<none>:<none>" && img.Repo != "<none>" && h.imageMaturityService != nil {
- go func(imageID string, repo string, tag string, createdTime time.Time) {
- maturityData, checkErr := h.imageMaturityService.CheckImageMaturity(context.Background(), imageID, repo, tag, createdTime)
- if checkErr == nil {
- setErr := h.imageMaturityService.SetImageMaturity(context.Background(), imageID, repo, tag, *maturityData, map[string]interface{}{
- "registryDomain": utils.ExtractRegistryDomain(repo),
- "isPrivateRegistry": utils.IsPrivateRegistry(repo),
- "currentImageDate": createdTime,
- })
- if setErr != nil {
- fmt.Printf("Error setting image maturity for %s: %v\n", imageID, setErr)
- }
- } else {
- fmt.Printf("Error checking image maturity for %s (%s:%s): %v\n", imageID, repo, tag, checkErr)
- }
- }(img.ID, img.Repo, img.Tag, img.Created)
- }
- result = append(result, imageData)
+ images, pagination, err := h.imageService.ListImagesWithMaturityPaginated(c.Request.Context(), req)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to list images: " + err.Error(),
+ })
+ return
}
c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": result,
+ "success": true,
+ "data": images,
+ "pagination": pagination,
})
}
diff --git a/backend/internal/api/image_maturity_handler.go b/backend/internal/api/image_maturity_handler.go
index 0ad617007..ccbe2396f 100644
--- a/backend/internal/api/image_maturity_handler.go
+++ b/backend/internal/api/image_maturity_handler.go
@@ -3,6 +3,7 @@ package api
import (
"net/http"
"strconv"
+ "time"
"github.com/gin-gonic/gin"
"github.com/ofkm/arcane-backend/internal/dto"
@@ -77,21 +78,30 @@ func (h *ImageMaturityHandler) GetImageMaturity(c *gin.Context) {
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": true,
- "data": map[string]interface{}{
- "id": imageID,
- "status": "Unknown",
- "updatesAvailable": false,
- "version": nil,
- "date": nil,
- "lastChecked": nil,
+ "data": models.ImageMaturity{
+ Version: "unknown",
+ Date: time.Now().Format(time.RFC3339),
+ Status: models.ImageStatusUnknown,
+ UpdatesAvailable: false,
},
})
return
}
+ maturity := models.ImageMaturity{
+ Version: record.CurrentVersion,
+ Date: record.LastChecked.Format(time.RFC3339),
+ Status: record.Status,
+ UpdatesAvailable: record.UpdatesAvailable,
+ }
+
+ if record.LatestVersion != nil {
+ maturity.LatestVersion = *record.LatestVersion
+ }
+
c.JSON(http.StatusOK, gin.H{
"success": true,
- "data": record,
+ "data": maturity,
})
}
diff --git a/backend/internal/api/network_handler.go b/backend/internal/api/network_handler.go
index a39dfed7c..b60cf7e87 100644
--- a/backend/internal/api/network_handler.go
+++ b/backend/internal/api/network_handler.go
@@ -6,6 +6,7 @@ import (
"github.com/docker/docker/api/types/network"
"github.com/gin-gonic/gin"
"github.com/ofkm/arcane-backend/internal/services"
+ "github.com/ofkm/arcane-backend/internal/utils"
)
type NetworkHandler struct {
@@ -19,38 +20,72 @@ func NewNetworkHandler(networkService *services.NetworkService) *NetworkHandler
}
func (h *NetworkHandler) List(c *gin.Context) {
+ var req utils.SortedPaginationRequest
+ if err := c.ShouldBindQuery(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "error": "Invalid pagination or sort parameters: " + err.Error(),
+ })
+ return
+ }
+
+ if req.Pagination.Page == 0 {
+ req.Pagination.Page = 1
+ }
+ if req.Pagination.Limit == 0 {
+ req.Pagination.Limit = 20
+ }
+
driver := c.Query("driver")
scope := c.Query("scope")
userDefined := c.Query("user_defined") == "true"
defaults := c.Query("defaults") == "true"
- var networks []network.Summary
- var err error
-
- switch {
- case driver != "":
- networks, err = h.networkService.GetNetworksByDriver(c.Request.Context(), driver)
- case scope != "":
- networks, err = h.networkService.GetNetworksByScope(c.Request.Context(), scope)
- case userDefined:
- networks, err = h.networkService.GetUserDefinedNetworks(c.Request.Context())
- case defaults:
- networks, err = h.networkService.GetDefaultNetworks(c.Request.Context())
- default:
- networks, err = h.networkService.ListNetworks(c.Request.Context())
+ if req.Pagination.Page == 0 && req.Pagination.Limit == 0 {
+ var networks []network.Summary
+ var err error
+
+ switch {
+ case driver != "":
+ networks, err = h.networkService.GetNetworksByDriver(c.Request.Context(), driver)
+ case scope != "":
+ networks, err = h.networkService.GetNetworksByScope(c.Request.Context(), scope)
+ case userDefined:
+ networks, err = h.networkService.GetUserDefinedNetworks(c.Request.Context())
+ case defaults:
+ networks, err = h.networkService.GetDefaultNetworks(c.Request.Context())
+ default:
+ networks, err = h.networkService.ListNetworks(c.Request.Context())
+ }
+
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": err.Error(),
+ })
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": networks,
+ })
+ return
}
+ networks, pagination, err := h.networkService.ListNetworksPaginated(c.Request.Context(), req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "error": "Failed to list networks: " + err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": networks,
+ "success": true,
+ "data": networks,
+ "pagination": pagination,
})
}
diff --git a/backend/internal/api/routes.go b/backend/internal/api/routes.go
index ce4ec6071..5533288e2 100644
--- a/backend/internal/api/routes.go
+++ b/backend/internal/api/routes.go
@@ -158,6 +158,7 @@ func setupEnvironmentRoutes(api *gin.RouterGroup, services *Services) {
environments.POST("/:id/containers/:containerId/restart", environmentHandler.RestartContainer)
environments.DELETE("/:id/containers/:containerId", environmentHandler.RemoveContainer)
environments.GET("/:id/containers/:containerId/logs", environmentHandler.GetContainerLogs)
+ environments.GET("/:id/containers/:containerId/logs/stream", environmentHandler.GetContainerLogsStream)
environments.GET("/:id/containers/:containerId/stats", environmentHandler.GetContainerStats)
environments.GET("/:id/containers/:containerId/stats/stream", environmentHandler.GetContainerStatsStream)
diff --git a/backend/internal/api/stack_handler.go b/backend/internal/api/stack_handler.go
index 161606f46..144b8b42f 100644
--- a/backend/internal/api/stack_handler.go
+++ b/backend/internal/api/stack_handler.go
@@ -12,6 +12,7 @@ import (
"github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/models"
"github.com/ofkm/arcane-backend/internal/services"
+ "github.com/ofkm/arcane-backend/internal/utils"
)
type StackHandler struct {
@@ -27,39 +28,35 @@ func NewStackHandler(stackService *services.StackService) *StackHandler {
}
func (h *StackHandler) ListStacks(c *gin.Context) {
- stacks, err := h.stackService.ListStacks(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
+ var req utils.SortedPaginationRequest
+ if err := c.ShouldBindQuery(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": fmt.Sprintf("Failed to fetch stacks: %v", err),
+ "error": "Invalid pagination or sort parameters: " + err.Error(),
})
return
}
- var stackList []map[string]interface{}
- for _, stack := range stacks {
- stackResponse := map[string]interface{}{
- "id": stack.ID,
- "name": stack.Name,
- "path": stack.Path,
- "status": stack.Status,
- "serviceCount": stack.ServiceCount,
- "runningCount": stack.RunningCount,
- "createdAt": stack.CreatedAt,
- "updatedAt": stack.UpdatedAt,
- "autoUpdate": stack.AutoUpdate,
- "isExternal": stack.IsExternal,
- "isLegacy": stack.IsLegacy,
- "isRemote": stack.IsRemote,
- "services": nil, // Services are not fetched in the list view for performance.
- }
- stackList = append(stackList, stackResponse)
+ if req.Pagination.Page == 0 {
+ req.Pagination.Page = 1
+ }
+ if req.Pagination.Limit == 0 {
+ req.Pagination.Limit = 20
+ }
+
+ stacks, pagination, err := h.stackService.ListStacksPaginated(c.Request.Context(), req)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to list stacks: " + err.Error(),
+ })
+ return
}
c.JSON(http.StatusOK, gin.H{
- "success": true,
- "stacks": stackList,
- "count": len(stackList),
+ "success": true,
+ "data": stacks,
+ "pagination": pagination,
})
}
@@ -534,10 +531,8 @@ func (h *StackHandler) ConvertDockerRun(c *gin.Context) {
}
func (h *StackHandler) GetStackLogsStream(c *gin.Context) {
- stackID := c.Param("id")
- if stackID == "" {
- stackID = c.Param("stackId")
- }
+
+ stackID := c.Param("stackId")
follow := c.Query("follow") == "true"
tail := c.DefaultQuery("tail", "100")
diff --git a/backend/internal/api/system_handler.go b/backend/internal/api/system_handler.go
index fa794fbe5..48afc5a8a 100644
--- a/backend/internal/api/system_handler.go
+++ b/backend/internal/api/system_handler.go
@@ -156,32 +156,34 @@ func (h *SystemHandler) GetDockerInfo(c *gin.Context) {
return
}
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "version": version.Version,
- "apiVersion": version.APIVersion,
- "gitCommit": version.GitCommit,
- "goVersion": version.GoVersion,
- "os": version.Os,
- "arch": version.Arch,
- "buildTime": version.BuildTime,
- "containers": len(containers),
- "containersRunning": info.ContainersRunning,
- "containersPaused": info.ContainersPaused,
- "containersStopped": info.ContainersStopped,
- "images": len(images),
- "storageDriver": info.Driver,
- "loggingDriver": info.LoggingDriver,
- "cgroupDriver": info.CgroupDriver,
- "cgroupVersion": info.CgroupVersion,
- "kernelVersion": info.KernelVersion,
- "operatingSystem": info.OperatingSystem,
- "osVersion": info.OSVersion,
- "serverVersion": info.ServerVersion,
- "architecture": info.Architecture,
- "cpus": info.NCPU,
- "memTotal": info.MemTotal,
- })
+ dockerInfo := dto.DockerInfoDto{
+ Success: true,
+ Version: version.Version,
+ APIVersion: version.APIVersion,
+ GitCommit: version.GitCommit,
+ GoVersion: version.GoVersion,
+ OS: version.Os,
+ Arch: version.Arch,
+ BuildTime: version.BuildTime,
+ Containers: len(containers),
+ ContainersRunning: info.ContainersRunning,
+ ContainersPaused: info.ContainersPaused,
+ ContainersStopped: info.ContainersStopped,
+ Images: len(images),
+ StorageDriver: info.Driver,
+ LoggingDriver: info.LoggingDriver,
+ CgroupDriver: info.CgroupDriver,
+ CgroupVersion: info.CgroupVersion,
+ KernelVersion: info.KernelVersion,
+ OperatingSystem: info.OperatingSystem,
+ OSVersion: info.OSVersion,
+ ServerVersion: info.ServerVersion,
+ Architecture: info.Architecture,
+ CPUs: info.NCPU,
+ MemTotal: info.MemTotal,
+ }
+
+ c.JSON(http.StatusOK, dockerInfo)
}
func (h *SystemHandler) TestDockerConnection(c *gin.Context) {
diff --git a/backend/internal/api/user_handler.go b/backend/internal/api/user_handler.go
index 1dfd818d3..bfcb0ab25 100644
--- a/backend/internal/api/user_handler.go
+++ b/backend/internal/api/user_handler.go
@@ -9,6 +9,7 @@ import (
"github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/models"
"github.com/ofkm/arcane-backend/internal/services"
+ "github.com/ofkm/arcane-backend/internal/utils"
)
type UserHandler struct {
@@ -22,30 +23,63 @@ func NewUserHandler(userService *services.UserService) *UserHandler {
}
func (h *UserHandler) ListUsers(c *gin.Context) {
- users, err := h.userService.ListUsers(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
+ var req utils.SortedPaginationRequest
+ if err := c.ShouldBindQuery(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Failed to fetch users",
+ "error": "Invalid pagination or sort parameters: " + err.Error(),
})
return
}
- var userResponses []UserResponse
- for _, user := range users {
- userResponses = append(userResponses, UserResponse{
- ID: user.ID,
- Username: user.Username,
- DisplayName: user.DisplayName,
- Email: user.Email,
- Roles: user.Roles,
+ if req.Pagination.Page == 0 {
+ req.Pagination.Page = 1
+ }
+ if req.Pagination.Limit == 0 {
+ req.Pagination.Limit = 20
+ }
+
+ if req.Pagination.Page == 0 && req.Pagination.Limit == 0 {
+ users, err := h.userService.ListUsers(c.Request.Context())
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to fetch users",
+ })
+ return
+ }
+
+ var userResponses []UserResponse
+ for _, user := range users {
+ userResponses = append(userResponses, UserResponse{
+ ID: user.ID,
+ Username: user.Username,
+ DisplayName: user.DisplayName,
+ Email: user.Email,
+ Roles: user.Roles,
+ })
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": userResponses,
})
+ return
+ }
+
+ users, pagination, err := h.userService.ListUsersPaginated(c.Request.Context(), req)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to list users: " + err.Error(),
+ })
+ return
}
c.JSON(http.StatusOK, gin.H{
- "success": true,
- "users": userResponses,
- "count": len(userResponses),
+ "success": true,
+ "data": users,
+ "pagination": pagination,
})
}
diff --git a/backend/internal/api/volume_handler.go b/backend/internal/api/volume_handler.go
index 7e01df73c..addc71316 100644
--- a/backend/internal/api/volume_handler.go
+++ b/backend/internal/api/volume_handler.go
@@ -1,9 +1,12 @@
package api
import (
+ "net/http"
+
"github.com/docker/docker/api/types/volume"
"github.com/gin-gonic/gin"
"github.com/ofkm/arcane-backend/internal/services"
+ "github.com/ofkm/arcane-backend/internal/utils"
)
type VolumeHandler struct {
@@ -17,27 +20,64 @@ func NewVolumeHandler(volumeService *services.VolumeService) *VolumeHandler {
}
func (h *VolumeHandler) List(c *gin.Context) {
- driver := c.Query("driver")
+ var req utils.SortedPaginationRequest
+ if err := c.ShouldBindQuery(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "error": "Invalid pagination or sort parameters: " + err.Error(),
+ })
+ return
+ }
- var volumes []volume.Volume
- var err error
+ if req.Pagination.Page == 0 {
+ req.Pagination.Page = 1
+ }
+ if req.Pagination.Limit == 0 {
+ req.Pagination.Limit = 20
+ }
- if driver != "" {
- volumes, err = h.volumeService.GetVolumesByDriver(c.Request.Context(), driver)
- } else {
- volumes, err = h.volumeService.ListVolumes(c.Request.Context())
+ driver := c.Query("driver")
+
+ if req.Pagination.Page == 0 && req.Pagination.Limit == 0 {
+ volumes, err := h.volumeService.ListVolumesWithUsage(c.Request.Context())
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": err.Error(),
+ })
+ return
+ }
+
+ if driver != "" {
+ filtered := make([]map[string]interface{}, 0)
+ for _, vol := range volumes {
+ if volDriver, ok := vol["Driver"].(string); ok && volDriver == driver {
+ filtered = append(filtered, vol)
+ }
+ }
+ volumes = filtered
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": volumes,
+ })
+ return
}
+ volumes, pagination, err := h.volumeService.ListVolumesPaginated(c.Request.Context(), req)
if err != nil {
- c.JSON(500, gin.H{
- "error": err.Error(),
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to list volumes: " + err.Error(),
})
return
}
- c.JSON(200, gin.H{
- "success": true,
- "data": volumes,
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": volumes,
+ "pagination": pagination,
})
}
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index 5a147f0e1..7840a9b00 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -81,7 +81,7 @@ func InitializeApp() (*App, error) {
log.Printf("Warning: failed to create default admin user: %v", err)
}
- if cfg.PublicOidcEnabled {
+ if cfg.OidcEnabled {
if err := appServices.Auth.SyncOidcEnvToDatabase(context.Background()); err != nil {
log.Printf("⚠️ Warning: Failed to sync OIDC environment variables to database: %v", err)
}
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index 623f23081..7b1b7d70d 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -12,7 +12,7 @@ type Config struct {
Environment string
JWTSecret string
- PublicOidcEnabled bool
+ OidcEnabled bool
OidcClientID string
OidcClientSecret string
OidcRedirectURI string
@@ -25,7 +25,7 @@ type Config struct {
}
func Load() *Config {
- publicOidcEnabled, _ := strconv.ParseBool(os.Getenv("PUBLIC_OIDC_ENABLED"))
+ publicOidcEnabled, _ := strconv.ParseBool(os.Getenv("OIDC_ENABLED"))
return &Config{
AppUrl: getEnvOrDefault("APP_URL", "http://localhost:8080"),
@@ -35,7 +35,7 @@ func Load() *Config {
JWTSecret: getEnvOrDefault("JWT_SECRET", "default-jwt-secret-change-me"),
EncryptionKey: getEnvOrDefault("ENCRYPTION_KEY", "arcane-dev-key-32-characters!!!"),
- PublicOidcEnabled: publicOidcEnabled,
+ OidcEnabled: publicOidcEnabled,
OidcClientID: os.Getenv("OIDC_CLIENT_ID"),
OidcClientSecret: os.Getenv("OIDC_CLIENT_SECRET"),
OidcRedirectURI: os.Getenv("OIDC_REDIRECT_URI"),
diff --git a/backend/internal/dto/docker_info_dto.go b/backend/internal/dto/docker_info_dto.go
new file mode 100644
index 000000000..c9a782ea1
--- /dev/null
+++ b/backend/internal/dto/docker_info_dto.go
@@ -0,0 +1,28 @@
+package dto
+
+type DockerInfoDto struct {
+ Success bool `json:"success"`
+ Version string `json:"version"`
+ APIVersion string `json:"apiVersion"`
+ GitCommit string `json:"gitCommit"`
+ GoVersion string `json:"goVersion"`
+ OS string `json:"os"`
+ Arch string `json:"arch"`
+ BuildTime string `json:"buildTime"`
+ Containers int `json:"containers"`
+ ContainersRunning int `json:"containersRunning"`
+ ContainersPaused int `json:"containersPaused"`
+ ContainersStopped int `json:"containersStopped"`
+ Images int `json:"images"`
+ StorageDriver string `json:"storageDriver"`
+ LoggingDriver string `json:"loggingDriver"`
+ CgroupDriver string `json:"cgroupDriver"`
+ CgroupVersion string `json:"cgroupVersion"`
+ KernelVersion string `json:"kernelVersion"`
+ OperatingSystem string `json:"operatingSystem"`
+ OSVersion string `json:"osVersion"`
+ ServerVersion string `json:"serverVersion"`
+ Architecture string `json:"architecture"`
+ CPUs int `json:"cpus"`
+ MemTotal int64 `json:"memTotal"`
+}
diff --git a/backend/internal/dto/settings_dto.go b/backend/internal/dto/settings_dto.go
index 830701759..5ec84a602 100644
--- a/backend/internal/dto/settings_dto.go
+++ b/backend/internal/dto/settings_dto.go
@@ -3,7 +3,6 @@ package dto
import "github.com/ofkm/arcane-backend/internal/models"
type UpdateSettingsDto struct {
- DockerHost *string `json:"dockerHost,omitempty"`
StacksDirectory *string `json:"stacksDirectory,omitempty"`
AutoUpdate *bool `json:"autoUpdate,omitempty"`
AutoUpdateInterval *int `json:"autoUpdateInterval,omitempty"`
diff --git a/backend/internal/models/container_registry.go b/backend/internal/models/container_registry.go
index b2d19632a..4709e7d74 100644
--- a/backend/internal/models/container_registry.go
+++ b/backend/internal/models/container_registry.go
@@ -5,15 +5,15 @@ import (
)
type ContainerRegistry struct {
- ID string `json:"id" gorm:"primaryKey"`
- URL string `json:"url" gorm:"not null"`
- Username string `json:"username" gorm:"not null"`
+ ID string `json:"id" gorm:"primaryKey" sortable:"true"`
+ URL string `json:"url" gorm:"not null" sortable:"true"`
+ Username string `json:"username" gorm:"not null" sortable:"true"`
Token string `json:"token" gorm:"not null"`
- Description *string `json:"description,omitempty"`
- Insecure bool `json:"insecure" gorm:"default:false"`
- Enabled bool `json:"enabled" gorm:"default:true"`
- CreatedAt time.Time `json:"createdAt"`
- UpdatedAt time.Time `json:"updatedAt"`
+ Description *string `json:"description,omitempty" sortable:"true"`
+ Insecure bool `json:"insecure" gorm:"default:false" sortable:"true"`
+ Enabled bool `json:"enabled" gorm:"default:true" sortable:"true"`
+ CreatedAt time.Time `json:"createdAt" sortable:"true"`
+ UpdatedAt time.Time `json:"updatedAt" sortable:"true"`
}
func (ContainerRegistry) TableName() string {
diff --git a/backend/internal/models/docker.go b/backend/internal/models/docker.go
index c1bfdb07b..8499df168 100644
--- a/backend/internal/models/docker.go
+++ b/backend/internal/models/docker.go
@@ -9,10 +9,10 @@ import (
type Container struct {
ID string `json:"id" gorm:"primaryKey;type:text"`
- Name string `json:"name" gorm:"not null"`
- Image string `json:"image" gorm:"not null"`
- Status string `json:"status" gorm:"not null"`
- State string `json:"state" gorm:"not null"`
+ Name string `json:"name" gorm:"not null" sortable:"true"`
+ Image string `json:"image" gorm:"not null" sortable:"true"`
+ Status string `json:"status" gorm:"not null" sortable:"true"`
+ State string `json:"state" gorm:"not null" sortable:"true"`
Ports JSON `json:"ports,omitempty" gorm:"type:text"`
Mounts JSON `json:"mounts,omitempty" gorm:"type:text"`
Networks StringSlice `json:"networks,omitempty" gorm:"type:text"`
@@ -20,8 +20,8 @@ type Container struct {
Environment StringSlice `json:"environment,omitempty" gorm:"type:text"`
Command StringSlice `json:"command,omitempty" gorm:"type:text"`
StackID *string `json:"stackId,omitempty" gorm:"column:stack_id;index"`
- CreatedAt time.Time `json:"createdAt" gorm:"not null"`
- StartedAt *time.Time `json:"startedAt,omitempty" gorm:"column:started_at"`
+ CreatedAt time.Time `json:"createdAt" gorm:"not null" sortable:"true"`
+ StartedAt *time.Time `json:"startedAt,omitempty" gorm:"column:started_at" sortable:"true"`
Stack *Stack `json:"stack,omitempty" gorm:"foreignKey:StackID;references:ID"`
@@ -75,14 +75,14 @@ type Image struct {
ID string `json:"id" gorm:"primaryKey;type:text"`
RepoTags StringSlice `json:"repoTags" gorm:"type:text"`
RepoDigests StringSlice `json:"repoDigests,omitempty" gorm:"type:text"`
- Size int64 `json:"size" gorm:"not null"`
+ Size int64 `json:"size" gorm:"not null" sortable:"true"`
VirtualSize int64 `json:"virtualSize" gorm:"column:virtual_size"`
Labels JSON `json:"labels,omitempty" gorm:"type:text"`
- Created time.Time `json:"created" gorm:"not null"`
+ Created time.Time `json:"created" gorm:"not null" sortable:"true"`
- Repo string `json:"repo" gorm:"column:repo;index"`
- Tag string `json:"tag" gorm:"column:tag;index"`
- InUse bool `json:"inUse" gorm:"column:in_use;default:false"`
+ Repo string `json:"repo" gorm:"column:repo;index" sortable:"true"`
+ Tag string `json:"tag" gorm:"column:tag;index" sortable:"true"`
+ InUse bool `json:"inUse" gorm:"column:in_use;default:false" sortable:"true"`
MaturityRecord *ImageMaturityRecord `json:"maturityRecord,omitempty" gorm:"foreignKey:ID;references:ID"`
diff --git a/backend/internal/models/stack.go b/backend/internal/models/stack.go
index 0efe8c162..a0eb74ff1 100644
--- a/backend/internal/models/stack.go
+++ b/backend/internal/models/stack.go
@@ -45,13 +45,13 @@ const (
type Stack struct {
ID string `json:"id" gorm:"primaryKey"`
- Name string `json:"name" gorm:"not null"`
+ Name string `json:"name" gorm:"not null" sortable:"true"`
DirName *string `json:"dir_name" gorm:"unique"`
Path string `json:"path" gorm:"not null"`
- Status StackStatus `json:"status"`
- ServiceCount int `json:"service_count"`
- RunningCount int `json:"running_count"`
- AutoUpdate bool `json:"auto_update"`
+ Status StackStatus `json:"status" sortable:"true"`
+ ServiceCount int `json:"service_count" sortable:"true"`
+ RunningCount int `json:"running_count" sortable:"true"`
+ AutoUpdate bool `json:"auto_update" sortable:"true"`
IsExternal bool `json:"is_external"`
IsLegacy bool `json:"is_legacy"`
IsRemote bool `json:"is_remote"`
diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.go
index 0946938ca..f379aaaf1 100644
--- a/backend/internal/services/auth_service.go
+++ b/backend/internal/services/auth_service.go
@@ -61,6 +61,15 @@ type OidcStatusInfo struct {
EffectivelyConfigured bool `json:"effectivelyConfigured"`
}
+type UserClaims struct {
+ jwt.RegisteredClaims
+ UserID string `json:"user_id"`
+ Username string `json:"username"`
+ Email string `json:"email,omitempty"`
+ DisplayName string `json:"display_name,omitempty"`
+ Roles []string `json:"roles"`
+}
+
// AuthService handles authentication related operations
type AuthService struct {
userService *UserService
@@ -94,8 +103,8 @@ func NewAuthService(userService *UserService, settingsService *SettingsService,
}
func (s *AuthService) SyncOidcEnvToDatabase(ctx context.Context) error {
- if !s.config.PublicOidcEnabled {
- return errors.New("OIDC sync called but PUBLIC_OIDC_ENABLED is false")
+ if !s.config.OidcEnabled {
+ return errors.New("OIDC sync called but OIDC_ENABLED is false")
}
settings, err := s.settingsService.GetSettings(ctx)
@@ -136,7 +145,6 @@ func (s *AuthService) SyncOidcEnvToDatabase(ctx context.Context) error {
currentAuthMap["oidcEnabled"] = true
currentAuthMap["oidc"] = oidcConfigMap
- // Assign directly - no need to marshal again
settings.Auth = models.JSON(currentAuthMap)
_, err = s.settingsService.UpdateSettings(ctx, settings)
@@ -178,7 +186,7 @@ func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error
}, nil
}
- if s.config.PublicOidcEnabled && !effectiveAuthSettings.OidcEnabled {
+ if s.config.OidcEnabled && !effectiveAuthSettings.OidcEnabled {
log.Printf("Warning: PUBLIC_OIDC_ENABLED is true, but effective OIDC settings from DB show oidcEnabled=false. This might indicate an issue with the initial sync or subsequent manual changes.")
}
@@ -188,7 +196,7 @@ func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error
func (s *AuthService) GetOidcConfigurationStatus(ctx context.Context) (*OidcStatusInfo, error) {
status := &OidcStatusInfo{}
- status.EnvForced = s.config.PublicOidcEnabled
+ status.EnvForced = s.config.OidcEnabled
if status.EnvForced {
// This reflects if the env vars themselves were complete at load time
status.EnvConfigured = s.config.OidcClientID != "" &&
@@ -507,7 +515,7 @@ func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string) (*T
// VerifyToken verifies and returns the user from an access token
func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*models.User, error) {
- token, err := jwt.ParseWithClaims(accessToken, &jwt.RegisteredClaims{},
+ token, err := jwt.ParseWithClaims(accessToken, &UserClaims{},
func(t *jwt.Token) (interface{}, error) {
return s.jwtSecret, nil
})
@@ -523,7 +531,7 @@ func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*mod
return nil, ErrInvalidToken
}
- claims, ok := token.Claims.(*jwt.RegisteredClaims)
+ claims, ok := token.Claims.(*UserClaims)
if !ok {
return nil, errors.New("invalid token claims")
}
@@ -532,14 +540,18 @@ func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*mod
return nil, errors.New("not an access token")
}
- userId := claims.ID
- if userId == "" {
- return nil, errors.New("missing user ID in token")
+ user := &models.User{
+ ID: claims.UserID,
+ Username: claims.Username,
+ Roles: models.StringSlice(claims.Roles),
}
- user, err := s.userService.GetUserByID(ctx, userId)
- if err != nil {
- return nil, err
+ if claims.Email != "" {
+ user.Email = &claims.Email
+ }
+
+ if claims.DisplayName != "" {
+ user.DisplayName = &claims.DisplayName
}
return user, nil
@@ -585,12 +597,27 @@ func (s *AuthService) generateTokenPair(ctx context.Context, user *models.User)
accessTokenExpiry := time.Now().Add(time.Duration(sessionTimeout) * time.Minute)
- accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
- ID: user.ID,
- Subject: "access",
- IssuedAt: jwt.NewNumericDate(time.Now()),
- ExpiresAt: jwt.NewNumericDate(accessTokenExpiry),
- })
+ userClaims := UserClaims{
+ RegisteredClaims: jwt.RegisteredClaims{
+ ID: user.ID,
+ Subject: "access",
+ IssuedAt: jwt.NewNumericDate(time.Now()),
+ ExpiresAt: jwt.NewNumericDate(accessTokenExpiry),
+ },
+ UserID: user.ID,
+ Username: user.Username,
+ Roles: []string(user.Roles),
+ }
+
+ if user.Email != nil {
+ userClaims.Email = *user.Email
+ }
+
+ if user.DisplayName != nil {
+ userClaims.DisplayName = *user.DisplayName
+ }
+
+ accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, userClaims)
accessTokenString, err := accessToken.SignedString(s.jwtSecret)
if err != nil {
diff --git a/backend/internal/services/container_registry_service.go b/backend/internal/services/container_registry_service.go
index 3776cd3f6..81359f328 100644
--- a/backend/internal/services/container_registry_service.go
+++ b/backend/internal/services/container_registry_service.go
@@ -3,6 +3,7 @@ package services
import (
"context"
"fmt"
+ "strings"
"time"
"github.com/google/uuid"
@@ -19,7 +20,6 @@ func NewContainerRegistryService(db *database.DB) *ContainerRegistryService {
return &ContainerRegistryService{db: db}
}
-// generateID generates a unique ID for container registries
func generateID() string {
return uuid.New().String()
}
@@ -32,6 +32,23 @@ func (s *ContainerRegistryService) GetAllRegistries(ctx context.Context) ([]mode
return registries, nil
}
+func (s *ContainerRegistryService) GetRegistriesPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]models.ContainerRegistry, utils.PaginationResponse, error) {
+ var registries []models.ContainerRegistry
+ query := s.db.WithContext(ctx).Model(&models.ContainerRegistry{})
+
+ if req.Search != "" {
+ searchTerm := "%" + strings.ToLower(req.Search) + "%"
+ query = query.Where("LOWER(url) LIKE ? OR LOWER(username) LIKE ? OR LOWER(description) LIKE ?", searchTerm, searchTerm, searchTerm)
+ }
+
+ pagination, err := utils.PaginateAndSort(req, query, &registries)
+ if err != nil {
+ return nil, utils.PaginationResponse{}, fmt.Errorf("failed to paginate container registries: %w", err)
+ }
+
+ return registries, pagination, nil
+}
+
func (s *ContainerRegistryService) GetRegistryByID(ctx context.Context, id string) (*models.ContainerRegistry, error) {
var registry models.ContainerRegistry
if err := s.db.WithContext(ctx).Where("id = ?", id).First(&registry).Error; err != nil {
diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.go
index 38b7439ed..69ffa9099 100644
--- a/backend/internal/services/container_service.go
+++ b/backend/internal/services/container_service.go
@@ -10,12 +10,14 @@ import (
"strings"
"time"
+ "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/pkg/stdcopy"
"github.com/ofkm/arcane-backend/internal/database"
"github.com/ofkm/arcane-backend/internal/models"
+ "github.com/ofkm/arcane-backend/internal/utils"
)
type ContainerService struct {
@@ -54,7 +56,7 @@ func (s *ContainerService) PullContainerImage(ctx context.Context, containerID s
return err
}
-func (s *ContainerService) ListContainers(ctx context.Context, includeAll bool) ([]container.Summary, error) {
+func (s *ContainerService) ListContainers(ctx context.Context, includeAll bool) ([]types.Container, error) {
dockerClient, err := s.dockerService.CreateConnection(ctx)
if err != nil {
return nil, fmt.Errorf("failed to connect to Docker: %w", err)
@@ -432,3 +434,95 @@ func (s *ContainerService) readAllLogs(logs io.ReadCloser, logsChan chan<- strin
return nil
}
+
+func (s *ContainerService) ListContainersPaginated(ctx context.Context, req utils.SortedPaginationRequest, includeAll bool) ([]map[string]interface{}, utils.PaginationResponse, error) {
+ dockerContainers, err := s.ListContainers(ctx, includeAll)
+ if err != nil {
+ return nil, utils.PaginationResponse{}, fmt.Errorf("failed to list Docker containers: %w", err)
+ }
+
+ var result []map[string]interface{}
+ for _, dockerContainer := range dockerContainers {
+ containerData := map[string]interface{}{
+ "Id": dockerContainer.ID,
+ "Names": dockerContainer.Names,
+ "Image": dockerContainer.Image,
+ "ImageID": dockerContainer.ImageID,
+ "Command": dockerContainer.Command,
+ "Created": dockerContainer.Created,
+ "Ports": dockerContainer.Ports,
+ "Labels": dockerContainer.Labels,
+ "State": dockerContainer.State,
+ "Status": dockerContainer.Status,
+ "HostConfig": map[string]interface{}{
+ "NetworkMode": dockerContainer.HostConfig.NetworkMode,
+ },
+ "NetworkSettings": map[string]interface{}{
+ "Networks": dockerContainer.NetworkSettings.Networks,
+ },
+ "Mounts": dockerContainer.Mounts,
+ }
+
+ result = append(result, containerData)
+ }
+
+ if req.Search != "" {
+ filtered := make([]map[string]interface{}, 0)
+ searchLower := strings.ToLower(req.Search)
+ for _, container := range result {
+ if names, ok := container["Names"].([]string); ok {
+ for _, name := range names {
+ if strings.Contains(strings.ToLower(name), searchLower) {
+ filtered = append(filtered, container)
+ break
+ }
+ }
+ }
+ if image, ok := container["Image"].(string); ok {
+ if strings.Contains(strings.ToLower(image), searchLower) {
+ filtered = append(filtered, container)
+ continue
+ }
+ }
+ if state, ok := container["State"].(string); ok {
+ if strings.Contains(strings.ToLower(state), searchLower) {
+ filtered = append(filtered, container)
+ continue
+ }
+ }
+ }
+ result = filtered
+ }
+
+ totalItems := len(result)
+
+ if req.Sort.Column != "" {
+ utils.SortSliceByField(result, req.Sort.Column, req.Sort.Direction)
+ }
+
+ startIdx := (req.Pagination.Page - 1) * req.Pagination.Limit
+ endIdx := startIdx + req.Pagination.Limit
+
+ if startIdx > len(result) {
+ startIdx = len(result)
+ }
+ if endIdx > len(result) {
+ endIdx = len(result)
+ }
+
+ if startIdx < endIdx {
+ result = result[startIdx:endIdx]
+ } else {
+ result = []map[string]interface{}{}
+ }
+
+ totalPages := (totalItems + req.Pagination.Limit - 1) / req.Pagination.Limit
+ pagination := utils.PaginationResponse{
+ TotalPages: int64(totalPages),
+ TotalItems: int64(totalItems),
+ CurrentPage: req.Pagination.Page,
+ ItemsPerPage: req.Pagination.Limit,
+ }
+
+ return result, pagination, nil
+}
diff --git a/backend/internal/services/image_maturity_service.go b/backend/internal/services/image_maturity_service.go
index 83ff10fe9..660fdbb6a 100644
--- a/backend/internal/services/image_maturity_service.go
+++ b/backend/internal/services/image_maturity_service.go
@@ -45,14 +45,6 @@ func (s *ImageMaturityService) CheckImageMaturity(ctx context.Context, imageID,
return nil, fmt.Errorf("failed to get settings: %w", err)
}
- maturityThresholdDays := settings.MaturityThresholdDays
- if maturityThresholdDays == 0 {
- maturityThresholdDays = 30
- }
-
- imageAge := time.Since(imageCreatedAt)
- isMaturedByAge := imageAge > time.Duration(maturityThresholdDays)*24*time.Hour
-
hasUpdates := false
latestVersion := ""
var checkError error
@@ -76,7 +68,8 @@ func (s *ImageMaturityService) CheckImageMaturity(ctx context.Context, imageID,
}
}
- status := s.determineMaturityStatus(isMaturedByAge, hasUpdates, checkError)
+ // Pass settings to determine status
+ status := s.determineMaturityStatus(imageCreatedAt, hasUpdates, checkError, settings)
maturity := &models.ImageMaturity{
Version: tag,
@@ -86,13 +79,18 @@ func (s *ImageMaturityService) CheckImageMaturity(ctx context.Context, imageID,
LatestVersion: latestVersion,
}
+ // Calculate age for metadata
+ imageAge := time.Since(imageCreatedAt)
+ daysSinceCreation := int(imageAge.Hours() / 24)
+ isMaturedByAge := imageAge > time.Duration(settings.MaturityThresholdDays)*24*time.Hour
+
metadata := map[string]interface{}{
"registryDomain": utils.ExtractRegistryDomain(repository),
"isPrivateRegistry": s.isPrivateRegistry(repository),
"currentImageDate": imageCreatedAt,
- "daysSinceCreation": int(imageAge.Hours() / 24),
+ "daysSinceCreation": daysSinceCreation,
"isMaturedByAge": isMaturedByAge,
- "maturityThreshold": maturityThresholdDays,
+ "maturityThreshold": settings.MaturityThresholdDays,
}
if registryManifest != nil {
@@ -416,22 +414,31 @@ func (s *ImageMaturityService) hasNewerVersions(currentTag string, allTags []str
return hasNewer, newestTag
}
-func (s *ImageMaturityService) determineMaturityStatus(isMaturedByAge, hasUpdates bool, checkError error) string {
+func (s *ImageMaturityService) determineMaturityStatus(imageCreatedAt time.Time, hasUpdates bool, checkError error, settings *models.Settings) string {
+ maturityThresholdDays := settings.MaturityThresholdDays
+ if maturityThresholdDays == 0 {
+ maturityThresholdDays = 30 // Default fallback
+ }
+
+ imageAge := time.Since(imageCreatedAt)
+ isMaturedByAge := imageAge > time.Duration(maturityThresholdDays)*24*time.Hour
+
+ // If there's a check error, return Unknown
if checkError != nil {
- if isMaturedByAge {
- return models.ImageStatusMatured
- }
- return models.ImageStatusError
+ return models.ImageStatusUnknown
}
+ // If image is matured by age threshold, it's matured regardless of updates
if isMaturedByAge {
return models.ImageStatusMatured
}
+ // If image hasn't reached maturity threshold but has updates, it's still not matured
if hasUpdates {
- return models.ImageStatusMatured
+ return models.ImageStatusNotMatured
}
+ // Image is within threshold and no updates available
return models.ImageStatusNotMatured
}
diff --git a/backend/internal/services/image_service.go b/backend/internal/services/image_service.go
index 9c3e95dc6..5cfcbdd15 100644
--- a/backend/internal/services/image_service.go
+++ b/backend/internal/services/image_service.go
@@ -19,6 +19,7 @@ import (
"github.com/docker/docker/client"
"github.com/ofkm/arcane-backend/internal/database"
"github.com/ofkm/arcane-backend/internal/models"
+ "github.com/ofkm/arcane-backend/internal/utils"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
@@ -537,3 +538,47 @@ func (s *ImageService) DeleteImageByDockerID(ctx context.Context, dockerImageID
}
return nil
}
+
+func (s *ImageService) ListImagesWithMaturityPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]map[string]interface{}, utils.PaginationResponse, error) {
+ _, err := s.ListImages(ctx)
+ if err != nil {
+ return nil, utils.PaginationResponse{}, fmt.Errorf("failed to list and sync Docker images: %w", err)
+ }
+
+ var images []*models.Image
+ query := s.db.WithContext(ctx).Model(&models.Image{}).Preload("MaturityRecord")
+
+ pagination, err := utils.PaginateAndSort(req, query, &images)
+ if err != nil {
+ return nil, utils.PaginationResponse{}, fmt.Errorf("failed to paginate images: %w", err)
+ }
+
+ var result []map[string]interface{}
+ for _, img := range images {
+ imageData := map[string]interface{}{
+ "Id": img.ID,
+ "RepoTags": img.RepoTags,
+ "RepoDigests": img.RepoDigests,
+ "Created": img.Created.Unix(),
+ "Size": img.Size,
+ "VirtualSize": img.VirtualSize,
+ "Labels": img.Labels,
+ "InUse": img.InUse,
+ "Repo": img.Repo,
+ "Tag": img.Tag,
+ }
+
+ if img.MaturityRecord != nil {
+ imageData["maturity"] = map[string]interface{}{
+ "updatesAvailable": img.MaturityRecord.UpdatesAvailable,
+ "status": img.MaturityRecord.Status,
+ "version": img.MaturityRecord.CurrentVersion,
+ "date": img.MaturityRecord.CurrentImageDate,
+ }
+ }
+
+ result = append(result, imageData)
+ }
+
+ return result, pagination, nil
+}
diff --git a/backend/internal/services/network_service.go b/backend/internal/services/network_service.go
index 2f069434e..36df68b4e 100644
--- a/backend/internal/services/network_service.go
+++ b/backend/internal/services/network_service.go
@@ -3,10 +3,12 @@ package services
import (
"context"
"fmt"
+ "strings"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/network"
"github.com/ofkm/arcane-backend/internal/database"
+ "github.com/ofkm/arcane-backend/internal/utils"
)
type NetworkService struct {
@@ -221,3 +223,90 @@ func (s *NetworkService) GetUserDefinedNetworks(ctx context.Context) ([]network.
return userDefined, nil
}
+
+// ListNetworksPaginated returns paginated Docker networks
+func (s *NetworkService) ListNetworksPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]map[string]interface{}, utils.PaginationResponse, error) {
+ networks, err := s.ListNetworks(ctx)
+ if err != nil {
+ return nil, utils.PaginationResponse{}, fmt.Errorf("failed to list Docker networks: %w", err)
+ }
+
+ var result []map[string]interface{}
+ for _, network := range networks {
+ networkData := map[string]interface{}{
+ "ID": network.ID,
+ "Name": network.Name,
+ "Driver": network.Driver,
+ "Scope": network.Scope,
+ "Created": network.Created,
+ "Internal": network.Internal,
+ "Attachable": network.Attachable,
+ "Ingress": network.Ingress,
+ "ConfigFrom": network.ConfigFrom,
+ "ConfigOnly": network.ConfigOnly,
+ "Containers": network.Containers,
+ "Options": network.Options,
+ "Labels": network.Labels,
+ }
+
+ result = append(result, networkData)
+ }
+
+ if req.Search != "" {
+ filtered := make([]map[string]interface{}, 0)
+ searchLower := strings.ToLower(req.Search)
+ for _, network := range result {
+ if name, ok := network["Name"].(string); ok {
+ if strings.Contains(strings.ToLower(name), searchLower) {
+ filtered = append(filtered, network)
+ continue
+ }
+ }
+ if driver, ok := network["Driver"].(string); ok {
+ if strings.Contains(strings.ToLower(driver), searchLower) {
+ filtered = append(filtered, network)
+ continue
+ }
+ }
+ if scope, ok := network["Scope"].(string); ok {
+ if strings.Contains(strings.ToLower(scope), searchLower) {
+ filtered = append(filtered, network)
+ continue
+ }
+ }
+ }
+ result = filtered
+ }
+
+ totalItems := len(result)
+
+ if req.Sort.Column != "" {
+ utils.SortSliceByField(result, req.Sort.Column, req.Sort.Direction)
+ }
+
+ startIdx := (req.Pagination.Page - 1) * req.Pagination.Limit
+ endIdx := startIdx + req.Pagination.Limit
+
+ if startIdx > len(result) {
+ startIdx = len(result)
+ }
+ if endIdx > len(result) {
+ endIdx = len(result)
+ }
+
+ if startIdx < endIdx {
+ result = result[startIdx:endIdx]
+ } else {
+ result = []map[string]interface{}{}
+ }
+
+ totalPages := (totalItems + req.Pagination.Limit - 1) / req.Pagination.Limit
+ pagination := utils.PaginationResponse{
+ TotalPages: int64(totalPages),
+ TotalItems: int64(totalItems),
+ CurrentPage: req.Pagination.Page,
+ ItemsPerPage: req.Pagination.Limit,
+ }
+
+ return result, pagination, nil
+}
diff --git a/backend/internal/services/stack_service.go b/backend/internal/services/stack_service.go
index 09df8165a..1bd6f8ccd 100644
--- a/backend/internal/services/stack_service.go
+++ b/backend/internal/services/stack_service.go
@@ -17,6 +17,7 @@ import (
"github.com/google/uuid"
"github.com/ofkm/arcane-backend/internal/database"
"github.com/ofkm/arcane-backend/internal/models"
+ "github.com/ofkm/arcane-backend/internal/utils"
"gorm.io/gorm"
)
@@ -1014,3 +1015,34 @@ func (s *StackService) getServiceCounts(services []StackServiceInfo) (total int,
}
return total, running
}
+
+func (s *StackService) ListStacksPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]map[string]interface{}, utils.PaginationResponse, error) {
+ var stacks []models.Stack
+ query := s.db.WithContext(ctx).Model(&models.Stack{})
+
+ pagination, err := utils.PaginateAndSort(req, query, &stacks)
+ if err != nil {
+ return nil, utils.PaginationResponse{}, fmt.Errorf("failed to paginate stacks: %w", err)
+ }
+
+ var result []map[string]interface{}
+ for _, stack := range stacks {
+ stackData := map[string]interface{}{
+ "id": stack.ID,
+ "name": stack.Name,
+ "path": stack.Path,
+ "status": stack.Status,
+ "serviceCount": stack.ServiceCount,
+ "runningCount": stack.RunningCount,
+ "createdAt": stack.CreatedAt,
+ "updatedAt": stack.UpdatedAt,
+ "autoUpdate": stack.AutoUpdate,
+ "isExternal": stack.IsExternal,
+ "isLegacy": stack.IsLegacy,
+ "isRemote": stack.IsRemote,
+ }
+ result = append(result, stackData)
+ }
+
+ return result, pagination, nil
+}
diff --git a/backend/internal/services/user_service.go b/backend/internal/services/user_service.go
index 211d5e31f..9da268777 100644
--- a/backend/internal/services/user_service.go
+++ b/backend/internal/services/user_service.go
@@ -16,6 +16,7 @@ import (
"github.com/google/uuid"
"github.com/ofkm/arcane-backend/internal/database"
"github.com/ofkm/arcane-backend/internal/models"
+ "github.com/ofkm/arcane-backend/internal/utils"
)
type Argon2Params struct {
@@ -268,3 +269,83 @@ func (s *UserService) UpgradePasswordHash(ctx context.Context, userID, password
Where("id = ?", userID).
Update("password_hash", newHash).Error
}
+
+func (s *UserService) ListUsersPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]map[string]interface{}, utils.PaginationResponse, error) {
+ users, err := s.ListUsers(ctx)
+ if err != nil {
+ return nil, utils.PaginationResponse{}, fmt.Errorf("failed to list users: %w", err)
+ }
+
+ var result []map[string]interface{}
+ for _, user := range users {
+ userData := map[string]interface{}{
+ "ID": user.ID,
+ "Username": user.Username,
+ "DisplayName": user.DisplayName,
+ "Email": user.Email,
+ "Roles": user.Roles,
+ "CreatedAt": user.CreatedAt,
+ "UpdatedAt": user.UpdatedAt,
+ }
+
+ result = append(result, userData)
+ }
+
+ if req.Search != "" {
+ filtered := make([]map[string]interface{}, 0)
+ searchLower := strings.ToLower(req.Search)
+ for _, user := range result {
+ if username, ok := user["Username"].(string); ok {
+ if strings.Contains(strings.ToLower(username), searchLower) {
+ filtered = append(filtered, user)
+ continue
+ }
+ }
+ if displayName, ok := user["DisplayName"].(*string); ok && displayName != nil {
+ if strings.Contains(strings.ToLower(*displayName), searchLower) {
+ filtered = append(filtered, user)
+ continue
+ }
+ }
+ if email, ok := user["Email"].(*string); ok && email != nil {
+ if strings.Contains(strings.ToLower(*email), searchLower) {
+ filtered = append(filtered, user)
+ continue
+ }
+ }
+ }
+ result = filtered
+ }
+
+ totalItems := len(result)
+
+ if req.Sort.Column != "" {
+ utils.SortSliceByField(result, req.Sort.Column, req.Sort.Direction)
+ }
+
+ startIdx := (req.Pagination.Page - 1) * req.Pagination.Limit
+ endIdx := startIdx + req.Pagination.Limit
+
+ if startIdx > len(result) {
+ startIdx = len(result)
+ }
+ if endIdx > len(result) {
+ endIdx = len(result)
+ }
+
+ if startIdx < endIdx {
+ result = result[startIdx:endIdx]
+ } else {
+ result = []map[string]interface{}{}
+ }
+
+ totalPages := (totalItems + req.Pagination.Limit - 1) / req.Pagination.Limit
+ pagination := utils.PaginationResponse{
+ TotalPages: int64(totalPages),
+ TotalItems: int64(totalItems),
+ CurrentPage: req.Pagination.Page,
+ ItemsPerPage: req.Pagination.Limit,
+ }
+
+ return result, pagination, nil
+}
diff --git a/backend/internal/services/volume_service.go b/backend/internal/services/volume_service.go
index a2f8f3507..ff937e8fc 100644
--- a/backend/internal/services/volume_service.go
+++ b/backend/internal/services/volume_service.go
@@ -3,6 +3,7 @@ package services
import (
"context"
"fmt"
+ "strings"
"time"
"github.com/docker/docker/api/types/container"
@@ -10,6 +11,7 @@ import (
"github.com/docker/docker/api/types/volume"
"github.com/ofkm/arcane-backend/internal/database"
"github.com/ofkm/arcane-backend/internal/models"
+ "github.com/ofkm/arcane-backend/internal/utils"
)
type VolumeService struct {
@@ -170,3 +172,157 @@ func (s *VolumeService) GetVolumeUsage(ctx context.Context, name string) (bool,
return inUse, usingContainers, nil
}
+
+func (s *VolumeService) ListVolumesPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]map[string]interface{}, utils.PaginationResponse, error) {
+ volumes, err := s.ListVolumes(ctx)
+ if err != nil {
+ return nil, utils.PaginationResponse{}, fmt.Errorf("failed to list Docker volumes: %w", err)
+ }
+
+ dockerClient, err := s.dockerService.CreateConnection(ctx)
+ if err != nil {
+ return nil, utils.PaginationResponse{}, fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+ defer dockerClient.Close()
+
+ containers, err := dockerClient.ContainerList(ctx, container.ListOptions{All: true})
+ if err != nil {
+ return nil, utils.PaginationResponse{}, fmt.Errorf("failed to list containers: %w", err)
+ }
+
+ volumeUsageMap := make(map[string]bool)
+ for _, container := range containers {
+ containerInfo, err := dockerClient.ContainerInspect(ctx, container.ID)
+ if err != nil {
+ continue
+ }
+
+ for _, mount := range containerInfo.Mounts {
+ if mount.Type == "volume" {
+ volumeUsageMap[mount.Name] = true
+ }
+ }
+ }
+
+ var result []map[string]interface{}
+ for _, volume := range volumes {
+ inUse := volumeUsageMap[volume.Name]
+
+ volumeData := map[string]interface{}{
+ "Name": volume.Name,
+ "Driver": volume.Driver,
+ "Mountpoint": volume.Mountpoint,
+ "Scope": volume.Scope,
+ "Options": volume.Options,
+ "Labels": volume.Labels,
+ "CreatedAt": volume.CreatedAt,
+ "InUse": inUse,
+ }
+
+ result = append(result, volumeData)
+ }
+
+ if req.Search != "" {
+ filtered := make([]map[string]interface{}, 0)
+ searchLower := strings.ToLower(req.Search)
+ for _, volume := range result {
+ if name, ok := volume["Name"].(string); ok {
+ if strings.Contains(strings.ToLower(name), searchLower) {
+ filtered = append(filtered, volume)
+ continue
+ }
+ }
+ if driver, ok := volume["Driver"].(string); ok {
+ if strings.Contains(strings.ToLower(driver), searchLower) {
+ filtered = append(filtered, volume)
+ continue
+ }
+ }
+ }
+ result = filtered
+ }
+
+ totalItems := len(result)
+
+ if req.Sort.Column != "" {
+ utils.SortSliceByField(result, req.Sort.Column, req.Sort.Direction)
+ }
+
+ startIdx := (req.Pagination.Page - 1) * req.Pagination.Limit
+ endIdx := startIdx + req.Pagination.Limit
+
+ if startIdx > len(result) {
+ startIdx = len(result)
+ }
+ if endIdx > len(result) {
+ endIdx = len(result)
+ }
+
+ if startIdx < endIdx {
+ result = result[startIdx:endIdx]
+ } else {
+ result = []map[string]interface{}{}
+ }
+
+ totalPages := (totalItems + req.Pagination.Limit - 1) / req.Pagination.Limit
+ pagination := utils.PaginationResponse{
+ TotalPages: int64(totalPages),
+ TotalItems: int64(totalItems),
+ CurrentPage: req.Pagination.Page,
+ ItemsPerPage: req.Pagination.Limit,
+ }
+
+ return result, pagination, nil
+}
+
+func (s *VolumeService) ListVolumesWithUsage(ctx context.Context) ([]map[string]interface{}, error) {
+ volumes, err := s.ListVolumes(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("failed to list Docker volumes: %w", err)
+ }
+
+ dockerClient, err := s.dockerService.CreateConnection(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+ defer dockerClient.Close()
+
+ containers, err := dockerClient.ContainerList(ctx, container.ListOptions{All: true})
+ if err != nil {
+ return nil, fmt.Errorf("failed to list containers: %w", err)
+ }
+
+ volumeUsageMap := make(map[string]bool)
+ for _, container := range containers {
+ containerInfo, err := dockerClient.ContainerInspect(ctx, container.ID)
+ if err != nil {
+ continue
+ }
+
+ for _, mount := range containerInfo.Mounts {
+ if mount.Type == "volume" {
+ volumeUsageMap[mount.Name] = true
+ }
+ }
+ }
+
+ var result []map[string]interface{}
+ for _, volume := range volumes {
+ inUse := volumeUsageMap[volume.Name]
+
+ volumeData := map[string]interface{}{
+ "Name": volume.Name,
+ "Driver": volume.Driver,
+ "Mountpoint": volume.Mountpoint,
+ "Scope": volume.Scope,
+ "Options": volume.Options,
+ "Labels": volume.Labels,
+ "CreatedAt": volume.CreatedAt,
+ "InUse": inUse,
+ }
+
+ result = append(result, volumeData)
+ }
+
+ return result, nil
+}
diff --git a/backend/internal/utils/page_util.go b/backend/internal/utils/page_util.go
new file mode 100644
index 000000000..ee4223213
--- /dev/null
+++ b/backend/internal/utils/page_util.go
@@ -0,0 +1,290 @@
+package utils
+
+import (
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+type PaginationResponse struct {
+ TotalPages int64 `json:"totalPages"`
+ TotalItems int64 `json:"totalItems"`
+ CurrentPage int `json:"currentPage"`
+ ItemsPerPage int `json:"itemsPerPage"`
+}
+
+type SortedPaginationRequest struct {
+ Pagination struct {
+ Page int `form:"pagination[page]"`
+ Limit int `form:"pagination[limit]"`
+ } `form:"pagination"`
+ Sort struct {
+ Column string `form:"sort[column]"`
+ Direction string `form:"sort[direction]"`
+ } `form:"sort"`
+ Search string `form:"search"`
+ Filters map[string]interface{} `form:"filters"`
+}
+
+type SimplePaginationRequest struct {
+ Page int `form:"page" json:"page"`
+ Limit int `form:"limit" json:"limit"`
+}
+
+type SimpleSortRequest struct {
+ Column string `form:"column" json:"column"`
+ Direction string `form:"direction" json:"direction"`
+}
+
+type PaginationOptions struct {
+ DefaultPageSize int
+ MaxPageSize int
+ AllowedSorts []string
+}
+
+func PaginateAndSort(sortedPaginationRequest SortedPaginationRequest, query *gorm.DB, result interface{}) (PaginationResponse, error) {
+ pagination := sortedPaginationRequest.Pagination
+ sort := sortedPaginationRequest.Sort
+
+ if sort.Column == "" {
+ return Paginate(pagination.Page, pagination.Limit, query, result)
+ }
+
+ capitalizedSortColumn := CapitalizeFirstLetter(sort.Column)
+
+ // Get the element type correctly
+ resultType := reflect.TypeOf(result)
+ if resultType.Kind() == reflect.Ptr {
+ resultType = resultType.Elem()
+ }
+ if resultType.Kind() == reflect.Slice {
+ resultType = resultType.Elem()
+ }
+ if resultType.Kind() == reflect.Ptr {
+ resultType = resultType.Elem()
+ }
+
+ sortField, sortFieldFound := resultType.FieldByName(capitalizedSortColumn)
+ isSortable := false
+ if sortFieldFound {
+ if sortableTag := sortField.Tag.Get("sortable"); sortableTag != "" {
+ isSortable, _ = strconv.ParseBool(sortableTag)
+ }
+ }
+
+ if sort.Direction == "" || (sort.Direction != "asc" && sort.Direction != "desc") {
+ sort.Direction = "asc"
+ }
+
+ if sortFieldFound && isSortable {
+ columnName := CamelCaseToSnakeCase(sort.Column)
+ query = query.Clauses(clause.OrderBy{
+ Columns: []clause.OrderByColumn{
+ {Column: clause.Column{Name: columnName}, Desc: sort.Direction == "desc"},
+ },
+ })
+ }
+
+ return Paginate(pagination.Page, pagination.Limit, query, result)
+}
+
+func PaginateWithSort(page, pageSize int, sortColumn, sortDirection string, query *gorm.DB, result interface{}, options *PaginationOptions) (PaginationResponse, error) {
+ if options == nil {
+ options = &PaginationOptions{
+ DefaultPageSize: 20,
+ MaxPageSize: 100,
+ }
+ }
+
+ if sortColumn != "" && sortDirection != "" {
+ if len(options.AllowedSorts) == 0 || contains(options.AllowedSorts, sortColumn) {
+ if sortDirection != "asc" && sortDirection != "desc" {
+ sortDirection = "asc"
+ }
+
+ columnName := CamelCaseToSnakeCase(sortColumn)
+ query = query.Clauses(clause.OrderBy{
+ Columns: []clause.OrderByColumn{
+ {Column: clause.Column{Name: columnName}, Desc: sortDirection == "desc"},
+ },
+ })
+ }
+ }
+
+ return Paginate(page, pageSize, query, result)
+}
+
+func Paginate(page int, pageSize int, query *gorm.DB, result interface{}) (PaginationResponse, error) {
+ if page < 1 {
+ page = 1
+ }
+
+ if pageSize < 1 {
+ pageSize = 20
+ } else if pageSize > 100 {
+ pageSize = 100
+ }
+
+ offset := (page - 1) * pageSize
+
+ var totalItems int64
+ if err := query.Count(&totalItems).Error; err != nil {
+ return PaginationResponse{}, err
+ }
+
+ if err := query.Offset(offset).Limit(pageSize).Find(result).Error; err != nil {
+ return PaginationResponse{}, err
+ }
+
+ totalPages := (totalItems + int64(pageSize) - 1) / int64(pageSize)
+ if totalItems == 0 {
+ totalPages = 1
+ }
+
+ return PaginationResponse{
+ TotalPages: totalPages,
+ TotalItems: totalItems,
+ CurrentPage: page,
+ ItemsPerPage: pageSize,
+ }, nil
+}
+
+func PaginateSimple(req SimplePaginationRequest, query *gorm.DB, result interface{}) (PaginationResponse, error) {
+ return Paginate(req.Page, req.Limit, query, result)
+}
+
+func ApplySort(sort SimpleSortRequest, query *gorm.DB, allowedColumns []string) *gorm.DB {
+ if sort.Column == "" {
+ return query
+ }
+
+ if len(allowedColumns) > 0 && !contains(allowedColumns, sort.Column) {
+ return query
+ }
+
+ if sort.Direction != "asc" && sort.Direction != "desc" {
+ sort.Direction = "asc"
+ }
+
+ columnName := CamelCaseToSnakeCase(sort.Column)
+ return query.Order(columnName + " " + sort.Direction)
+}
+
+func CamelCaseToSnakeCase(str string) string {
+ var result strings.Builder
+ for i, r := range str {
+ if i > 0 && r >= 'A' && r <= 'Z' {
+ result.WriteRune('_')
+ }
+ result.WriteRune(r)
+ }
+ return strings.ToLower(result.String())
+}
+
+func CapitalizeFirstLetter(str string) string {
+ if len(str) == 0 {
+ return str
+ }
+ return strings.ToUpper(str[:1]) + str[1:]
+}
+
+func contains(slice []string, item string) bool {
+ for _, s := range slice {
+ if s == item {
+ return true
+ }
+ }
+ return false
+}
+
+func ValidatePaginationParams(page, limit int) (int, int) {
+ if page < 1 {
+ page = 1
+ }
+ if limit < 1 {
+ limit = 20
+ } else if limit > 100 {
+ limit = 100
+ }
+ return page, limit
+}
+
+func GetOffsetFromPage(page, pageSize int) int {
+ if page < 1 {
+ page = 1
+ }
+ return (page - 1) * pageSize
+}
+
+func CalculateTotalPages(totalItems int64, pageSize int) int64 {
+ if totalItems == 0 {
+ return 1
+ }
+ return (totalItems + int64(pageSize) - 1) / int64(pageSize)
+}
+
+func SortSliceByField(data []map[string]interface{}, field, direction string) {
+ if field == "" {
+ return
+ }
+
+ sort.Slice(data, func(i, j int) bool {
+ val1, exists1 := data[i][field]
+ val2, exists2 := data[j][field]
+
+ if !exists1 && !exists2 {
+ return false
+ }
+ if !exists1 {
+ return direction == "desc"
+ }
+ if !exists2 {
+ return direction == "asc"
+ }
+
+ switch v1 := val1.(type) {
+ case string:
+ v2, ok := val2.(string)
+ if !ok {
+ return false
+ }
+ if direction == "desc" {
+ return v1 > v2
+ }
+ return v1 < v2
+ case int:
+ v2, ok := val2.(int)
+ if !ok {
+ return false
+ }
+ if direction == "desc" {
+ return v1 > v2
+ }
+ return v1 < v2
+ case int64:
+ v2, ok := val2.(int64)
+ if !ok {
+ return false
+ }
+ if direction == "desc" {
+ return v1 > v2
+ }
+ return v1 < v2
+ case float64:
+ v2, ok := val2.(float64)
+ if !ok {
+ return false
+ }
+ if direction == "desc" {
+ return v1 > v2
+ }
+ return v1 < v2
+ default:
+ return false
+ }
+ })
+}
diff --git a/backend/resources/embed.go b/backend/resources/embed.go
new file mode 100644
index 000000000..561af061a
--- /dev/null
+++ b/backend/resources/embed.go
@@ -0,0 +1,8 @@
+package resources
+
+import "embed"
+
+// Embedded file systems for the project
+
+//go:embed migrations
+var FS embed.FS
diff --git a/backend/resources/migrations/psql/001_initial_schema.up.sql b/backend/resources/migrations/psql/001_initial_schema.up.sql
new file mode 100644
index 000000000..e69de29bb
diff --git a/backend/resources/migrations/sqlite/001_initial_schema.up.sql b/backend/resources/migrations/sqlite/001_initial_schema.up.sql
new file mode 100644
index 000000000..79d87cb1a
--- /dev/null
+++ b/backend/resources/migrations/sqlite/001_initial_schema.up.sql
@@ -0,0 +1,216 @@
+CREATE TABLE IF NOT EXISTS settings_table (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ docker_tls_cert TEXT NOT NULL DEFAULT '',
+ stacks_directory TEXT NOT NULL,
+ auto_update BOOLEAN NOT NULL DEFAULT 0,
+ auto_update_interval INTEGER NOT NULL DEFAULT 300,
+ polling_enabled BOOLEAN NOT NULL DEFAULT 1,
+ polling_interval INTEGER NOT NULL DEFAULT 5,
+ prune_mode TEXT,
+ registry_credentials TEXT NOT NULL DEFAULT '[]',
+ template_registries TEXT NOT NULL DEFAULT '[]',
+ auth TEXT NOT NULL,
+ onboarding TEXT,
+ base_server_url TEXT,
+ maturity_threshold_days INTEGER NOT NULL DEFAULT 30,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME
+);
+
+CREATE TABLE IF NOT EXISTS users_table (
+ id TEXT PRIMARY KEY,
+ username TEXT NOT NULL UNIQUE,
+ password_hash TEXT NOT NULL DEFAULT '',
+ display_name TEXT,
+ email TEXT,
+ roles TEXT NOT NULL DEFAULT '[]',
+ require_password_change BOOLEAN NOT NULL DEFAULT 0,
+ oidc_subject_id TEXT,
+ last_login DATETIME,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME
+);
+
+CREATE TABLE IF NOT EXISTS user_sessions_table (
+ id TEXT PRIMARY KEY,
+ user_id TEXT NOT NULL,
+ username TEXT NOT NULL,
+ token TEXT NOT NULL UNIQUE,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ last_accessed DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ expires_at DATETIME,
+ is_active BOOLEAN NOT NULL DEFAULT 1,
+ updated_at DATETIME,
+ FOREIGN KEY (user_id) REFERENCES users_table(id) ON DELETE CASCADE
+);
+
+CREATE TABLE IF NOT EXISTS stacks_table (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ dir_name TEXT UNIQUE,
+ path TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'unknown',
+ service_count INTEGER NOT NULL DEFAULT 0,
+ running_count INTEGER NOT NULL DEFAULT 0,
+ auto_update BOOLEAN NOT NULL DEFAULT 0,
+ is_external BOOLEAN NOT NULL DEFAULT 0,
+ is_legacy BOOLEAN NOT NULL DEFAULT 0,
+ is_remote BOOLEAN NOT NULL DEFAULT 0,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME
+);
+
+CREATE TABLE IF NOT EXISTS environments (
+ id TEXT PRIMARY KEY,
+ hostname TEXT NOT NULL,
+ api_url TEXT NOT NULL,
+ description TEXT,
+ status TEXT NOT NULL DEFAULT 'offline',
+ enabled BOOLEAN NOT NULL DEFAULT 1,
+ last_seen DATETIME,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME
+);
+
+CREATE TABLE IF NOT EXISTS containers_table (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ image TEXT NOT NULL,
+ status TEXT NOT NULL,
+ state TEXT NOT NULL,
+ ports TEXT,
+ mounts TEXT,
+ networks TEXT,
+ labels TEXT,
+ environment TEXT,
+ command TEXT,
+ stack_id TEXT,
+ started_at DATETIME,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME,
+ FOREIGN KEY (stack_id) REFERENCES stacks_table(id) ON DELETE SET NULL
+);
+
+CREATE TABLE IF NOT EXISTS images_table (
+ id TEXT PRIMARY KEY,
+ repo_tags TEXT,
+ repo_digests TEXT,
+ size INTEGER NOT NULL DEFAULT 0,
+ virtual_size INTEGER NOT NULL DEFAULT 0,
+ labels TEXT,
+ created DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ repo TEXT NOT NULL DEFAULT '',
+ tag TEXT NOT NULL DEFAULT '',
+ in_use BOOLEAN NOT NULL DEFAULT 0,
+ updated_at DATETIME
+);
+
+CREATE TABLE IF NOT EXISTS volumes_table (
+ name TEXT PRIMARY KEY,
+ driver TEXT NOT NULL,
+ mountpoint TEXT NOT NULL,
+ labels TEXT,
+ scope TEXT NOT NULL,
+ options TEXT,
+ in_use BOOLEAN NOT NULL DEFAULT 0,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME
+);
+
+CREATE TABLE IF NOT EXISTS networks_table (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL UNIQUE,
+ driver TEXT NOT NULL,
+ scope TEXT NOT NULL,
+ internal BOOLEAN NOT NULL DEFAULT 0,
+ attachable BOOLEAN NOT NULL DEFAULT 0,
+ ingress BOOLEAN NOT NULL DEFAULT 0,
+ ipam TEXT,
+ labels TEXT,
+ options TEXT,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME
+);
+
+CREATE TABLE IF NOT EXISTS image_maturity_table (
+ id TEXT PRIMARY KEY,
+ repository TEXT NOT NULL,
+ tag TEXT NOT NULL,
+ current_version TEXT NOT NULL DEFAULT '',
+ latest_version TEXT,
+ status TEXT NOT NULL,
+ updates_available BOOLEAN NOT NULL DEFAULT 0,
+ current_image_date DATETIME,
+ latest_image_date DATETIME,
+ days_since_creation INTEGER,
+ registry_domain TEXT,
+ is_private_registry BOOLEAN NOT NULL DEFAULT 0,
+ last_checked DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ check_count INTEGER NOT NULL DEFAULT 0,
+ last_error TEXT,
+ response_time_ms INTEGER,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME,
+ FOREIGN KEY (id) REFERENCES images_table(id) ON DELETE CASCADE
+);
+
+CREATE TABLE IF NOT EXISTS template_registries (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ url TEXT NOT NULL UNIQUE,
+ enabled BOOLEAN NOT NULL DEFAULT 1,
+ description TEXT NOT NULL DEFAULT '',
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE TABLE IF NOT EXISTS compose_templates (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ description TEXT NOT NULL DEFAULT '',
+ content TEXT NOT NULL,
+ env_content TEXT,
+ is_custom BOOLEAN NOT NULL DEFAULT 1,
+ is_remote BOOLEAN NOT NULL DEFAULT 0,
+ registry_id TEXT,
+ meta_version TEXT,
+ meta_author TEXT,
+ meta_tags TEXT,
+ meta_remote_url TEXT,
+ meta_env_url TEXT,
+ meta_documentation_url TEXT,
+ meta_icon_url TEXT,
+ meta_updated_at TEXT,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (registry_id) REFERENCES template_registries(id) ON DELETE SET NULL
+);
+
+CREATE TABLE IF NOT EXISTS container_registries (
+ id TEXT PRIMARY KEY,
+ url TEXT NOT NULL,
+ username TEXT NOT NULL,
+ token TEXT NOT NULL,
+ description TEXT,
+ insecure BOOLEAN NOT NULL DEFAULT 0,
+ enabled BOOLEAN NOT NULL DEFAULT 1,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE INDEX IF NOT EXISTS idx_users_username ON users_table(username);
+CREATE INDEX IF NOT EXISTS idx_user_sessions_user_id ON user_sessions_table(user_id);
+CREATE INDEX IF NOT EXISTS idx_user_sessions_token ON user_sessions_table(token);
+CREATE INDEX IF NOT EXISTS idx_containers_stack_id ON containers_table(stack_id);
+CREATE INDEX IF NOT EXISTS idx_containers_name ON containers_table(name);
+CREATE INDEX IF NOT EXISTS idx_containers_image ON containers_table(image);
+CREATE INDEX IF NOT EXISTS idx_containers_status ON containers_table(status);
+CREATE INDEX IF NOT EXISTS idx_containers_state ON containers_table(state);
+CREATE INDEX IF NOT EXISTS idx_images_repo ON images_table(repo);
+CREATE INDEX IF NOT EXISTS idx_images_tag ON images_table(tag);
+CREATE INDEX IF NOT EXISTS idx_images_in_use ON images_table(in_use);
+CREATE INDEX IF NOT EXISTS idx_stacks_name ON stacks_table(name);
+CREATE INDEX IF NOT EXISTS idx_stacks_status ON stacks_table(status);
+CREATE INDEX IF NOT EXISTS idx_image_maturity_repository ON image_maturity_table(repository);
+CREATE INDEX IF NOT EXISTS idx_image_maturity_tag ON image_maturity_table(tag);
+CREATE INDEX IF NOT EXISTS idx_image_maturity_status ON image_maturity_table(status);
\ No newline at end of file
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 51c3cb185..afe4448b1 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -30,6 +30,8 @@
"@sveltejs/kit": "^2.22.2",
"@sveltejs/vite-plugin-svelte": "^5.1.0",
"@tailwindcss/vite": "^4.1.10",
+ "@types/d3-scale": "^4.0.9",
+ "@types/d3-shape": "^3.1.7",
"@types/dockerode": "^3.3.42",
"@types/js-yaml": "^4.0.9",
"bits-ui": "^2.8.10",
@@ -39,6 +41,7 @@
"formsnap": "^2.0.1",
"globals": "^16.2.0",
"isomorphic-dompurify": "^2.25.0",
+ "layerchart": "^2.0.0-next.27",
"mode-watcher": "^1.0.8",
"paneforge": "^1.0.0-next.5",
"runed": "^0.29.1",
@@ -334,6 +337,26 @@
"node": ">=18"
}
},
+ "node_modules/@dagrejs/dagre": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@dagrejs/dagre/-/dagre-1.1.5.tgz",
+ "integrity": "sha512-Ghgrh08s12DCL5SeiR6AoyE80mQELTWhJBRmXfFoqDiFkR458vPEdgTbbjA0T+9ETNxUblnD0QW55tfdvi5pjQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@dagrejs/graphlib": "2.2.4"
+ }
+ },
+ "node_modules/@dagrejs/graphlib": {
+ "version": "2.2.4",
+ "resolved": "https://registry.npmjs.org/@dagrejs/graphlib/-/graphlib-2.2.4.tgz",
+ "integrity": "sha512-mepCf/e9+SKYy1d02/UkvSy6+6MoyXhVxP8lLDfA7BPE1X1d4dR0sZznmbM8/XVJ1GPM+Svnx7Xj6ZweByWUkw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">17.0.0"
+ }
+ },
"node_modules/@esbuild/aix-ppc64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.4.tgz",
@@ -1132,6 +1155,55 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
+ "node_modules/@layerstack/svelte-actions": {
+ "version": "1.0.1-next.12",
+ "resolved": "https://registry.npmjs.org/@layerstack/svelte-actions/-/svelte-actions-1.0.1-next.12.tgz",
+ "integrity": "sha512-dndWTlYu8b1u6vw2nrO7NssccoACArGG75WoNlyVC13KuENZlWdKE9Q79/wlnbq00NeQMNKMjJwRMsrKQj2ULA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@floating-ui/dom": "^1.7.0",
+ "@layerstack/utils": "2.0.0-next.12",
+ "d3-scale": "^4.0.2"
+ }
+ },
+ "node_modules/@layerstack/svelte-state": {
+ "version": "0.1.0-next.17",
+ "resolved": "https://registry.npmjs.org/@layerstack/svelte-state/-/svelte-state-0.1.0-next.17.tgz",
+ "integrity": "sha512-z7e6mPJnypD80LEI/UDuH0bI6s8/nut06MB7rEkRcEfHJekhKSJgFhMnrYzLED7Mc2gTTD0X/wcYlakauWlU8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@layerstack/utils": "2.0.0-next.12"
+ }
+ },
+ "node_modules/@layerstack/tailwind": {
+ "version": "2.0.0-next.15",
+ "resolved": "https://registry.npmjs.org/@layerstack/tailwind/-/tailwind-2.0.0-next.15.tgz",
+ "integrity": "sha512-7tqKE3OV7/ybeDOORX++USYYCBJa7IgTya2czFpzbgXGo7CQDVyuv+0J1DggjRcEqhhXQA4MUhgnhcRaZvHxWg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@layerstack/utils": "^2.0.0-next.12",
+ "clsx": "^2.1.1",
+ "d3-array": "^3.2.4",
+ "lodash-es": "^4.17.21",
+ "tailwind-merge": "^3.2.0"
+ }
+ },
+ "node_modules/@layerstack/utils": {
+ "version": "2.0.0-next.12",
+ "resolved": "https://registry.npmjs.org/@layerstack/utils/-/utils-2.0.0-next.12.tgz",
+ "integrity": "sha512-fhGZUlSr3N+D44BYm37WKMGSEFyZBW+dwIqtGU8Cl54mR4TLQ/UwyGhdpgIHyH/x/8q1abE0fP0Dn6ZsrDE3BA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "d3-array": "^3.2.4",
+ "d3-time": "^3.1.0",
+ "d3-time-format": "^4.1.0",
+ "lodash-es": "^4.17.21"
+ }
+ },
"node_modules/@lezer/common": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.2.3.tgz",
@@ -1966,6 +2038,40 @@
"integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==",
"license": "MIT"
},
+ "node_modules/@types/d3-path": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
+ "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-scale": {
+ "version": "4.0.9",
+ "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
+ "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-time": "*"
+ }
+ },
+ "node_modules/@types/d3-shape": {
+ "version": "3.1.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.7.tgz",
+ "integrity": "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-path": "*"
+ }
+ },
+ "node_modules/@types/d3-time": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
+ "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/docker-modem": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/@types/docker-modem/-/docker-modem-3.0.6.tgz",
@@ -2568,9 +2674,9 @@
}
},
"node_modules/brace-expansion": {
- "version": "1.1.11",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
- "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
+ "version": "1.1.12",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
+ "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2748,6 +2854,16 @@
"node": ">= 0.8"
}
},
+ "node_modules/commander": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
+ "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10"
+ }
+ },
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -2812,6 +2928,338 @@
"node": ">=18"
}
},
+ "node_modules/d3-array": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
+ "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "internmap": "1 - 2"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-color": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-delaunay": {
+ "version": "6.0.4",
+ "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.4.tgz",
+ "integrity": "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "delaunator": "5"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-dispatch": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",
+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-dsv": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.1.tgz",
+ "integrity": "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "commander": "7",
+ "iconv-lite": "0.6",
+ "rw": "1"
+ },
+ "bin": {
+ "csv2json": "bin/dsv2json.js",
+ "csv2tsv": "bin/dsv2dsv.js",
+ "dsv2dsv": "bin/dsv2dsv.js",
+ "dsv2json": "bin/dsv2json.js",
+ "json2csv": "bin/json2dsv.js",
+ "json2dsv": "bin/json2dsv.js",
+ "json2tsv": "bin/json2dsv.js",
+ "tsv2csv": "bin/dsv2dsv.js",
+ "tsv2json": "bin/dsv2json.js"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-force": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz",
+ "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-quadtree": "1 - 3",
+ "d3-timer": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-format": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz",
+ "integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-geo": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz",
+ "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2.5.0 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-geo-voronoi": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/d3-geo-voronoi/-/d3-geo-voronoi-2.1.0.tgz",
+ "integrity": "sha512-kqE4yYuOjPbKdBXG0xztCacPwkVSK2REF1opSNrnqqtXJmNcM++UbwQ8SxvwP6IQTj9RvIjjK4qeiVsEfj0Z2Q==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "3",
+ "d3-delaunay": "6",
+ "d3-geo": "3",
+ "d3-tricontour": "1"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-hierarchy": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz",
+ "integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-interpolate": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-interpolate-path": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/d3-interpolate-path/-/d3-interpolate-path-2.3.0.tgz",
+ "integrity": "sha512-tZYtGXxBmbgHsIc9Wms6LS5u4w6KbP8C09a4/ZYc4KLMYYqub57rRBUgpUr2CIarIrJEpdAWWxWQvofgaMpbKQ==",
+ "dev": true,
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/d3-path": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
+ "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-quadtree": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz",
+ "integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-random": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.1.tgz",
+ "integrity": "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-sankey": {
+ "version": "0.12.3",
+ "resolved": "https://registry.npmjs.org/d3-sankey/-/d3-sankey-0.12.3.tgz",
+ "integrity": "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "d3-array": "1 - 2",
+ "d3-shape": "^1.2.0"
+ }
+ },
+ "node_modules/d3-sankey/node_modules/d3-array": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-2.12.1.tgz",
+ "integrity": "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "internmap": "^1.0.0"
+ }
+ },
+ "node_modules/d3-sankey/node_modules/d3-path": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz",
+ "integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==",
+ "dev": true,
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/d3-sankey/node_modules/d3-shape": {
+ "version": "1.3.7",
+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz",
+ "integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "d3-path": "1"
+ }
+ },
+ "node_modules/d3-sankey/node_modules/internmap": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-1.0.1.tgz",
+ "integrity": "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/d3-scale": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
+ "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2.10.0 - 3",
+ "d3-format": "1 - 3",
+ "d3-interpolate": "1.2.0 - 3",
+ "d3-time": "2.1.1 - 3",
+ "d3-time-format": "2 - 4"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-scale-chromatic": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
+ "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3",
+ "d3-interpolate": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-shape": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
+ "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-path": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-tile": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/d3-tile/-/d3-tile-1.0.0.tgz",
+ "integrity": "sha512-79fnTKpPMPDS5xQ0xuS9ir0165NEwwkFpe/DSOmc2Gl9ldYzKKRDWogmTTE8wAJ8NA7PMapNfEcyKhI9Lxdu5Q==",
+ "dev": true,
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/d3-time": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
+ "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-time-format": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
+ "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-time": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-timer": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-tricontour": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/d3-tricontour/-/d3-tricontour-1.0.2.tgz",
+ "integrity": "sha512-HIRxHzHagPtUPNabjOlfcyismJYIsc+Xlq4mlsts4e8eAcwyq9Tgk/sYdyhlBpQ0MHwVquc/8j+e29YjXnmxeA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-delaunay": "6",
+ "d3-scale": "4"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/data-urls": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz",
@@ -2884,6 +3332,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/delaunator": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.0.1.tgz",
+ "integrity": "sha512-8nvh+XBe96aCESrGOqMp/84b13H9cdKbG5P2ejQCh4d4sK9RL4371qou9drQjMhvnPmhWl5hnmqbEE0fXr9Xnw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "robust-predicates": "^3.0.2"
+ }
+ },
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@@ -3832,6 +4290,16 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/internmap": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
+ "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
@@ -4032,6 +4500,62 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/layerchart": {
+ "version": "2.0.0-next.27",
+ "resolved": "https://registry.npmjs.org/layerchart/-/layerchart-2.0.0-next.27.tgz",
+ "integrity": "sha512-yt28xU8WzXq0AliX7eiC0JKZGQtO8M9FmHvt8sESNitSc/yC+fYeTghaO9lMRwcYCmi6D1NjbFyD9mWFeazNIQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@dagrejs/dagre": "^1.1.4",
+ "@layerstack/svelte-actions": "1.0.1-next.12",
+ "@layerstack/svelte-state": "0.1.0-next.17",
+ "@layerstack/tailwind": "2.0.0-next.15",
+ "@layerstack/utils": "2.0.0-next.12",
+ "d3-array": "^3.2.4",
+ "d3-color": "^3.1.0",
+ "d3-delaunay": "^6.0.4",
+ "d3-dsv": "^3.0.1",
+ "d3-force": "^3.0.0",
+ "d3-geo": "^3.1.1",
+ "d3-geo-voronoi": "^2.1.0",
+ "d3-hierarchy": "^3.1.2",
+ "d3-interpolate": "^3.0.1",
+ "d3-interpolate-path": "^2.3.0",
+ "d3-path": "^3.1.0",
+ "d3-quadtree": "^3.0.1",
+ "d3-random": "^3.0.1",
+ "d3-sankey": "^0.12.3",
+ "d3-scale": "^4.0.2",
+ "d3-scale-chromatic": "^3.1.0",
+ "d3-shape": "^3.2.0",
+ "d3-tile": "^1.0.0",
+ "d3-time": "^3.1.0",
+ "lodash-es": "^4.17.21",
+ "memoize": "^10.1.0",
+ "runed": "^0.28.0"
+ },
+ "peerDependencies": {
+ "svelte": "^5.0.0"
+ }
+ },
+ "node_modules/layerchart/node_modules/runed": {
+ "version": "0.28.0",
+ "resolved": "https://registry.npmjs.org/runed/-/runed-0.28.0.tgz",
+ "integrity": "sha512-k2xx7RuO9hWcdd9f+8JoBeqWtYrm5CALfgpkg2YDB80ds/QE4w0qqu34A7fqiAwiBBSBQOid7TLxwxVC27ymWQ==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/huntabyte",
+ "https://github.com/sponsors/tglide"
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "esm-env": "^1.0.0"
+ },
+ "peerDependencies": {
+ "svelte": "^5.7.0"
+ }
+ },
"node_modules/levn": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
@@ -4315,6 +4839,13 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/lodash-es": {
+ "version": "4.17.21",
+ "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz",
+ "integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/lodash.merge": {
"version": "4.6.2",
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
@@ -4347,6 +4878,22 @@
"node": ">= 0.4"
}
},
+ "node_modules/memoize": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/memoize/-/memoize-10.1.0.tgz",
+ "integrity": "sha512-MMbFhJzh4Jlg/poq1si90XRlTZRDHVqdlz2mPyGJ6kqMpyHUyVpDd5gpFAvVehW64+RA1eKE9Yt8aSLY7w2Kgg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "mimic-function": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sindresorhus/memoize?sponsor=1"
+ }
+ },
"node_modules/memoize-weak": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/memoize-weak/-/memoize-weak-1.0.2.tgz",
@@ -4412,6 +4959,19 @@
"node": ">= 0.6"
}
},
+ "node_modules/mimic-function": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz",
+ "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
@@ -5155,6 +5715,13 @@
"node": ">=0.10.0"
}
},
+ "node_modules/robust-predicates": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.2.tgz",
+ "integrity": "sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg==",
+ "dev": true,
+ "license": "Unlicense"
+ },
"node_modules/rollup": {
"version": "4.41.0",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.41.0.tgz",
@@ -5242,6 +5809,13 @@
"svelte": "^5.7.0"
}
},
+ "node_modules/rw": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",
+ "integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==",
+ "dev": true,
+ "license": "BSD-3-Clause"
+ },
"node_modules/sade": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz",
@@ -5564,9 +6138,9 @@
}
},
"node_modules/sveltekit-superforms": {
- "version": "2.27.0",
- "resolved": "https://registry.npmjs.org/sveltekit-superforms/-/sveltekit-superforms-2.27.0.tgz",
- "integrity": "sha512-FXIdUg4VRVZeAdVH/zB7JtHvuoC6RmHDw032meEasqB5v+i1ud4pwU/Big+6eJ2SysqrzCahBbCvLN2qzRPVUw==",
+ "version": "2.27.1",
+ "resolved": "https://registry.npmjs.org/sveltekit-superforms/-/sveltekit-superforms-2.27.1.tgz",
+ "integrity": "sha512-cvq2AevkZ0Zrk0w0gNM3kjcnJMtJ0jzu+2zqDoM9a+lZa+8bGpNl4YqxVkemiJNkGnFgNC8xr5xF5BlMzjookQ==",
"dev": true,
"funding": [
{
diff --git a/frontend/package.json b/frontend/package.json
index 26dd9d180..34baeb5a6 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -44,6 +44,8 @@
"@sveltejs/kit": "^2.22.2",
"@sveltejs/vite-plugin-svelte": "^5.1.0",
"@tailwindcss/vite": "^4.1.10",
+ "@types/d3-scale": "^4.0.9",
+ "@types/d3-shape": "^3.1.7",
"@types/dockerode": "^3.3.42",
"@types/js-yaml": "^4.0.9",
"bits-ui": "^2.8.10",
@@ -53,6 +55,7 @@
"formsnap": "^2.0.1",
"globals": "^16.2.0",
"isomorphic-dompurify": "^2.25.0",
+ "layerchart": "^2.0.0-next.27",
"mode-watcher": "^1.0.8",
"paneforge": "^1.0.0-next.5",
"runed": "^0.29.1",
diff --git a/frontend/src/lib/components/LogViewer.svelte b/frontend/src/lib/components/LogViewer.svelte
index c4b835f46..662c54e4f 100644
--- a/frontend/src/lib/components/LogViewer.svelte
+++ b/frontend/src/lib/components/LogViewer.svelte
@@ -1,6 +1,8 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { browser } from '$app/environment';
+ import { get } from 'svelte/store';
+ import { environmentStore } from '$lib/stores/environment.store';
interface LogEntry {
timestamp: string;
@@ -24,7 +26,19 @@
onStop?: () => void;
}
- let { containerId = null, stackId = null, type = 'container', maxLines = 1000, autoScroll = $bindable(true), showTimestamps = true, height = '400px', onClear, onToggleAutoScroll, onStart, onStop }: Props = $props();
+ let {
+ containerId = null,
+ stackId = null,
+ type = 'container',
+ maxLines = 1000,
+ autoScroll = $bindable(true),
+ showTimestamps = true,
+ height = '400px',
+ onClear,
+ onToggleAutoScroll,
+ onStart,
+ onStop
+ }: Props = $props();
let logs: LogEntry[] = $state([]);
let logContainer: HTMLElement | undefined = $state();
@@ -32,7 +46,22 @@
let error: string | null = $state(null);
let eventSource: EventSource | null = null;
- export function startLogStream() {
+ async function buildLogStreamEndpoint(): Promise<string> {
+ if (browser) {
+ await environmentStore.ready;
+ }
+ const currentEnvironment = get(environmentStore.selected);
+ const envId = currentEnvironment?.id || 'local';
+
+ const baseEndpoint =
+ type === 'stack'
+ ? `/api/environments/${envId}/stacks/${stackId}/logs/stream`
+ : `/api/environments/${envId}/containers/${containerId}/logs/stream`;
+
+ return `${baseEndpoint}?follow=true&tail=100&timestamps=${showTimestamps}`;
+ }
+
+ export async function startLogStream() {
const targetId = type === 'stack' ? stackId : containerId;
if (!targetId || !browser) return;
@@ -42,7 +71,7 @@
error = null;
onStart?.();
- const endpoint = type === 'stack' ? `/api/stacks/${stackId}/logs/stream?follow=true&tail=100&timestamps=${showTimestamps}` : `/api/containers/${containerId}/logs/stream?follow=true&tail=100&timestamps=${showTimestamps}`;
+ const endpoint = await buildLogStreamEndpoint();
eventSource = new EventSource(endpoint);
@@ -51,7 +80,6 @@
const logData = JSON.parse(event.data);
if (logData.message !== undefined) {
- // Stack log format
addLogEntry({
level: logData.level || 'info',
message: logData.message,
@@ -60,7 +88,6 @@
containerId: logData.containerId
});
} else if (logData.data !== undefined) {
- // Container log format
addLogEntry({
level: logData.data.includes('[STDERR]') ? 'stderr' : 'stdout',
message: logData.data.replace('[STDERR] ', ''),
@@ -79,7 +106,6 @@
}
});
- // Handle container logs (come as default messages)
eventSource.onmessage = (event) => {
try {
const logData = JSON.parse(event.data);
@@ -160,11 +186,30 @@
return logs.length;
}
- function addLogEntry(logData: { level: string; message: string; timestamp?: string; service?: string; containerId?: string }) {
+ function addLogEntry(logData: {
+ level: string;
+ message: string;
+ timestamp?: string;
+ service?: string;
+ containerId?: string;
+ }) {
+ let cleanMessage = logData.message;
+ let timestamp = logData.timestamp || new Date().toISOString();
+
+ const dockerTimestampRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z?\s*/;
+ if (dockerTimestampRegex.test(cleanMessage)) {
+ cleanMessage = cleanMessage.replace(dockerTimestampRegex, '').trim();
+ }
+
+ const dockerTimestampRegex2 = /^\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}\s*/;
+ if (dockerTimestampRegex2.test(cleanMessage)) {
+ cleanMessage = cleanMessage.replace(dockerTimestampRegex2, '').trim();
+ }
+
const entry: LogEntry = {
- timestamp: logData.timestamp || new Date().toISOString(),
+ timestamp,
level: logData.level as LogEntry['level'],
- message: logData.message,
+ message: cleanMessage,
service: logData.service,
containerId: logData.containerId
};
@@ -181,7 +226,8 @@
}
function formatTimestamp(timestamp: string): string {
- return new Date(timestamp).toLocaleTimeString();
+ const date = new Date(timestamp);
+ return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}
function getLevelClass(level: LogEntry['level']): string {
@@ -225,7 +271,11 @@
</div>
{/if}
- <div bind:this={logContainer} class="log-viewer overflow-y-auto rounded-lg border bg-black font-mono text-sm text-white" style="height: {height}">
+ <div
+ bind:this={logContainer}
+ class="log-viewer overflow-y-auto rounded-lg border bg-black font-mono text-sm text-white"
+ style="height: {height}"
+ >
{#if logs.length === 0}
<div class="p-4 text-center text-gray-500">
{#if !containerId}
@@ -238,24 +288,29 @@
</div>
{:else}
{#each logs as log (log.timestamp + log.message + (log.service || ''))}
- <div class="flex border-l-2 border-transparent px-3 py-1 transition-colors hover:border-blue-500 hover:bg-gray-900/50">
+ <div
+ class="flex border-l-2 border-transparent px-3 py-1 transition-colors hover:border-blue-500 hover:bg-gray-900/50"
+ >
{#if showTimestamps}
- <span class="mr-3 w-20 shrink-0 text-xs text-gray-500">
+ <span class="mr-3 shrink-0 text-xs text-gray-500 min-w-fit">
{formatTimestamp(log.timestamp)}
</span>
{/if}
- <span class="mr-2 w-12 shrink-0 text-xs {getLevelClass(log.level)}">
+ <span class="mr-2 shrink-0 text-xs {getLevelClass(log.level)} min-w-fit">
{log.level.toUpperCase()}
</span>
{#if type === 'stack' && log.service}
- <span class="mr-2 w-16 shrink-0 truncate text-xs text-blue-400" title={log.service}>
+ <span
+ class="mr-2 shrink-0 truncate text-xs text-blue-400 min-w-fit"
+ title={log.service}
+ >
{log.service}
</span>
{/if}
- <span class="break-all whitespace-pre-wrap text-gray-300">
+ <span class="break-words whitespace-pre-wrap text-gray-300 flex-1">
{log.message}
</span>
</div>
@@ -266,6 +321,7 @@
<style>
.log-viewer {
- font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
+ font-family:
+ 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
}
</style>
diff --git a/frontend/src/lib/components/arcane-table.svelte b/frontend/src/lib/components/arcane-table.svelte
new file mode 100644
index 000000000..ab42dd5fd
--- /dev/null
+++ b/frontend/src/lib/components/arcane-table.svelte
@@ -0,0 +1,220 @@
+<script lang="ts" generics="TData extends {id: string}">
+ import { Checkbox } from '$lib/components/ui/checkbox/index.js';
+ import { Input } from '$lib/components/ui/input/index.js';
+ import * as Pagination from '$lib/components/ui/pagination/index.js';
+ import * as Select from '$lib/components/ui/select/index.js';
+ import * as Table from '$lib/components/ui/table/index.js';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { ChevronDown } from '@lucide/svelte';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import { debounced } from '$lib/utils';
+ import { cn } from '$lib/utils';
+ import type { Snippet } from 'svelte';
+
+ let {
+ items,
+ requestOptions = $bindable(),
+ selectedIds = $bindable(),
+ withoutSearch = false,
+ withoutPagination = false,
+ selectionDisabled = false,
+ onRefresh,
+ columns,
+ rows,
+ filterPlaceholder = 'Search...',
+ noResultsMessage = 'No results found',
+ itemsPerPageLabel = 'Items per page',
+ class: className = ''
+ }: {
+ items: Paginated<TData>;
+ requestOptions: SearchPaginationSortRequest;
+ selectedIds?: string[];
+ withoutSearch?: boolean;
+ withoutPagination?: boolean;
+ selectionDisabled?: boolean;
+ onRefresh: (requestOptions: SearchPaginationSortRequest) => Promise<Paginated<TData>>;
+ columns: { label: string; hidden?: boolean; sortColumn?: string }[];
+ rows: Snippet<[{ item: TData }]>;
+ filterPlaceholder?: string;
+ noResultsMessage?: string;
+ itemsPerPageLabel?: string;
+ class?: string;
+ } = $props();
+
+ let searchValue = $state('');
+ let availablePageSizes: number[] = [10, 20, 50, 100];
+
+ let allChecked = $derived.by(() => {
+ if (!selectedIds || items.data.length === 0) return false;
+ for (const item of items.data) {
+ if (!selectedIds.includes(item.id)) {
+ return false;
+ }
+ }
+ return true;
+ });
+
+ const onSearch = debounced(async (search: string) => {
+ requestOptions.search = search;
+ await onRefresh(requestOptions);
+ searchValue = search;
+ }, 300);
+
+ async function onAllCheck(checked: boolean) {
+ if (checked) {
+ selectedIds = items.data.map((item) => item.id);
+ } else {
+ selectedIds = [];
+ }
+ }
+
+ async function onCheck(checked: boolean, id: string) {
+ if (!selectedIds) return;
+ if (checked) {
+ selectedIds = [...selectedIds, id];
+ } else {
+ selectedIds = selectedIds.filter((selectedId) => selectedId !== id);
+ }
+ }
+
+ async function onPageChange(page: number) {
+ requestOptions.pagination = { limit: items.pagination.itemsPerPage, page };
+ onRefresh(requestOptions);
+ }
+
+ async function onPageSizeChange(size: number) {
+ requestOptions.pagination = { limit: size, page: 1 };
+ onRefresh(requestOptions);
+ }
+
+ async function onSort(column?: string, direction: 'asc' | 'desc' = 'asc') {
+ if (!column) return;
+
+ requestOptions.sort = { column, direction };
+ onRefresh(requestOptions);
+ }
+</script>
+
+<div class={cn('space-y-4', className)}>
+ {#if !withoutSearch}
+ <Input
+ value={searchValue}
+ class={cn(
+ 'relative z-50 mb-4 max-w-sm',
+ items.data.length == 0 && searchValue == '' && 'hidden'
+ )}
+ placeholder={filterPlaceholder}
+ type="text"
+ oninput={(e) => onSearch(e.currentTarget.value)}
+ />
+ {/if}
+
+ {#if items.data.length === 0 && searchValue === ''}
+ <div class="my-5 flex flex-col items-center">
+ <p class="text-muted-foreground mt-3 text-sm">{noResultsMessage}</p>
+ </div>
+ {:else}
+ <Table.Root class="min-w-full table-auto overflow-x-auto">
+ <Table.Header>
+ <Table.Row>
+ {#if selectedIds && !selectionDisabled}
+ <Table.Head class="w-12">
+ <Checkbox checked={allChecked} onCheckedChange={(c) => onAllCheck(c as boolean)} />
+ </Table.Head>
+ {/if}
+ {#each columns as column}
+ <Table.Head class={cn(column.hidden && 'sr-only', column.sortColumn && 'px-0')}>
+ {#if column.sortColumn}
+ <Button
+ variant="ghost"
+ class="flex items-center"
+ onclick={() =>
+ onSort(
+ column.sortColumn,
+ requestOptions.sort?.direction === 'desc' ? 'asc' : 'desc'
+ )}
+ >
+ {column.label}
+ {#if requestOptions.sort?.column === column.sortColumn}
+ <ChevronDown
+ class={cn(
+ 'ml-2 size-4',
+ requestOptions.sort?.direction === 'asc' ? 'rotate-180' : ''
+ )}
+ />
+ {/if}
+ </Button>
+ {:else}
+ {column.label}
+ {/if}
+ </Table.Head>
+ {/each}
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {#each items.data as item}
+ <Table.Row class={selectedIds?.includes(item.id) ? 'bg-muted/20' : ''}>
+ {#if selectedIds && !selectionDisabled}
+ <Table.Cell class="w-12">
+ <Checkbox
+ checked={selectedIds.includes(item.id)}
+ onCheckedChange={(c) => onCheck(c as boolean, item.id)}
+ />
+ </Table.Cell>
+ {/if}
+ {@render rows({ item })}
+ </Table.Row>
+ {/each}
+ </Table.Body>
+ </Table.Root>
+
+ {#if !withoutPagination}
+ <div class="mt-5 flex flex-col-reverse items-center justify-between gap-3 sm:flex-row">
+ <div class="flex items-center space-x-2">
+ <p class="text-sm font-medium">{itemsPerPageLabel}</p>
+ <Select.Root
+ type="single"
+ value={items.pagination.itemsPerPage.toString()}
+ onValueChange={(v) => onPageSizeChange(Number(v))}
+ >
+ <Select.Trigger class="h-9 w-[80px]">
+ {items.pagination.itemsPerPage}
+ </Select.Trigger>
+ <Select.Content>
+ {#each availablePageSizes as size}
+ <Select.Item value={size.toString()}>{size}</Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ </div>
+ <Pagination.Root
+ class="mx-0 w-auto"
+ count={items.pagination.totalItems}
+ perPage={items.pagination.itemsPerPage}
+ {onPageChange}
+ page={items.pagination.currentPage}
+ >
+ {#snippet children({ pages })}
+ <Pagination.Content class="flex justify-end">
+ <Pagination.Item>
+ <Pagination.PrevButton />
+ </Pagination.Item>
+ {#each pages as page (page.key)}
+ {#if page.type !== 'ellipsis' && page.value != 0}
+ <Pagination.Item>
+ <Pagination.Link {page} isActive={items.pagination.currentPage === page.value}>
+ {page.value}
+ </Pagination.Link>
+ </Pagination.Item>
+ {/if}
+ {/each}
+ <Pagination.Item>
+ <Pagination.NextButton />
+ </Pagination.Item>
+ </Pagination.Content>
+ {/snippet}
+ </Pagination.Root>
+ </div>
+ {/if}
+ {/if}
+</div>
diff --git a/frontend/src/lib/components/maturity-item.svelte b/frontend/src/lib/components/maturity-item.svelte
index f85227e94..6e17a4fa3 100644
--- a/frontend/src/lib/components/maturity-item.svelte
+++ b/frontend/src/lib/components/maturity-item.svelte
@@ -1,9 +1,21 @@
<script lang="ts">
import * as Tooltip from '$lib/components/ui/tooltip/index.js';
- import { CircleCheck, CircleFadingArrowUp, CircleArrowUp, Loader2, Clock, Package, Calendar, AlertTriangle, RefreshCw, ArrowRight } from '@lucide/svelte';
- import ImageMaturityAPIService from '$lib/services/api/image-maturity-api-service';
+ import {
+ CircleCheck,
+ CircleFadingArrowUp,
+ CircleArrowUp,
+ Loader2,
+ Clock,
+ Package,
+ Calendar,
+ AlertTriangle,
+ RefreshCw,
+ ArrowRight
+ } from '@lucide/svelte';
+ import { environmentAPI } from '$lib/services/api';
import { toast } from 'svelte-sonner';
import { invalidateAll } from '$app/navigation';
+ import { formatDate } from '$lib/utils/string.utils';
interface MaturityData {
updatesAvailable: boolean;
@@ -23,10 +35,8 @@
let { maturity = undefined, isLoadingInBackground = false, imageId, repo, tag }: Props = $props();
- const imageMaturityApi = new ImageMaturityAPIService();
let isChecking = $state(false);
- // Check if image has valid repo/tag for checking
const canCheckMaturity = $derived(repo && tag && repo !== '<none>' && tag !== '<none>');
async function checkImageMaturity() {
@@ -34,12 +44,10 @@
isChecking = true;
try {
- // Since the backend only has bulk check, we trigger that
- const result = await imageMaturityApi.triggerMaturityCheck();
+ const result = await environmentAPI.triggerMaturityCheck([imageId]);
if (result.success) {
toast.success('Maturity check completed');
- // Refresh the page to get updated data
await invalidateAll();
} else {
toast.error('Maturity check failed');
@@ -52,58 +60,6 @@
}
}
- // Helper function to format the date more nicely
- function formatDate(dateString: string | undefined): string {
- if (!dateString || dateString === 'Unknown date' || dateString === 'Invalid date') {
- return 'Unknown';
- }
-
- try {
- const date = new Date(dateString);
- if (isNaN(date.getTime())) return 'Unknown';
-
- const now = new Date();
- const diffTime = date.getTime() - now.getTime();
- const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
- const absDiffDays = Math.abs(diffDays);
-
- // Handle same day (within 24 hours)
- if (absDiffDays === 0) {
- const diffHours = Math.floor(Math.abs(diffTime) / (1000 * 60 * 60));
- if (diffHours === 0) return 'Now';
- return diffTime > 0 ? `In ${diffHours} hours` : `${diffHours} hours ago`;
- }
-
- // Future dates
- if (diffTime > 0) {
- if (diffDays === 1) return 'Tomorrow';
- if (diffDays < 7) return `In ${diffDays} days`;
- if (diffDays < 30) {
- const weeks = Math.floor(diffDays / 7);
- return weeks === 1 ? 'In 1 week' : `In ${weeks} weeks`;
- }
- return 'Future';
- }
-
- // Past dates
- if (absDiffDays === 1) return 'Yesterday';
- if (absDiffDays < 7) return `${absDiffDays} days ago`;
- if (absDiffDays < 30) {
- const weeks = Math.floor(absDiffDays / 7);
- return weeks === 1 ? '1 week ago' : `${weeks} weeks ago`;
- }
- if (absDiffDays < 365) {
- const months = Math.floor(absDiffDays / 30);
- return months === 1 ? '1 month ago' : `${months} months ago`;
- }
- const years = Math.floor(absDiffDays / 365);
- return years === 1 ? '1 year ago' : `${years} years ago`;
- } catch {
- return 'Unknown';
- }
- }
-
- // Helper function to get status color
function getStatusColor(status: string): string {
switch (status) {
case 'Matured':
@@ -117,7 +73,6 @@
}
}
- // Helper function to get update priority level
function getUpdatePriority(maturity: MaturityData): {
level: string;
color: string;
@@ -127,7 +82,6 @@
return { level: 'None', color: 'text-green-500', description: 'Image is up to date' };
}
- // If we have a latest version, include it in the description
let description = 'Stable update available';
if (maturity.latestVersion) {
description = `Update to ${maturity.latestVersion} available`;
@@ -141,7 +95,9 @@
return {
level: 'Optional',
color: 'text-yellow-500',
- description: maturity.latestVersion ? `${maturity.latestVersion} available, but not yet matured` : 'Recent update, may be unstable'
+ description: maturity.latestVersion
+ ? `${maturity.latestVersion} available, but not yet matured`
+ : 'Recent update, may be unstable'
};
}
@@ -156,29 +112,62 @@
<Tooltip.Trigger>
<span class="mr-2 inline-flex size-4 items-center justify-center align-middle">
{#if !maturity.updatesAvailable}
- <CircleCheck class="size-4 text-green-500" fill="none" stroke="currentColor" strokeWidth="2" />
+ <CircleCheck
+ class="size-4 text-green-500"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ />
{:else if maturity.status === 'Not Matured'}
- <CircleFadingArrowUp class="size-4 text-yellow-500" fill="none" stroke="currentColor" stroke-width="2" />
+ <CircleFadingArrowUp
+ class="size-4 text-yellow-500"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ />
{:else}
- <CircleArrowUp class="size-4 text-blue-500" fill="none" stroke="currentColor" stroke-width="2" />
+ <CircleArrowUp
+ class="size-4 text-blue-500"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ />
{/if}
</span>
</Tooltip.Trigger>
- <Tooltip.Content side="right" class="bg-popover text-popover-foreground border-border tooltip-with-arrow maturity-tooltip relative max-w-[280px] border p-4 shadow-lg" align="center">
+ <Tooltip.Content
+ side="right"
+ class="bg-popover text-popover-foreground border-border tooltip-with-arrow maturity-tooltip relative max-w-[280px] border p-4 shadow-lg"
+ align="center"
+ >
<div class="space-y-3">
<!-- Header with icon and status -->
<div class="border-border flex items-center gap-3 border-b pb-2">
{#if !maturity.updatesAvailable}
- <div class="flex h-8 w-8 items-center justify-center rounded-full border border-green-500/20 bg-green-500/10">
- <CircleCheck class="size-5 text-green-500" fill="none" stroke="currentColor" strokeWidth="2" />
+ <div
+ class="flex h-8 w-8 items-center justify-center rounded-full border border-green-500/20 bg-green-500/10"
+ >
+ <CircleCheck
+ class="size-5 text-green-500"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ />
</div>
<div>
<div class="text-sm font-semibold">Up to Date</div>
<div class="text-muted-foreground text-xs">No updates available</div>
</div>
{:else if maturity.status === 'Not Matured'}
- <div class="flex h-8 w-8 items-center justify-center rounded-full border border-yellow-500/20 bg-yellow-500/10">
- <CircleFadingArrowUp class="size-5 text-yellow-500" fill="none" stroke="currentColor" stroke-width="2" />
+ <div
+ class="flex h-8 w-8 items-center justify-center rounded-full border border-yellow-500/20 bg-yellow-500/10"
+ >
+ <CircleFadingArrowUp
+ class="size-5 text-yellow-500"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ />
</div>
<div>
<div class="text-sm font-semibold">Update Available</div>
@@ -188,8 +177,15 @@
</div>
</div>
{:else}
- <div class="flex h-8 w-8 items-center justify-center rounded-full border border-blue-500/20 bg-blue-500/10">
- <CircleArrowUp class="size-5 text-blue-500" fill="none" stroke="currentColor" stroke-width="2" />
+ <div
+ class="flex h-8 w-8 items-center justify-center rounded-full border border-blue-500/20 bg-blue-500/10"
+ >
+ <CircleArrowUp
+ class="size-5 text-blue-500"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ />
</div>
<div>
<div class="text-sm font-semibold">Stable Update</div>
@@ -215,7 +211,9 @@
<ArrowRight class="size-3" />
<span>Latest</span>
</div>
- <span class="font-mono font-medium text-blue-600 dark:text-blue-400">{maturity.latestVersion}</span>
+ <span class="font-mono font-medium text-blue-600 dark:text-blue-400"
+ >{maturity.latestVersion}</span
+ >
</div>
{/if}
@@ -257,7 +255,11 @@
<!-- Re-check button -->
{#if canCheckMaturity}
<div class="border-border border-t pt-2">
- <button onclick={checkImageMaturity} disabled={isChecking} class="flex items-center gap-1.5 text-xs text-blue-600 hover:text-blue-700 disabled:cursor-not-allowed disabled:opacity-50 dark:text-blue-400 dark:hover:text-blue-300">
+ <button
+ onclick={checkImageMaturity}
+ disabled={isChecking}
+ class="flex items-center gap-1.5 text-xs text-blue-600 hover:text-blue-700 disabled:cursor-not-allowed disabled:opacity-50 dark:text-blue-400 dark:hover:text-blue-300"
+ >
{#if isChecking}
<Loader2 class="size-3 animate-spin" />
Checking...
@@ -280,7 +282,11 @@
<Loader2 class="size-4 animate-spin text-blue-400" />
</span>
</Tooltip.Trigger>
- <Tooltip.Content side="right" class="bg-popover text-popover-foreground border-border tooltip-with-arrow relative max-w-[220px] border p-3 shadow-lg" align="center">
+ <Tooltip.Content
+ side="right"
+ class="bg-popover text-popover-foreground border-border tooltip-with-arrow relative max-w-[220px] border p-3 shadow-lg"
+ align="center"
+ >
<div class="flex items-center gap-2">
<Loader2 class="size-4 animate-spin text-blue-400" />
<div>
@@ -297,23 +303,37 @@
<Tooltip.Trigger>
<span class="mr-2 inline-flex size-4 items-center justify-center">
{#if canCheckMaturity}
- <button onclick={checkImageMaturity} disabled={isChecking} class="group flex h-4 w-4 items-center justify-center rounded-full border-2 border-dashed border-gray-400 transition-colors hover:border-blue-400 hover:bg-blue-50 disabled:cursor-not-allowed dark:hover:bg-blue-950">
+ <button
+ onclick={checkImageMaturity}
+ disabled={isChecking}
+ class="group flex h-4 w-4 items-center justify-center rounded-full border-2 border-dashed border-gray-400 transition-colors hover:border-blue-400 hover:bg-blue-50 disabled:cursor-not-allowed dark:hover:bg-blue-950"
+ >
{#if isChecking}
<Loader2 class="h-2 w-2 animate-spin text-blue-400" />
{:else}
- <div class="h-1.5 w-1.5 rounded-full bg-gray-400 transition-colors group-hover:bg-blue-400"></div>
+ <div
+ class="h-1.5 w-1.5 rounded-full bg-gray-400 transition-colors group-hover:bg-blue-400"
+ ></div>
{/if}
</button>
{:else}
- <div class="flex h-4 w-4 items-center justify-center rounded-full border-2 border-dashed border-gray-400 opacity-30">
+ <div
+ class="flex h-4 w-4 items-center justify-center rounded-full border-2 border-dashed border-gray-400 opacity-30"
+ >
<div class="h-1.5 w-1.5 rounded-full bg-gray-400"></div>
</div>
{/if}
</span>
</Tooltip.Trigger>
- <Tooltip.Content side="right" class="bg-popover text-popover-foreground border-border tooltip-with-arrow relative max-w-[240px] border p-3 shadow-lg" align="center">
+ <Tooltip.Content
+ side="right"
+ class="bg-popover text-popover-foreground border-border tooltip-with-arrow relative max-w-[240px] border p-3 shadow-lg"
+ align="center"
+ >
<div class="flex items-center gap-2">
- <div class="bg-muted border-border flex h-6 w-6 items-center justify-center rounded-full border">
+ <div
+ class="bg-muted border-border flex h-6 w-6 items-center justify-center rounded-full border"
+ >
<AlertTriangle class="text-muted-foreground size-3" />
</div>
<div>
diff --git a/frontend/src/lib/components/meter-metric.svelte b/frontend/src/lib/components/meter-metric.svelte
new file mode 100644
index 000000000..bcf4282b3
--- /dev/null
+++ b/frontend/src/lib/components/meter-metric.svelte
@@ -0,0 +1,60 @@
+<script lang="ts">
+ import * as Card from '$lib/components/ui/card/index.js';
+ import Meter from '$lib/components/ui/meter/meter.svelte';
+
+ interface MetricDataPoint {
+ date: Date;
+ value: number;
+ }
+
+ interface Props {
+ title: string;
+ description?: string;
+ currentValue: number;
+ data: MetricDataPoint[];
+ unit?: string;
+ formatValue?: (value: number) => string;
+ color?: string;
+ maxValue?: number;
+ }
+
+ let {
+ title,
+ description,
+ currentValue,
+ data,
+ unit = '',
+ formatValue = (v) => `${v.toFixed(1)}${unit}`,
+ color = 'var(--chart-1)',
+ maxValue = 100
+ }: Props = $props();
+
+ const percentage = $derived((currentValue / maxValue) * 100);
+</script>
+
+<div
+ class="group relative overflow-hidden rounded-lg border border-white/10 bg-gradient-to-br from-white/5 to-white/2 backdrop-blur-sm transition-all duration-300 hover:border-white/20 hover:bg-gradient-to-br hover:from-white/10 hover:to-white/5"
+>
+ <div
+ class="absolute inset-0 bg-gradient-to-br from-white/5 via-transparent to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100"
+ ></div>
+
+ <div class="relative z-10 p-4">
+ <div class="mb-3 text-center">
+ <h3 class="text-sm font-medium text-white/90">{title}</h3>
+ {#if description}
+ <p class="text-xs text-white/60">{description}</p>
+ {/if}
+ </div>
+
+ <div class="flex flex-col items-center space-y-3">
+ <div class="text-2xl font-bold text-white/95">{formatValue(currentValue)}</div>
+
+ <div class="w-full max-w-[100px]">
+ <Meter value={percentage} class="h-1.5 bg-white/10" />
+ </div>
+
+ <div class="text-xs font-medium text-white/70">{percentage.toFixed(1)}%</div>
+ </div>
+ </div>
+</div>
diff --git a/frontend/src/lib/components/sheets/user-form-sheet.svelte b/frontend/src/lib/components/sheets/user-form-sheet.svelte
index c530b001a..835296ed6 100644
--- a/frontend/src/lib/components/sheets/user-form-sheet.svelte
+++ b/frontend/src/lib/components/sheets/user-form-sheet.svelte
@@ -12,12 +12,23 @@
open: boolean;
userToEdit: User | null;
roles: { id: string; name: string }[];
- onSubmit: (data: { user: Partial<User> & { password?: string }; isEditMode: boolean; userId?: string }) => void;
+ onSubmit: (data: {
+ user: Partial<User> & { password?: string };
+ isEditMode: boolean;
+ userId?: string;
+ }) => void;
isLoading: boolean;
allowUsernameEdit?: boolean;
};
- let { open = $bindable(false), userToEdit = $bindable(), roles, onSubmit, isLoading, allowUsernameEdit = false }: UserFormProps = $props();
+ let {
+ open = $bindable(false),
+ userToEdit = $bindable(),
+ roles,
+ onSubmit,
+ isLoading,
+ allowUsernameEdit = false
+ }: UserFormProps = $props();
let isEditMode = $derived(!!userToEdit);
let canEditUsername = $derived(!isEditMode || allowUsernameEdit);
@@ -32,11 +43,11 @@
});
let formData = $derived({
- username: userToEdit?.username || '',
+ username: userToEdit?.Username || '',
password: '',
- displayName: userToEdit?.displayName || '',
- email: userToEdit?.email || '',
- isAdmin: Boolean(userToEdit?.roles?.includes('admin'))
+ displayName: userToEdit?.DisplayName || '',
+ email: userToEdit?.Email || '',
+ isAdmin: Boolean(userToEdit?.Roles?.includes('admin'))
});
let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
@@ -46,10 +57,10 @@
if (!data) return;
const userData: Partial<User> & { password?: string } = {
- username: data.username,
- displayName: data.displayName,
- email: data.email,
- roles: [data.isAdmin ? 'admin' : 'user']
+ Username: data.username,
+ DisplayName: data.displayName,
+ Email: data.email,
+ Roles: [data.isAdmin ? 'admin' : 'user']
};
// Only include password if it's provided (for create) or if editing and password is not empty
@@ -57,7 +68,7 @@
userData.password = data.password;
}
- onSubmit({ user: userData, isEditMode, userId: userToEdit?.id });
+ onSubmit({ user: userData, isEditMode, userId: userToEdit?.ID });
}
function handleOpenChange(newOpenState: boolean) {
@@ -80,21 +91,60 @@
{isEditMode ? 'Edit User' : 'Create New User'}
</Sheet.Title>
<Sheet.Description class="text-sm text-muted-foreground mt-1">
- {isEditMode ? `Update the details for ${userToEdit?.username || 'this user'}` : 'Add a new user to your system with the required permissions'}
+ {isEditMode
+ ? `Update the details for ${userToEdit?.Username || 'this user'}`
+ : 'Add a new user to your system with the required permissions'}
</Sheet.Description>
</div>
</div>
</Sheet.Header>
<form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-6">
- <FormInput label="Username *" type="text" description="Unique username for the user" disabled={!canEditUsername} bind:input={$inputs.username} />
- <FormInput label={isEditMode ? 'Password' : 'Password *'} type="password" placeholder={isEditMode ? 'Leave empty to keep current password' : 'Enter password'} description={isEditMode ? 'Leave empty to keep current password' : 'Password for the user account'} bind:input={$inputs.password} />
- <FormInput label="Display Name" type="text" placeholder="Full name or display name" description="Optional display name for the user" bind:input={$inputs.displayName} />
- <FormInput label="Email" type="email" placeholder="[email protected]" description="Email address for the user" bind:input={$inputs.email} />
- <SwitchWithLabel id="isAdminSwitch" label="Administrator" description="Grant administrator privileges to this user" bind:checked={$inputs.isAdmin.value} />
+ <FormInput
+ label="Username *"
+ type="text"
+ description="Unique username for the user"
+ disabled={!canEditUsername}
+ bind:input={$inputs.username}
+ />
+ <FormInput
+ label={isEditMode ? 'Password' : 'Password *'}
+ type="password"
+ placeholder={isEditMode ? 'Leave empty to keep current password' : 'Enter password'}
+ description={isEditMode
+ ? 'Leave empty to keep current password'
+ : 'Password for the user account'}
+ bind:input={$inputs.password}
+ />
+ <FormInput
+ label="Display Name"
+ type="text"
+ placeholder="Full name or display name"
+ description="Optional display name for the user"
+ bind:input={$inputs.displayName}
+ />
+ <FormInput
+ label="Email"
+ type="email"
+ placeholder="[email protected]"
+ description="Email address for the user"
+ bind:input={$inputs.email}
+ />
+ <SwitchWithLabel
+ id="isAdminSwitch"
+ label="Administrator"
+ description="Grant administrator privileges to this user"
+ bind:checked={$inputs.isAdmin.value}
+ />
<Sheet.Footer class="flex flex-row gap-2">
- <Button type="button" class="arcane-button-cancel flex-1" variant="outline" onclick={() => (open = false)} disabled={isLoading}>Cancel</Button>
+ <Button
+ type="button"
+ class="arcane-button-cancel flex-1"
+ variant="outline"
+ onclick={() => (open = false)}
+ disabled={isLoading}>Cancel</Button
+ >
<Button type="submit" class="arcane-button-create flex-1" disabled={isLoading}>
{#if isLoading}
<Loader2 class="mr-2 size-4 animate-spin" />
diff --git a/frontend/src/lib/components/sidebar/sidebar.svelte b/frontend/src/lib/components/sidebar/sidebar.svelte
index 3b5e40943..2ec20f52b 100644
--- a/frontend/src/lib/components/sidebar/sidebar.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar.svelte
@@ -1,5 +1,19 @@
<script lang="ts" module>
- import { FileStack, HardDrive, Home, Network, Container, ImageIcon, SettingsIcon, DatabaseIcon, LayoutTemplate, UserIcon, Shield, ComputerIcon, LockKeyholeIcon } from '@lucide/svelte';
+ import {
+ FileStack,
+ HardDrive,
+ Home,
+ Network,
+ Container,
+ ImageIcon,
+ SettingsIcon,
+ DatabaseIcon,
+ LayoutTemplate,
+ UserIcon,
+ Shield,
+ ComputerIcon,
+ LockKeyholeIcon
+ } from '@lucide/svelte';
const staticData = {
settingsItems: [
@@ -35,7 +49,7 @@
}
],
managementItems: [
- { title: 'Dashboard', url: '/', icon: Home },
+ { title: 'Dashboard', url: '/dashboard', icon: Home },
{ title: 'Containers', url: '/containers', icon: Container },
{ title: 'Compose Projects', url: '/compose', icon: FileStack },
{ title: 'Images', url: '/images', icon: ImageIcon },
@@ -85,7 +99,11 @@
<SidebarItemGroup label="Administration" items={staticData.settingsItems} />
</Sidebar.Content>
<Sidebar.Footer>
- <SidebarUpdatebanner {isCollapsed} {versionInformation} updateAvailable={versionInformation.updateAvailable} />
+ <SidebarUpdatebanner
+ {isCollapsed}
+ {versionInformation}
+ updateAvailable={versionInformation.updateAvailable}
+ />
{#if user}
<SidebarUser {isCollapsed} {user} />
{/if}
diff --git a/frontend/src/lib/components/ui/data-table/data-table.svelte.ts b/frontend/src/lib/components/ui/data-table/data-table.svelte.ts
index 4c1aee773..9e0b91306 100644
--- a/frontend/src/lib/components/ui/data-table/data-table.svelte.ts
+++ b/frontend/src/lib/components/ui/data-table/data-table.svelte.ts
@@ -1,4 +1,10 @@
-import { type RowData, type TableOptions, type TableOptionsResolved, type TableState, createTable } from '@tanstack/table-core';
+import {
+ type RowData,
+ type TableOptions,
+ type TableOptionsResolved,
+ type TableState,
+ createTable,
+} from "@tanstack/table-core";
/**
* Creates a reactive TanStack table object for Svelte.
@@ -32,9 +38,12 @@ export function createSvelteTable<TData extends RowData>(options: TableOptions<T
state: {},
onStateChange() {},
renderFallbackValue: null,
- mergeOptions: (defaultOptions: TableOptions<TData>, options: Partial<TableOptions<TData>>) => {
+ mergeOptions: (
+ defaultOptions: TableOptions<TData>,
+ options: Partial<TableOptions<TData>>
+ ) => {
return mergeObjects(defaultOptions, options);
- }
+ },
},
options
);
@@ -53,7 +62,7 @@ export function createSvelteTable<TData extends RowData>(options: TableOptions<T
else state = mergeObjects(state, updater);
options.onStateChange?.(updater);
- }
+ },
});
});
}
@@ -67,37 +76,66 @@ export function createSvelteTable<TData extends RowData>(options: TableOptions<T
return table;
}
+type MaybeThunk<T extends object> = T | (() => T | null | undefined);
+type Intersection<T extends readonly unknown[]> = (T extends [infer H, ...infer R]
+ ? H & Intersection<R>
+ : unknown) & {};
+
/**
- * Merges objects together while keeping their getters alive.
- * Taken from SolidJS: {@link https://github.com/solidjs/solid/blob/24abc825c0996fd2bc8c1de1491efe9a7e743aff/packages/solid/src/server/rendering.ts#L82-L115}
+ * Lazily merges several objects (or thunks) while preserving
+ * getter semantics from every source.
+ *
+ * Proxy-based to avoid known WebKit recursion issue.
*/
-function mergeObjects<T>(source: T): T;
-function mergeObjects<T, U>(source: T, source1: U): T & U;
-function mergeObjects<T, U, V>(source: T, source1: U, source2: V): T & U & V;
-function mergeObjects<T, U, V, W>(source: T, source1: U, source2: V, source3: W): T & U & V & W;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function mergeObjects(...sources: any): any {
- const target = {};
- for (let i = 0; i < sources.length; i++) {
- let source = sources[i];
- if (typeof source === 'function') source = source();
- if (source) {
- const descriptors = Object.getOwnPropertyDescriptors(source);
- for (const key in descriptors) {
- if (key in target) continue;
- Object.defineProperty(target, key, {
- enumerable: true,
- get() {
- for (let i = sources.length - 1; i >= 0; i--) {
- let s = sources[i];
- if (typeof s === 'function') s = s();
- const v = (s || {})[key];
- if (v !== undefined) return v;
- }
+export function mergeObjects<Sources extends readonly MaybeThunk<any>[]>(
+ ...sources: Sources
+): Intersection<{ [K in keyof Sources]: Sources[K] }> {
+ const resolve = <T extends object>(src: MaybeThunk<T>): T | undefined =>
+ typeof src === "function" ? (src() ?? undefined) : src;
+
+ const findSourceWithKey = (key: PropertyKey) => {
+ for (let i = sources.length - 1; i >= 0; i--) {
+ const obj = resolve(sources[i]);
+ if (obj && key in obj) return obj;
+ }
+ return undefined;
+ };
+
+ return new Proxy(Object.create(null), {
+ get(_, key) {
+ const src = findSourceWithKey(key);
+
+ return src?.[key as never];
+ },
+
+ has(_, key) {
+ return !!findSourceWithKey(key);
+ },
+
+ ownKeys(): (string | symbol)[] {
+ const all = new Set<string | symbol>();
+ for (const s of sources) {
+ const obj = resolve(s);
+ if (obj) {
+ for (const k of Reflect.ownKeys(obj) as (string | symbol)[]) {
+ all.add(k);
}
- });
+ }
}
- }
- }
- return target;
+ return [...all];
+ },
+
+ getOwnPropertyDescriptor(_, key) {
+ const src = findSourceWithKey(key);
+ if (!src) return undefined;
+ return {
+ configurable: true,
+ enumerable: true,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ value: (src as any)[key],
+ writable: true,
+ };
+ },
+ }) as Intersection<{ [K in keyof Sources]: Sources[K] }>;
}
diff --git a/frontend/src/lib/components/ui/data-table/flex-render.svelte b/frontend/src/lib/components/ui/data-table/flex-render.svelte
index ff24a89ee..12d2af10e 100644
--- a/frontend/src/lib/components/ui/data-table/flex-render.svelte
+++ b/frontend/src/lib/components/ui/data-table/flex-render.svelte
@@ -1,16 +1,16 @@
-<script lang="ts" module>
- import type { CellContext, ColumnDefTemplate, HeaderContext } from '@tanstack/table-core';
-
- type TData = unknown;
- type TValue = unknown;
- type TContext = unknown;
-</script>
-
-<script lang="ts" generics="TData, TValue, TContext extends HeaderContext<TData, TValue> | CellContext<TData, TValue>">
- import { RenderComponentConfig, RenderSnippetConfig } from './render-helpers.js';
+<script
+ lang="ts"
+ generics="TData, TValue, TContext extends HeaderContext<TData, TValue> | CellContext<TData, TValue>"
+>
+ import type { CellContext, ColumnDefTemplate, HeaderContext } from "@tanstack/table-core";
+ import { RenderComponentConfig, RenderSnippetConfig } from "./render-helpers.js";
type Props = {
/** The cell or header field of the current cell's column definition. */
- content?: TContext extends HeaderContext<TData, TValue> ? ColumnDefTemplate<HeaderContext<TData, TValue>> : TContext extends CellContext<TData, TValue> ? ColumnDefTemplate<CellContext<TData, TValue>> : never;
+ content?: TContext extends HeaderContext<TData, TValue>
+ ? ColumnDefTemplate<HeaderContext<TData, TValue>>
+ : TContext extends CellContext<TData, TValue>
+ ? ColumnDefTemplate<CellContext<TData, TValue>>
+ : never;
/** The result of the `getContext()` function of the header or cell */
context: TContext;
};
@@ -18,7 +18,7 @@
let { content, context }: Props = $props();
</script>
-{#if typeof content === 'string'}
+{#if typeof content === "string"}
{content}
{:else if content instanceof Function}
<!-- It's unlikely that a CellContext will be passed to a Header -->
diff --git a/frontend/src/lib/components/ui/data-table/index.ts b/frontend/src/lib/components/ui/data-table/index.ts
index 05fb82150..5f4e77ea0 100644
--- a/frontend/src/lib/components/ui/data-table/index.ts
+++ b/frontend/src/lib/components/ui/data-table/index.ts
@@ -1,3 +1,3 @@
-export { default as FlexRender } from './flex-render.svelte';
-export { renderComponent, renderSnippet } from './render-helpers.js';
-export { createSvelteTable } from './data-table.svelte.js';
+export { default as FlexRender } from "./flex-render.svelte";
+export { renderComponent, renderSnippet } from "./render-helpers.js";
+export { createSvelteTable } from "./data-table.svelte.js";
diff --git a/frontend/src/lib/components/ui/data-table/render-helpers.ts b/frontend/src/lib/components/ui/data-table/render-helpers.ts
index 853e14799..fa036d62a 100644
--- a/frontend/src/lib/components/ui/data-table/render-helpers.ts
+++ b/frontend/src/lib/components/ui/data-table/render-helpers.ts
@@ -1,4 +1,4 @@
-import type { Component, ComponentProps, Snippet } from 'svelte';
+import type { Component, ComponentProps, Snippet } from "svelte";
/**
* A helper class to make it easy to identify Svelte components in
@@ -19,7 +19,10 @@ import type { Component, ComponentProps, Snippet } from 'svelte';
export class RenderComponentConfig<TComponent extends Component> {
component: TComponent;
props: ComponentProps<TComponent> | Record<string, never>;
- constructor(component: TComponent, props: ComponentProps<TComponent> | Record<string, never> = {}) {
+ constructor(
+ component: TComponent,
+ props: ComponentProps<TComponent> | Record<string, never> = {}
+ ) {
this.component = component;
this.props = props;
}
@@ -74,8 +77,8 @@ export class RenderSnippetConfig<TProps> {
export function renderComponent<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
T extends Component<any>,
- Props extends ComponentProps<T>
->(component: T, props: Props) {
+ Props extends ComponentProps<T>,
+>(component: T, props: Props = {} as Props) {
return new RenderComponentConfig(component, props);
}
@@ -103,6 +106,6 @@ export function renderComponent<
* ```
* @see {@link https://tanstack.com/table/latest/docs/guide/column-defs}
*/
-export function renderSnippet<TProps>(snippet: Snippet<[TProps]>, params: TProps) {
+export function renderSnippet<TProps>(snippet: Snippet<[TProps]>, params: TProps = {} as TProps) {
return new RenderSnippetConfig(snippet, params);
}
diff --git a/frontend/src/lib/components/meter.svelte b/frontend/src/lib/components/ui/meter/meter.svelte
similarity index 72%
rename from frontend/src/lib/components/meter.svelte
rename to frontend/src/lib/components/ui/meter/meter.svelte
index efcdd0e51..e0d156d69 100644
--- a/frontend/src/lib/components/meter.svelte
+++ b/frontend/src/lib/components/ui/meter/meter.svelte
@@ -28,7 +28,7 @@
const labelId = useId();
const variantStyles = {
- default: 'bg-accent',
+ default: 'bg-primary',
success: 'bg-green-500',
warning: 'bg-amber-500',
destructive: 'bg-destructive'
@@ -54,8 +54,28 @@
</div>
{/if}
-<div class={cn('bg-secondary relative w-full overflow-hidden rounded-full', sizeStyles[size], className)}>
- <Meter.Root aria-labelledby={label ? labelId : undefined} aria-valuetext={valueLabel} {value} {min} {max} class="h-full w-full" {...restProps}>
- <div class={cn('h-full rounded-full transition-all duration-300 ease-in-out', variantStyles[variant])} style="width: {percentage}%"></div>
+<div
+ class={cn(
+ 'bg-secondary relative w-full overflow-hidden rounded-full',
+ sizeStyles[size],
+ className
+ )}
+>
+ <Meter.Root
+ aria-labelledby={label ? labelId : undefined}
+ aria-valuetext={valueLabel}
+ {value}
+ {min}
+ {max}
+ class="h-full w-full"
+ {...restProps}
+ >
+ <div
+ class={cn(
+ 'h-full rounded-full transition-all duration-300 ease-in-out',
+ variantStyles[variant]
+ )}
+ style="width: {percentage}%"
+ ></div>
</Meter.Root>
</div>
diff --git a/frontend/src/lib/components/ui/table/index.ts b/frontend/src/lib/components/ui/table/index.ts
index 99239aeea..14695c815 100644
--- a/frontend/src/lib/components/ui/table/index.ts
+++ b/frontend/src/lib/components/ui/table/index.ts
@@ -1,11 +1,11 @@
-import Root from './table.svelte';
-import Body from './table-body.svelte';
-import Caption from './table-caption.svelte';
-import Cell from './table-cell.svelte';
-import Footer from './table-footer.svelte';
-import Head from './table-head.svelte';
-import Header from './table-header.svelte';
-import Row from './table-row.svelte';
+import Root from "./table.svelte";
+import Body from "./table-body.svelte";
+import Caption from "./table-caption.svelte";
+import Cell from "./table-cell.svelte";
+import Footer from "./table-footer.svelte";
+import Head from "./table-head.svelte";
+import Header from "./table-header.svelte";
+import Row from "./table-row.svelte";
export {
Root,
@@ -24,5 +24,5 @@ export {
Footer as TableFooter,
Head as TableHead,
Header as TableHeader,
- Row as TableRow
+ Row as TableRow,
};
diff --git a/frontend/src/lib/components/ui/table/table-body.svelte b/frontend/src/lib/components/ui/table/table-body.svelte
index 0fa52ef02..29e96875f 100644
--- a/frontend/src/lib/components/ui/table/table-body.svelte
+++ b/frontend/src/lib/components/ui/table/table-body.svelte
@@ -1,11 +1,20 @@
<script lang="ts">
- import type { HTMLAttributes } from 'svelte/elements';
- import type { WithElementRef } from '$lib/utils.js';
- import { cn } from '$lib/utils.js';
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
- let { ref = $bindable(null), class: className, children, ...restProps }: WithElementRef<HTMLAttributes<HTMLTableSectionElement>> = $props();
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLTableSectionElement>> = $props();
</script>
-<tbody bind:this={ref} class={cn('[&_tr:last-child]:border-0', className)} {...restProps}>
+<tbody
+ bind:this={ref}
+ data-slot="table-body"
+ class={cn("[&_tr:last-child]:border-0", className)}
+ {...restProps}
+>
{@render children?.()}
</tbody>
diff --git a/frontend/src/lib/components/ui/table/table-caption.svelte b/frontend/src/lib/components/ui/table/table-caption.svelte
index 3faa8c7c2..4696cff57 100644
--- a/frontend/src/lib/components/ui/table/table-caption.svelte
+++ b/frontend/src/lib/components/ui/table/table-caption.svelte
@@ -1,11 +1,20 @@
<script lang="ts">
- import type { HTMLAttributes } from 'svelte/elements';
- import type { WithElementRef } from '$lib/utils.js';
- import { cn } from '$lib/utils.js';
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
- let { ref = $bindable(null), class: className, children, ...restProps }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();
</script>
-<caption bind:this={ref} class={cn('text-muted-foreground mt-4 text-sm', className)} {...restProps}>
+<caption
+ bind:this={ref}
+ data-slot="table-caption"
+ class={cn("text-muted-foreground mt-4 text-sm", className)}
+ {...restProps}
+>
{@render children?.()}
</caption>
diff --git a/frontend/src/lib/components/ui/table/table-cell.svelte b/frontend/src/lib/components/ui/table/table-cell.svelte
index 45a0afaaa..599204845 100644
--- a/frontend/src/lib/components/ui/table/table-cell.svelte
+++ b/frontend/src/lib/components/ui/table/table-cell.svelte
@@ -1,11 +1,20 @@
<script lang="ts">
- import type { HTMLTdAttributes } from 'svelte/elements';
- import type { WithElementRef } from '$lib/utils.js';
- import { cn } from '$lib/utils.js';
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLTdAttributes } from "svelte/elements";
- let { ref = $bindable(null), class: className, children, ...restProps }: WithElementRef<HTMLTdAttributes> = $props();
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLTdAttributes> = $props();
</script>
-<td bind:this={ref} class={cn('truncate overflow-hidden p-4 align-middle text-ellipsis whitespace-nowrap [&:has([role=checkbox])]:pr-0', className)} {...restProps}>
+<td
+ bind:this={ref}
+ data-slot="table-cell"
+ class={cn("whitespace-nowrap p-2 align-middle [&:has([role=checkbox])]:pr-0", className)}
+ {...restProps}
+>
{@render children?.()}
</td>
diff --git a/frontend/src/lib/components/ui/table/table-footer.svelte b/frontend/src/lib/components/ui/table/table-footer.svelte
index b3ec796c1..b9b14ebfa 100644
--- a/frontend/src/lib/components/ui/table/table-footer.svelte
+++ b/frontend/src/lib/components/ui/table/table-footer.svelte
@@ -1,11 +1,20 @@
<script lang="ts">
- import type { HTMLAttributes } from 'svelte/elements';
- import type { WithElementRef } from '$lib/utils.js';
- import { cn } from '$lib/utils.js';
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
- let { ref = $bindable(null), class: className, children, ...restProps }: WithElementRef<HTMLAttributes<HTMLTableSectionElement>> = $props();
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLTableSectionElement>> = $props();
</script>
-<tfoot bind:this={ref} class={cn('bg-muted/50 font-medium', className)} {...restProps}>
+<tfoot
+ bind:this={ref}
+ data-slot="table-footer"
+ class={cn("bg-muted/50 border-t font-medium [&>tr]:last:border-b-0", className)}
+ {...restProps}
+>
{@render children?.()}
</tfoot>
diff --git a/frontend/src/lib/components/ui/table/table-head.svelte b/frontend/src/lib/components/ui/table/table-head.svelte
index 0c65d65fd..2742939af 100644
--- a/frontend/src/lib/components/ui/table/table-head.svelte
+++ b/frontend/src/lib/components/ui/table/table-head.svelte
@@ -1,11 +1,23 @@
<script lang="ts">
- import type { HTMLThAttributes } from 'svelte/elements';
- import type { WithElementRef } from '$lib/utils.js';
- import { cn } from '$lib/utils.js';
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLThAttributes } from "svelte/elements";
- let { ref = $bindable(null), class: className, children, ...restProps }: WithElementRef<HTMLThAttributes> = $props();
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLThAttributes> = $props();
</script>
-<th bind:this={ref} class={cn('text-muted-foreground h-12 px-4 text-left align-middle font-medium [&:has([role=checkbox])]:pr-0', className)} {...restProps}>
+<th
+ bind:this={ref}
+ data-slot="table-head"
+ class={cn(
+ "text-foreground h-10 whitespace-nowrap px-2 text-left align-middle font-medium [&:has([role=checkbox])]:pr-0",
+ className
+ )}
+ {...restProps}
+>
{@render children?.()}
</th>
diff --git a/frontend/src/lib/components/ui/table/table-header.svelte b/frontend/src/lib/components/ui/table/table-header.svelte
index fa8eaaf81..f47d2597c 100644
--- a/frontend/src/lib/components/ui/table/table-header.svelte
+++ b/frontend/src/lib/components/ui/table/table-header.svelte
@@ -1,11 +1,20 @@
<script lang="ts">
- import type { HTMLAttributes } from 'svelte/elements';
- import type { WithElementRef } from '$lib/utils.js';
- import { cn } from '$lib/utils.js';
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
- let { ref = $bindable(null), class: className, children, ...restProps }: WithElementRef<HTMLAttributes<HTMLTableSectionElement>> = $props();
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLTableSectionElement>> = $props();
</script>
-<thead bind:this={ref} class={cn('[&_tr]:border-b', className)} {...restProps}>
+<thead
+ bind:this={ref}
+ data-slot="table-header"
+ class={cn("[&_tr]:border-b", className)}
+ {...restProps}
+>
{@render children?.()}
</thead>
diff --git a/frontend/src/lib/components/ui/table/table-row.svelte b/frontend/src/lib/components/ui/table/table-row.svelte
index 7358f0928..8829581c9 100644
--- a/frontend/src/lib/components/ui/table/table-row.svelte
+++ b/frontend/src/lib/components/ui/table/table-row.svelte
@@ -1,11 +1,23 @@
<script lang="ts">
- import type { HTMLAttributes } from 'svelte/elements';
- import type { WithElementRef } from '$lib/utils.js';
- import { cn } from '$lib/utils.js';
+ import { cn, type WithElementRef } from "$lib/utils.js";
+ import type { HTMLAttributes } from "svelte/elements";
- let { ref = $bindable(null), class: className, children, ...restProps }: WithElementRef<HTMLAttributes<HTMLTableRowElement>> = $props();
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLAttributes<HTMLTableRowElement>> = $props();
</script>
-<tr bind:this={ref} class={cn('hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors', className)} {...restProps}>
+<tr
+ bind:this={ref}
+ data-slot="table-row"
+ class={cn(
+ "hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
+ className
+ )}
+ {...restProps}
+>
{@render children?.()}
</tr>
diff --git a/frontend/src/lib/components/ui/table/table.svelte b/frontend/src/lib/components/ui/table/table.svelte
index fa6fe0cbe..a33495632 100644
--- a/frontend/src/lib/components/ui/table/table.svelte
+++ b/frontend/src/lib/components/ui/table/table.svelte
@@ -1,13 +1,22 @@
<script lang="ts">
- import type { HTMLTableAttributes } from 'svelte/elements';
- import type { WithElementRef } from '$lib/utils.js';
- import { cn } from '$lib/utils.js';
+ import type { HTMLTableAttributes } from "svelte/elements";
+ import { cn, type WithElementRef } from "$lib/utils.js";
- let { ref = $bindable(null), class: className, children, ...restProps }: WithElementRef<HTMLTableAttributes> = $props();
+ let {
+ ref = $bindable(null),
+ class: className,
+ children,
+ ...restProps
+ }: WithElementRef<HTMLTableAttributes> = $props();
</script>
-<div class="relative w-full overflow-auto">
- <table bind:this={ref} class={cn('w-full table-fixed caption-bottom text-sm', className)} {...restProps}>
+<div data-slot="table-container" class="relative w-full overflow-x-auto">
+ <table
+ bind:this={ref}
+ data-slot="table"
+ class={cn("w-full caption-bottom text-sm", className)}
+ {...restProps}
+ >
{@render children?.()}
</table>
</div>
diff --git a/frontend/src/lib/components/universal-table.svelte b/frontend/src/lib/components/universal-table.svelte
index c138b9ede..fd82e4443 100644
--- a/frontend/src/lib/components/universal-table.svelte
+++ b/frontend/src/lib/components/universal-table.svelte
@@ -1,412 +1,247 @@
<script lang="ts" generics="TData extends Record<string, any>">
- import {
- getCoreRowModel,
- getPaginationRowModel,
- getSortedRowModel,
- getFilteredRowModel,
- type SortingState,
- type ColumnFiltersState
- } from '@tanstack/table-core';
- import { createSvelteTable, FlexRender } from '$lib/components/ui/data-table/index.js';
- import * as Table from '$lib/components/ui/table/index.js';
+ import { Checkbox } from '$lib/components/ui/checkbox/index.js';
+ import { Input } from '$lib/components/ui/input/index.js';
import * as Pagination from '$lib/components/ui/pagination/index.js';
import * as Select from '$lib/components/ui/select/index.js';
- import { Input } from '$lib/components/ui/input/index.js';
+ import * as Table from '$lib/components/ui/table/index.js';
import { Button } from '$lib/components/ui/button/index.js';
- import { Checkbox } from '$lib/components/ui/checkbox/index.js';
import { ChevronDown } from '@lucide/svelte';
import { cn } from '$lib/utils';
import { debounced } from '$lib/utils';
- import type { UniversalTableProps } from '$lib/types/table-types';
import type { Snippet } from 'svelte';
+ import type { ExternalPagination } from '$lib/types/pagination.type';
- interface TableData extends Record<string, any> {
- isExternal?: boolean;
- }
-
- interface TableFeatures {
- sorting?: boolean;
- filtering?: boolean;
- selection?: boolean;
- }
-
- interface TableDisplay {
- pageSize?: number;
- pageSizeOptions?: number[];
- itemsPerPageLabel?: string;
- filterPlaceholder?: string;
- noResultsMessage?: string;
- isDashboardTable?: boolean;
- class?: string;
- }
-
- interface TablePagination {
- pageSize?: number;
- pageSizeOptions?: number[];
- itemsPerPageLabel?: string;
- }
-
- interface TableSort {
- defaultSort?: { id: string; desc: boolean };
- }
-
- // Props with better defaults and validation
let {
data,
+ externalPagination,
+ selectedIds = $bindable(),
+ withoutSearch = false,
+ selectionDisabled = false,
+ onRefresh,
+ onPageChange,
+ onPageSizeChange,
+ onSort,
columns,
- idKey,
- features = {},
- display = {},
- pagination = {},
- sort = {},
- selectedIds = $bindable<string[]>([]),
rows,
- onPageSizeChange = $bindable<((size: number) => void) | undefined>(undefined)
- }: UniversalTableProps<TData> & {
- idKey?: keyof TData;
- rows?: Snippet<[{ item: TData; index?: number }]>;
- onPageSizeChange?: ((size: number) => void) | undefined;
- } = $props();
-
- // Destructure with proper defaults
- const {
- sorting: enableSorting = true,
- filtering: enableFiltering = true,
- selection: enableSelection = true
- }: TableFeatures = features;
-
- const {
- pageSize: initialPageSize = 10,
- pageSizeOptions = [10, 20, 50, 100],
- itemsPerPageLabel = 'Items per page'
- }: TablePagination = pagination;
-
- const {
+ idKey = 'id',
filterPlaceholder = 'Search...',
noResultsMessage = 'No results found',
- isDashboardTable = false,
+ itemsPerPageLabel = 'Items per page',
class: className = ''
- }: TableDisplay = display;
-
- const { defaultSort }: TableSort = sort;
-
- // State management with better initialization
- let pageSize = $state(Math.max(1, initialPageSize));
- let pageIndex = $state(0);
- let currentPage = $state(1);
- let sorting = $state<SortingState>(defaultSort ? [defaultSort] : []);
- let columnFilters = $state<ColumnFiltersState>([]);
- let globalFilter = $state<string>('');
- let rowSelection = $state<Record<string, boolean>>({});
-
- // Optimized debounced filter function
- const debouncedFilter = debounced((value: string) => {
- table.setGlobalFilter(value);
- }, 300);
-
- // Effect for syncing external selectedIds with internal state
- $effect(() => {
- if (!enableSelection) return;
-
- const newSelection: Record<string, boolean> = {};
- selectedIds.forEach((id) => {
- if (id) newSelection[id] = true;
- });
+ }: {
+ data: TData[];
+ externalPagination?: ExternalPagination;
+ selectedIds?: string[];
+ withoutSearch?: boolean;
+ selectionDisabled?: boolean;
+ onRefresh?: () => Promise<void>;
+ onPageChange?: (page: number) => void;
+ onPageSizeChange?: (size: number) => void;
+ onSort?: (column: string, direction: 'asc' | 'desc') => void;
+ columns: { label: string; hidden?: boolean; sortColumn?: string }[];
+ rows: Snippet<[{ item: TData; index?: number }]>;
+ idKey?: string;
+ filterPlaceholder?: string;
+ noResultsMessage?: string;
+ itemsPerPageLabel?: string;
+ class?: string;
+ } = $props();
- const currentKeys = Object.keys(rowSelection)
- .filter((k) => rowSelection[k])
- .sort();
- const newKeys = Object.keys(newSelection).sort();
+ let searchValue = $state('');
+ let availablePageSizes: number[] = [10, 20, 50, 100];
+ let sortColumn = $state<string>('');
+ let sortDirection = $state<'asc' | 'desc'>('asc');
- if (JSON.stringify(currentKeys) !== JSON.stringify(newKeys)) {
- rowSelection = newSelection;
- }
- });
+ const isExternalPagination = $derived(!!externalPagination);
- // Effect for syncing page changes
- $effect(() => {
- const newPageIndex = Math.max(0, currentPage - 1);
- if (pageIndex !== newPageIndex) {
- pageIndex = newPageIndex;
+ let allChecked = $derived.by(() => {
+ if (!selectedIds || data.length === 0) return false;
+ for (const item of data) {
+ const itemId = String(item[idKey]);
+ if (!selectedIds.includes(itemId)) {
+ return false;
+ }
}
+ return true;
});
- // Effect for syncing table page state
- $effect(() => {
- const tablePageIndex = table.getState().pagination.pageIndex;
- const expectedCurrentPage = tablePageIndex + 1;
- if (currentPage !== expectedCurrentPage) {
- currentPage = expectedCurrentPage;
+ const onSearch = debounced(async (search: string) => {
+ searchValue = search;
+ if (onRefresh) {
+ await onRefresh();
}
- });
-
- // Create table instance
- const table = createSvelteTable({
- get data() {
- return data;
- },
- columns,
- getRowId: idKey ? (originalRow: TData) => String(originalRow[idKey]) : undefined,
- getCoreRowModel: getCoreRowModel(),
- ...(enableSorting && { getSortedRowModel: getSortedRowModel() }),
- ...(enableFiltering && { getFilteredRowModel: getFilteredRowModel() }),
- getPaginationRowModel: getPaginationRowModel(),
- enableRowSelection: enableSelection,
- state: {
- get pagination() {
- return { pageIndex, pageSize };
- },
- get sorting() {
- return sorting;
- },
- get columnFilters() {
- return columnFilters;
- },
- get globalFilter() {
- return globalFilter;
- },
- get rowSelection() {
- return rowSelection;
- }
- },
- onSortingChange: (updater) => {
- sorting = typeof updater === 'function' ? updater(sorting) : updater;
- },
- onColumnFiltersChange: (updater) => {
- columnFilters = typeof updater === 'function' ? updater(columnFilters) : updater;
- },
- onGlobalFilterChange: (value) => {
- globalFilter = value ?? '';
- pageIndex = 0;
- currentPage = 1;
- },
- onRowSelectionChange: (updater) => {
- if (!enableSelection) return;
-
- const newSelection = typeof updater === 'function' ? updater(rowSelection) : updater;
-
- if (JSON.stringify(newSelection) !== JSON.stringify(rowSelection)) {
- rowSelection = newSelection;
+ }, 300);
- // Update external selectedIds
- const newSelectedIds = Object.entries(newSelection)
- .filter(([_, selected]) => selected)
- .map(([id]) => id);
+ const filteredData = $derived(() => {
+ if (!searchValue || isExternalPagination) return data;
- if (JSON.stringify(selectedIds.sort()) !== JSON.stringify(newSelectedIds.sort())) {
- selectedIds = newSelectedIds;
- }
- }
- }
+ return data.filter((item) => {
+ return Object.values(item).some((value) =>
+ String(value).toLowerCase().includes(searchValue.toLowerCase())
+ );
+ });
});
- // Memoized computations
- const validPageSizeOptions = $derived(
- pageSizeOptions.filter((size) => size > 0).sort((a, b) => a - b)
- );
-
- const shouldShowPagination = $derived(
- !isDashboardTable && (table.getPageCount() > 1 || validPageSizeOptions.length > 1)
- );
-
- const shouldShowFiltering = $derived(enableFiltering && !isDashboardTable);
-
- const allRowsSelected = $derived(
- table.getIsAllPageRowsSelected() && table.getRowModel().rows.length > 0
- );
-
- const filteredRowCount = $derived(table.getFilteredRowModel().rows.length);
-
- // Event handlers
- function handleFilterChange(value: string) {
- debouncedFilter(value);
+ async function onAllCheck(checked: boolean) {
+ if (checked) {
+ selectedIds = data.map((item) => String(item[idKey]));
+ } else {
+ selectedIds = [];
+ }
}
- function handlePageSizeChange(size: string | number) {
- const sizeNumber = typeof size === 'string' ? parseInt(size, 10) : size;
-
- if (!isNaN(sizeNumber) && sizeNumber > 0) {
- pageSize = sizeNumber;
- table.setPageSize(sizeNumber);
- pageIndex = 0;
- currentPage = 1;
-
- onPageSizeChange?.(sizeNumber);
+ async function onCheck(checked: boolean, id: string) {
+ if (!selectedIds) return;
+ if (checked) {
+ selectedIds = [...selectedIds, id];
+ } else {
+ selectedIds = selectedIds.filter((selectedId) => selectedId !== id);
}
}
- function handleSelectAllChange(checked: boolean) {
- table.toggleAllPageRowsSelected(checked);
+ async function handlePageChange(page: number) {
+ onPageChange?.(page);
}
- function handleRowSelectionChange(row: any, checked: boolean) {
- const isDisabled = row.original?.isExternal ?? false;
- if (!isDisabled) {
- row.toggleSelected(checked);
- }
+ async function handlePageSizeChange(size: number) {
+ onPageSizeChange?.(size);
}
- function handleSortChange(header: any) {
- header.column.toggleSorting(header.column.getIsSorted() === 'asc');
+ async function handleSort(column?: string, direction: 'asc' | 'desc' = 'asc') {
+ if (!column) return;
+
+ sortColumn = column;
+ sortDirection = direction;
+ onSort?.(column, direction);
}
+
+ const currentPageSize = $derived(externalPagination?.pageSize || 10);
+
+ const currentPage = $derived(externalPagination?.currentPage || 1);
+
+ const totalItems = $derived(externalPagination?.totalItems || filteredData.length);
</script>
-<div class={cn('space-y-4', className, isDashboardTable && 'dashboard-table')}>
- <!-- Search Filter -->
- {#if shouldShowFiltering}
- <div class="flex items-center">
- <Input
- placeholder={filterPlaceholder}
- value={globalFilter}
- oninput={(e) => handleFilterChange(e.currentTarget.value)}
- class="max-w-sm"
- />
- </div>
+<div class={cn('space-y-4', className)}>
+ {#if !withoutSearch}
+ <Input
+ value={searchValue}
+ class={cn('relative z-50 max-w-sm', data.length == 0 && searchValue == '' && 'hidden')}
+ placeholder={filterPlaceholder}
+ type="text"
+ oninput={(e) => onSearch(e.currentTarget.value)}
+ />
{/if}
- <!-- Table -->
- <div class={cn('rounded-md border', isDashboardTable && 'rounded-none border-none')}>
- <Table.Root class="w-full table-auto">
- <Table.Header>
- {#each table.getHeaderGroups() as headerGroup (headerGroup.id)}
+ {#if data.length === 0 && searchValue === ''}
+ <div class="my-5 flex flex-col items-center">
+ <p class="text-muted-foreground mt-3 text-sm">{noResultsMessage}</p>
+ </div>
+ {:else}
+ <div class="rounded-md border">
+ <Table.Root class="min-w-full table-auto overflow-x-auto">
+ <Table.Header>
<Table.Row>
- {#if enableSelection}
+ {#if selectedIds !== undefined}
<Table.Head class="w-12">
<Checkbox
- checked={allRowsSelected}
- onCheckedChange={handleSelectAllChange}
- aria-label="Select all rows"
+ disabled={selectionDisabled}
+ checked={allChecked}
+ onCheckedChange={(c) => onAllCheck(c as boolean)}
/>
</Table.Head>
{/if}
- {#each headerGroup.headers as header, index (header.id)}
- <Table.Head class={cn(index === 0 ? '' : 'w-0 whitespace-nowrap', 'px-4')}>
- {#if !header.isPlaceholder}
- {#if header.column.getCanSort()}
- <Button
- variant="ghost"
- class="flex items-center p-0 hover:bg-transparent"
- onclick={() => handleSortChange(header)}
- aria-label="Sort by {header.column.columnDef.header}"
- >
- <FlexRender
- content={header.column.columnDef.header}
- context={header.getContext()}
+ {#each columns as column}
+ <Table.Head class={cn(column.hidden && 'sr-only', column.sortColumn && 'px-0')}>
+ {#if column.sortColumn}
+ <Button
+ variant="ghost"
+ class="flex items-center"
+ onclick={() =>
+ handleSort(
+ column.sortColumn,
+ sortColumn === column.sortColumn && sortDirection === 'asc' ? 'desc' : 'asc'
+ )}
+ >
+ {column.label}
+ {#if sortColumn === column.sortColumn}
+ <ChevronDown
+ class={cn('ml-2 size-4', sortDirection === 'asc' ? 'rotate-180' : '')}
/>
- {#if header.column.getIsSorted()}
- <ChevronDown
- class={cn(
- 'ml-2 size-4 transition-transform',
- header.column.getIsSorted() === 'asc' && 'rotate-180'
- )}
- />
- {/if}
- </Button>
- {:else}
- <FlexRender
- content={header.column.columnDef.header}
- context={header.getContext()}
- />
- {/if}
+ {/if}
+ </Button>
+ {:else}
+ {column.label}
{/if}
</Table.Head>
{/each}
</Table.Row>
- {/each}
- </Table.Header>
- <Table.Body>
- {#if table.getRowModel().rows.length > 0}
- {#each table.getRowModel().rows as row (row.id)}
- {@const isDisabled = row.original?.isExternal ?? false}
- <Table.Row data-state={row.getIsSelected() ? 'selected' : undefined}>
- {#if enableSelection}
+ </Table.Header>
+ <Table.Body>
+ {#each filteredData as item, index}
+ {@const itemId = String(item[idKey])}
+ <Table.Row class={selectedIds?.includes(itemId) ? 'bg-muted/20' : ''}>
+ {#if selectedIds !== undefined}
<Table.Cell class="w-12">
<Checkbox
- checked={row.getIsSelected()}
- disabled={isDisabled}
- onCheckedChange={(checked) => handleRowSelectionChange(row, !!checked)}
- aria-label="Select row"
+ disabled={selectionDisabled}
+ checked={selectedIds.includes(itemId)}
+ onCheckedChange={(c) => onCheck(c as boolean, itemId)}
/>
</Table.Cell>
{/if}
-
- {#if rows}
- {@render rows({ item: row.original, index: row.index })}
- {:else}
- {#each row.getVisibleCells() as cell, index (cell.id)}
- <Table.Cell class={cn(index === 0 ? '' : 'w-0 whitespace-nowrap', 'px-4')}>
- <FlexRender content={cell.column.columnDef.cell} context={cell.getContext()} />
- </Table.Cell>
- {/each}
- {/if}
+ {@render rows({ item, index })}
</Table.Row>
{/each}
- {:else}
- <Table.Row>
- <Table.Cell
- colspan={enableSelection ? columns.length + 1 : columns.length}
- class="size-24 text-center"
- >
- {noResultsMessage}
- </Table.Cell>
- </Table.Row>
- {/if}
- </Table.Body>
- </Table.Root>
- </div>
-
- <!-- Pagination Controls -->
- {#if shouldShowPagination}
- <div class="flex flex-col items-center justify-between gap-4 sm:flex-row">
- {#if validPageSizeOptions.length > 1}
- <div class="flex items-center gap-4">
- <span class="text-sm whitespace-nowrap">{itemsPerPageLabel}</span>
- <Select.Root
- type="single"
- value={pageSize.toString()}
- onValueChange={handlePageSizeChange}
- >
- <Select.Trigger class="h-8 w-[70px]" aria-label="Items per page">
- <span>{pageSize}</span>
- </Select.Trigger>
- <Select.Content>
- {#each validPageSizeOptions as size (size)}
- <Select.Item value={size.toString()}>
- {size}
- </Select.Item>
- {/each}
- </Select.Content>
- </Select.Root>
- </div>
- {/if}
+ </Table.Body>
+ </Table.Root>
+ </div>
- <div class="ml-auto">
- <Pagination.Root count={filteredRowCount} perPage={pageSize} bind:page={currentPage}>
- {#snippet children({ pages, currentPage: paginationCurrentPage })}
- <Pagination.Content>
- <Pagination.Item>
- <Pagination.PrevButton />
- </Pagination.Item>
- {#each pages as page (page.key)}
- {#if page.type === 'ellipsis'}
- <Pagination.Item>
- <Pagination.Ellipsis />
- </Pagination.Item>
- {:else}
- <Pagination.Item>
- <Pagination.Link {page} isActive={paginationCurrentPage === page.value}>
- {page.value}
- </Pagination.Link>
- </Pagination.Item>
- {/if}
- {/each}
- <Pagination.Item>
- <Pagination.NextButton />
- </Pagination.Item>
- </Pagination.Content>
- {/snippet}
- </Pagination.Root>
+ <div class="mt-5 flex flex-col-reverse items-center justify-between gap-3 sm:flex-row">
+ <div class="flex items-center space-x-2">
+ <p class="text-sm font-medium">{itemsPerPageLabel}</p>
+ <Select.Root
+ type="single"
+ value={currentPageSize.toString()}
+ onValueChange={(v) => handlePageSizeChange(Number(v))}
+ >
+ <Select.Trigger class="h-9 w-[80px]">
+ {currentPageSize}
+ </Select.Trigger>
+ <Select.Content>
+ {#each availablePageSizes as size}
+ <Select.Item value={size.toString()}>{size}</Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
</div>
+ <Pagination.Root
+ class="mx-0 w-auto"
+ count={totalItems}
+ perPage={currentPageSize}
+ onPageChange={handlePageChange}
+ page={currentPage}
+ >
+ {#snippet children({ pages })}
+ <Pagination.Content class="flex justify-end">
+ <Pagination.Item>
+ <Pagination.PrevButton />
+ </Pagination.Item>
+ {#each pages as page (page.key)}
+ {#if page.type !== 'ellipsis' && page.value != 0}
+ <Pagination.Item>
+ <Pagination.Link {page} isActive={currentPage === page.value}>
+ {page.value}
+ </Pagination.Link>
+ </Pagination.Item>
+ {/if}
+ {/each}
+ <Pagination.Item>
+ <Pagination.NextButton />
+ </Pagination.Item>
+ </Pagination.Content>
+ {/snippet}
+ </Pagination.Root>
</div>
{/if}
</div>
diff --git a/frontend/src/lib/models/container-registry.ts b/frontend/src/lib/models/container-registry.ts
index 95e3dcbb4..62a6af472 100644
--- a/frontend/src/lib/models/container-registry.ts
+++ b/frontend/src/lib/models/container-registry.ts
@@ -1,11 +1,11 @@
export interface ContainerRegistry {
- id?: string;
- url: string;
- username: string;
- token: string;
- description?: string;
- insecure?: boolean;
- enabled?: boolean;
- createdAt?: string;
- updatedAt?: string;
+ id: string;
+ url: string;
+ username: string;
+ token: string;
+ description?: string;
+ insecure?: boolean;
+ enabled?: boolean;
+ createdAt?: string;
+ updatedAt?: string;
}
diff --git a/frontend/src/lib/models/docker-info.type.ts b/frontend/src/lib/models/docker-info.type.ts
new file mode 100644
index 000000000..eb2a799ed
--- /dev/null
+++ b/frontend/src/lib/models/docker-info.type.ts
@@ -0,0 +1,26 @@
+export interface DockerInfo {
+ success: boolean;
+ version: string;
+ apiVersion: string;
+ gitCommit: string;
+ goVersion: string;
+ os: string;
+ arch: string;
+ buildTime: string;
+ containers: number;
+ containersRunning: number;
+ containersPaused: number;
+ containersStopped: number;
+ images: number;
+ storageDriver: string;
+ loggingDriver: string;
+ cgroupDriver: string;
+ cgroupVersion: string;
+ kernelVersion: string;
+ operatingSystem: string;
+ osVersion: string;
+ serverVersion: string;
+ architecture: string;
+ cpus: number;
+ memTotal: number;
+}
\ No newline at end of file
diff --git a/frontend/src/lib/services/api/api-service.ts b/frontend/src/lib/services/api/api-service.ts
index abcdd71e1..ec870d52c 100644
--- a/frontend/src/lib/services/api/api-service.ts
+++ b/frontend/src/lib/services/api/api-service.ts
@@ -42,7 +42,7 @@ abstract class BaseAPIService {
const response = await promise;
- const extractedData = response.data?.data || response.data?.result || response.data;
+ const extractedData = response.data || response.data.data;
return extractedData;
}
diff --git a/frontend/src/lib/services/api/container-registry-api-service.ts b/frontend/src/lib/services/api/container-registry-api-service.ts
index e43db8a77..0bc48a72e 100644
--- a/frontend/src/lib/services/api/container-registry-api-service.ts
+++ b/frontend/src/lib/services/api/container-registry-api-service.ts
@@ -1,29 +1,63 @@
import BaseAPIService from './api-service';
import type { ContainerRegistryCreateDto, ContainerRegistryUpdateDto } from '$lib/dto/container-registry-dto';
import type { ContainerRegistry } from '$lib/models/container-registry';
+import type { PaginationRequest, SortRequest, Paginated } from '$lib/types/pagination.type';
export default class ContainerRegistryAPIService extends BaseAPIService {
- async getAllRegistries(): Promise<ContainerRegistry[]> {
- return this.handleResponse(this.api.get(`/container-registries`));
- }
+ async getRegistries(
+ pagination?: PaginationRequest,
+ sort?: SortRequest,
+ search?: string,
+ filters?: Record<string, string>
+ ): Promise<ContainerRegistry[] | Paginated<ContainerRegistry>> {
+ if (!pagination) {
+ return this.handleResponse(this.api.get(`/container-registries`));
+ }
- async getRegistry(id: string): Promise<ContainerRegistry> {
- return this.handleResponse(this.api.get(`/container-registries/${id}`));
- }
+ const params: any = {
+ 'pagination[page]': pagination.page,
+ 'pagination[limit]': pagination.limit
+ };
- async createRegistry(registry: ContainerRegistryCreateDto): Promise<ContainerRegistry> {
- return this.handleResponse(this.api.post(`/container-registries`, registry));
- }
+ if (sort) {
+ params['sort[column]'] = sort.column;
+ params['sort[direction]'] = sort.direction;
+ }
- async updateRegistry(id: string, registry: ContainerRegistryUpdateDto): Promise<ContainerRegistry> {
- return this.handleResponse(this.api.put(`/container-registries/${id}`, registry));
- }
+ if (search) {
+ params.search = search;
+ }
- async deleteRegistry(id: string): Promise<void> {
- return this.handleResponse(this.api.delete(`/container-registries/${id}`));
- }
+ if (filters) {
+ Object.entries(filters).forEach(([key, value]) => {
+ params[key] = value;
+ });
+ }
- async testRegistry(id: string): Promise<any> {
- return this.handleResponse(this.api.post(`/container-registries/${id}/test`));
- }
+ return this.handleResponse(this.api.get(`/container-registries`, { params }));
+ }
+
+ async getAllRegistries(): Promise<ContainerRegistry[]> {
+ return this.handleResponse(this.api.get(`/container-registries`));
+ }
+
+ async getRegistry(id: string): Promise<ContainerRegistry> {
+ return this.handleResponse(this.api.get(`/container-registries/${id}`));
+ }
+
+ async createRegistry(registry: ContainerRegistryCreateDto): Promise<ContainerRegistry> {
+ return this.handleResponse(this.api.post(`/container-registries`, registry));
+ }
+
+ async updateRegistry(id: string, registry: ContainerRegistryUpdateDto): Promise<ContainerRegistry> {
+ return this.handleResponse(this.api.put(`/container-registries/${id}`, registry));
+ }
+
+ async deleteRegistry(id: string): Promise<void> {
+ return this.handleResponse(this.api.delete(`/container-registries/${id}`));
+ }
+
+ async testRegistry(id: string): Promise<any> {
+ return this.handleResponse(this.api.post(`/container-registries/${id}/test`));
+ }
}
diff --git a/frontend/src/lib/services/api/environment-api-service.ts b/frontend/src/lib/services/api/environment-api-service.ts
index ad94e5e4d..a75c1997f 100644
--- a/frontend/src/lib/services/api/environment-api-service.ts
+++ b/frontend/src/lib/services/api/environment-api-service.ts
@@ -3,315 +3,494 @@ import { get } from 'svelte/store';
import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '$lib/stores/environment.store';
import type { ContainerCreateOptions, NetworkCreateOptions, VolumeCreateOptions, ContainerStats } from 'dockerode';
import type { Stack, StackService } from '$lib/models/stack.type';
-
+import type { PaginationRequest, SortRequest, PaginatedApiResponse } from '$lib/types/pagination.type';
import { browser } from '$app/environment';
+import type { EnhancedImageInfo } from '$lib/models/image.type';
+import type { EnhancedContainerInfo } from '$lib/models/container-info';
export class EnvironmentAPIService extends BaseAPIService {
- private async getCurrentEnvironmentId(): Promise<string> {
- if (browser) {
- await environmentStore.ready;
- }
- const currentEnvironment = get(environmentStore.selected);
- if (!currentEnvironment) {
- return LOCAL_DOCKER_ENVIRONMENT_ID;
- }
- return currentEnvironment.id;
- }
-
- async getContainers(): Promise<any[]> {
- const envId = await this.getCurrentEnvironmentId();
- const response = await this.handleResponse<{ containers?: any[] }>(this.api.get(`/environments/${envId}/containers`));
- return Array.isArray(response.containers) ? response.containers : Array.isArray(response) ? response : [];
- }
-
- async getContainer(containerId: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/containers/${containerId}`));
- }
-
- async startContainer(containerId: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/start`));
- }
-
- async createContainer(options: ContainerCreateOptions): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/containers`, options));
- }
-
- async getContainerStats(containerId: string, stream: boolean = false): Promise<ContainerStats> {
- const envId = await this.getCurrentEnvironmentId();
- const url = `/environments/${envId}/containers/${containerId}/stats${stream ? '?stream=true' : ''}`;
- return this.handleResponse(this.api.get(url)) as Promise<ContainerStats>;
- }
-
- async stopContainer(containerId: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/stop`));
- }
-
- async restartContainer(containerId: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/restart`));
- }
-
- async deleteContainer(containerId: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.delete(`/environments/${envId}/containers/${containerId}`));
- }
-
- async pullContainerImage(containerId: string): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/pull`));
- }
-
- async getImages(): Promise<any[]> {
- const envId = await this.getCurrentEnvironmentId();
- const response = await this.handleResponse<{ images?: any[] }>(this.api.get(`/environments/${envId}/images`));
- return Array.isArray(response.images) ? response.images : Array.isArray(response) ? response : [];
- }
-
- async getImage(imageId: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/images/${imageId}`));
- }
-
- async getNetworks(): Promise<any[]> {
- const envId = await this.getCurrentEnvironmentId();
- const response = await this.handleResponse<{ networks?: any[] }>(this.api.get(`/environments/${envId}/networks`));
- return Array.isArray(response.networks) ? response.networks : Array.isArray(response) ? response : [];
- }
-
- async getNetwork(networkId: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/networks/${networkId}`));
- }
-
- async createNetwork(options: NetworkCreateOptions): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/networks`, options));
- }
-
- async deleteNetwork(networkId: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.delete(`/environments/${envId}/networks/${networkId}`));
- }
-
- async getVolumes(): Promise<any[]> {
- const envId = await this.getCurrentEnvironmentId();
- const response = await this.handleResponse<{ volumes?: any[] }>(this.api.get(`/environments/${envId}/volumes`));
- return Array.isArray(response.volumes) ? response.volumes : Array.isArray(response) ? response : [];
- }
-
- async getVolume(volumeName: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}`));
- }
-
- async getVolumeUsage(volumeName: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}/usage`));
- }
-
- async createVolume(options: VolumeCreateOptions): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/volumes`, options));
- }
-
- async deleteVolume(volumeName: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.delete(`/environments/${envId}/volumes/${volumeName}`));
- }
-
- async pruneVolumes(): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/volumes/prune`));
- }
-
- async getAllResources(): Promise<Record<string, any>> {
- const [containers, images, networks, volumes] = await Promise.all([this.getContainers(), this.getImages(), this.getNetworks(), this.getVolumes()]);
-
- return {
- containers,
- images,
- networks,
- volumes
- };
- }
-
- async syncResources(): Promise<void> {
- const envId = await this.getCurrentEnvironmentId();
- await this.handleResponse(this.api.post(`/environments/${envId}/sync`));
- }
-
- async executeDockerCommand(command: string, args: string[] = []): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/execute`, { command, args }));
- }
-
- async getStacks(): Promise<Stack[]> {
- const envId = await this.getCurrentEnvironmentId();
- const response = await this.handleResponse<{ stacks?: Stack[] }>(this.api.get(`/environments/${envId}/stacks`));
- return Array.isArray(response.stacks) ? response.stacks : Array.isArray(response) ? response : [];
- }
-
- async getStack(stackName: string): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- const response = await this.handleResponse<{ stack?: Stack; success?: boolean }>(this.api.get(`/environments/${envId}/stacks/${stackName}`));
-
- if (response.stack) {
- return response.stack;
- }
-
- return response as Stack;
- }
-
- async deployStack(stackName: string, composeContent: string, envContent?: string): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- const payload = {
- name: stackName,
- composeContent,
- envContent
- };
- return this.handleResponse(this.api.post(`/environments/${envId}/stacks`, payload));
- }
-
- async updateStack(stackName: string, composeContent: string, envContent?: string): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- const payload = {
- composeContent,
- envContent
- };
- return this.handleResponse(this.api.put(`/environments/${envId}/stacks/${stackName}`, payload));
- }
-
- async deleteStack(stackName: string): Promise<void> {
- const envId = await this.getCurrentEnvironmentId();
- await this.handleResponse(this.api.delete(`/environments/${envId}/stacks/${stackName}`));
- }
-
- async startStack(stackId: string): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/start`));
- }
-
- async stopStack(stackId: string): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/stop`));
- }
-
- async restartStack(stackId: string): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/restart`));
- }
-
- async getStackLogs(stackId: string): Promise<string> {
- const envId = await this.getCurrentEnvironmentId();
- const response = await this.handleResponse<{ logs?: string }>(this.api.get(`/environments/${envId}/stacks/${stackId}/logs`));
- return response.logs || '';
- }
-
- async deployStackWithOptions(stackId: string, options?: { profiles?: string[]; envOverrides?: Record<string, string> }): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/deploy`, options || {}));
- }
-
- async downStack(stackId: string): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/down`));
- }
-
- async redeployStack(stackId: string): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/redeploy`));
- }
-
- async pullStackImages(stackId: string): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/pull`));
- }
-
- async destroyStack(stackId: string, removeVolumes = false, removeFiles = false): Promise<void> {
- const envId = await this.getCurrentEnvironmentId();
- await this.handleResponse(
- this.api.delete(`/environments/${envId}/stacks/${stackId}/destroy`, {
- data: {
- removeVolumes,
- removeFiles
- }
- })
- );
- }
-
- async getStackServices(stackName: string): Promise<StackService[]> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/services`));
- }
-
- async getStackProfiles(stackName: string): Promise<string[]> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/profiles`));
- }
-
- async getStackChanges(stackName: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/changes`));
- }
-
- async getStackStats(stackName: string): Promise<ContainerStats[]> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/stats`)) as Promise<ContainerStats[]>;
- }
-
- async validateStack(stackName: string): Promise<{ valid: boolean; errors?: string[] }> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/validate`));
- }
-
- async convertDockerRun(command: string): Promise<{ composeContent: string }> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/stacks/convert`, { command }));
- }
-
- async discoverExternalStacks(): Promise<Stack[]> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/stacks/discover-external`));
- }
-
- async importStack(stackId: string, stackName?: string): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(
- this.api.post(`/environments/${envId}/stacks/import`, {
- stackId,
- stackName
- })
- );
- }
-
- async migrateStack(stackName: string): Promise<Stack> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackName}/migrate`));
- }
-
- async getStackLogsStream(stackName: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/logs/stream`));
- }
-
- async pullImage(imageName: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/images/pull`, { imageName }));
- }
-
- async deleteImage(imageId: string, options?: { force?: boolean; noprune?: boolean }): Promise<void> {
- const envId = await this.getCurrentEnvironmentId();
- await this.handleResponse(this.api.delete(`/environments/${envId}/images/${imageId}`, { params: options }));
- }
-
- async pruneImages(): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/images/prune`));
- }
+ private async getCurrentEnvironmentId(): Promise<string> {
+ if (browser) {
+ await environmentStore.ready;
+ }
+ const currentEnvironment = get(environmentStore.selected);
+ if (!currentEnvironment) {
+ return LOCAL_DOCKER_ENVIRONMENT_ID;
+ }
+ return currentEnvironment.id;
+ }
+
+ async getContainers(
+ pagination?: PaginationRequest,
+ sort?: SortRequest,
+ search?: string,
+ filters?: Record<string, string>
+ ): Promise<any[] | PaginatedApiResponse<any>> {
+ const envId = await this.getCurrentEnvironmentId();
+
+ if (!pagination) {
+ const response = await this.handleResponse<{ containers?: EnhancedContainerInfo[] }>(this.api.get(`/environments/${envId}/containers`));
+ return Array.isArray(response.containers) ? response.containers : Array.isArray(response) ? response : [];
+ }
+
+ const params: any = {
+ 'pagination[page]': pagination.page,
+ 'pagination[limit]': pagination.limit
+ };
+
+ if (sort) {
+ params['sort[column]'] = sort.column;
+ params['sort[direction]'] = sort.direction;
+ }
+
+ if (search) {
+ params.search = search;
+ }
+
+ if (filters) {
+ Object.entries(filters).forEach(([key, value]) => {
+ params[key] = value;
+ });
+ }
+
+ return this.handleResponse(this.api.get(`/environments/${envId}/containers`, { params }));
+ }
+
+ async getContainer(containerId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/containers/${containerId}`));
+ }
+
+ async startContainer(containerId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/start`));
+ }
+
+ async createContainer(options: ContainerCreateOptions): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/containers`, options));
+ }
+
+ async getContainerStats(containerId: string, stream: boolean = false): Promise<ContainerStats> {
+ const envId = await this.getCurrentEnvironmentId();
+ const url = `/environments/${envId}/containers/${containerId}/stats${stream ? '?stream=true' : ''}`;
+ return this.handleResponse(this.api.get(url)) as Promise<ContainerStats>;
+ }
+
+ async stopContainer(containerId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/stop`));
+ }
+
+ async restartContainer(containerId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/restart`));
+ }
+
+ async deleteContainer(containerId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.delete(`/environments/${envId}/containers/${containerId}`));
+ }
+
+ async pullContainerImage(containerId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/pull`));
+ }
+
+ async getImages(
+ pagination?: PaginationRequest,
+ sort?: SortRequest,
+ search?: string,
+ filters?: Record<string, string>
+ ): Promise<any[] | PaginatedApiResponse<any>> {
+ const envId = await this.getCurrentEnvironmentId();
+
+ if (!pagination) {
+ const response = await this.handleResponse<{ images?: EnhancedImageInfo[] }>(this.api.get(`/environments/${envId}/images`));
+ return Array.isArray(response.images) ? response.images : Array.isArray(response) ? response : [];
+ }
+
+ const params: any = {
+ 'pagination[page]': pagination.page,
+ 'pagination[limit]': pagination.limit
+ };
+
+ if (sort) {
+ params['sort[column]'] = sort.column;
+ params['sort[direction]'] = sort.direction;
+ }
+
+ if (search) {
+ params.search = search;
+ }
+
+ if (filters) {
+ params.filters = filters;
+ }
+
+ return this.handleResponse(this.api.get(`/environments/${envId}/images`, { params }));
+ }
+
+ async getImage(imageId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/images/${imageId}`));
+ }
+
+ async pullImage(imageName: string, tag: string = 'latest', auth?: any): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/images/pull`, { imageName, tag, auth }));
+ }
+
+ async deleteImage(imageId: string, options?: { force?: boolean; noprune?: boolean }): Promise<void> {
+ const envId = await this.getCurrentEnvironmentId();
+ await this.handleResponse(this.api.delete(`/environments/${envId}/images/${imageId}`, { params: options }));
+ }
+
+ async pruneImages(filters?: Record<string, string>): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/images/prune`, { filters }));
+ }
+
+ async inspectImage(imageId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/images/${imageId}/inspect`));
+ }
+
+ async searchImages(term: string, limit?: number): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/images/search`, { params: { term, limit } }));
+ }
+
+ async tagImage(imageId: string, repo: string, tag: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/images/${imageId}/tag`, { repo, tag }));
+ }
+
+ async getImageHistory(imageId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/images/${imageId}/history`));
+ }
+
+ async getNetworks(
+ pagination?: PaginationRequest,
+ sort?: SortRequest,
+ search?: string,
+ filters?: Record<string, string>
+ ): Promise<any[] | PaginatedApiResponse<any>> {
+ const envId = await this.getCurrentEnvironmentId();
+
+ if (!pagination) {
+ const response = await this.handleResponse<{ networks?: any[] }>(this.api.get(`/environments/${envId}/networks`));
+ return Array.isArray(response.networks) ? response.networks : Array.isArray(response) ? response : [];
+ }
+
+ const params: any = {
+ 'pagination[page]': pagination.page,
+ 'pagination[limit]': pagination.limit
+ };
+
+ if (sort) {
+ params['sort[column]'] = sort.column;
+ params['sort[direction]'] = sort.direction;
+ }
+
+ if (search) {
+ params.search = search;
+ }
+
+ if (filters) {
+ Object.entries(filters).forEach(([key, value]) => {
+ params[key] = value;
+ });
+ }
+
+ return this.handleResponse(this.api.get(`/environments/${envId}/networks`, { params }));
+ }
+
+ async getNetwork(networkId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/networks/${networkId}`));
+ }
+
+ async createNetwork(options: NetworkCreateOptions): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/networks`, options));
+ }
+
+ async deleteNetwork(networkId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.delete(`/environments/${envId}/networks/${networkId}`));
+ }
+
+ async getVolumes(
+ pagination?: PaginationRequest,
+ sort?: SortRequest,
+ search?: string,
+ filters?: Record<string, string>
+ ): Promise<any[] | PaginatedApiResponse<any>> {
+ const envId = await this.getCurrentEnvironmentId();
+
+ if (!pagination) {
+ const response = await this.handleResponse<{ volumes?: any[] }>(this.api.get(`/environments/${envId}/volumes`));
+ return Array.isArray(response.volumes) ? response.volumes : Array.isArray(response) ? response : [];
+ }
+
+ const params: any = {
+ 'pagination[page]': pagination.page,
+ 'pagination[limit]': pagination.limit
+ };
+
+ if (sort) {
+ params['sort[column]'] = sort.column;
+ params['sort[direction]'] = sort.direction;
+ }
+
+ if (search) {
+ params.search = search;
+ }
+
+ if (filters) {
+ Object.entries(filters).forEach(([key, value]) => {
+ params[key] = value;
+ });
+ }
+
+ return this.handleResponse(this.api.get(`/environments/${envId}/volumes`, { params }));
+ }
+
+ async getVolume(volumeName: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}`));
+ }
+
+ async getVolumeUsage(volumeName: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}/usage`));
+ }
+
+ async createVolume(options: VolumeCreateOptions): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/volumes`, options));
+ }
+
+ async deleteVolume(volumeName: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.delete(`/environments/${envId}/volumes/${volumeName}`));
+ }
+
+ async pruneVolumes(): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/volumes/prune`));
+ }
+
+ async getAllResources(): Promise<Record<string, any>> {
+ const [containers, images, networks, volumes] = await Promise.all([this.getContainers(), this.getImages(), this.getNetworks(), this.getVolumes()]);
+
+ return {
+ containers,
+ images,
+ networks,
+ volumes
+ };
+ }
+
+ async syncResources(): Promise<void> {
+ const envId = await this.getCurrentEnvironmentId();
+ await this.handleResponse(this.api.post(`/environments/${envId}/sync`));
+ }
+
+ async executeDockerCommand(command: string, args: string[] = []): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/execute`, { command, args }));
+ }
+
+ async getStacks(
+ pagination?: PaginationRequest,
+ sort?: SortRequest,
+ search?: string,
+ filters?: Record<string, string>
+ ): Promise<any[] | PaginatedApiResponse<any>> {
+ const envId = await this.getCurrentEnvironmentId();
+
+ if (!pagination) {
+ const response = await this.handleResponse<{ stacks?: Stack[] }>(this.api.get(`/environments/${envId}/stacks`));
+ return Array.isArray(response.stacks) ? response.stacks : Array.isArray(response) ? response : [];
+ }
+
+ const params: any = {
+ 'pagination[page]': pagination.page,
+ 'pagination[limit]': pagination.limit
+ };
+
+ if (sort) {
+ params['sort[column]'] = sort.column;
+ params['sort[direction]'] = sort.direction;
+ }
+
+ if (search) {
+ params.search = search;
+ }
+
+ if (filters) {
+ params.filters = filters;
+ }
+
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks`, { params }));
+ }
+
+ async getStack(stackName: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ const response = await this.handleResponse<{ stack?: Stack; success?: boolean }>(this.api.get(`/environments/${envId}/stacks/${stackName}`));
+
+ if (response.stack) {
+ return response.stack;
+ }
+
+ return response as Stack;
+ }
+
+ async deployStack(stackName: string, composeContent: string, envContent?: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ const payload = {
+ name: stackName,
+ composeContent,
+ envContent
+ };
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks`, payload));
+ }
+
+ async updateStack(stackName: string, composeContent: string, envContent?: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ const payload = {
+ composeContent,
+ envContent
+ };
+ return this.handleResponse(this.api.put(`/environments/${envId}/stacks/${stackName}`, payload));
+ }
+
+ async deleteStack(stackName: string): Promise<void> {
+ const envId = await this.getCurrentEnvironmentId();
+ await this.handleResponse(this.api.delete(`/environments/${envId}/stacks/${stackName}`));
+ }
+
+ async startStack(stackId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/start`));
+ }
+
+ async stopStack(stackId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/stop`));
+ }
+
+ async restartStack(stackId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/restart`));
+ }
+
+ async getStackLogs(stackId: string): Promise<string> {
+ const envId = await this.getCurrentEnvironmentId();
+ const response = await this.handleResponse<{ logs?: string }>(this.api.get(`/environments/${envId}/stacks/${stackId}/logs`));
+ return response.logs || '';
+ }
+
+ async deployStackWithOptions(stackId: string, options?: { profiles?: string[]; envOverrides?: Record<string, string> }): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/deploy`, options || {}));
+ }
+
+ async downStack(stackId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/down`));
+ }
+
+ async redeployStack(stackId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/redeploy`));
+ }
+
+ async pullStackImages(stackId: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackId}/pull`));
+ }
+
+ async destroyStack(stackId: string, removeVolumes = false, removeFiles = false): Promise<void> {
+ const envId = await this.getCurrentEnvironmentId();
+ await this.handleResponse(
+ this.api.delete(`/environments/${envId}/stacks/${stackId}/destroy`, {
+ data: {
+ removeVolumes,
+ removeFiles
+ }
+ })
+ );
+ }
+
+ async getStackServices(stackName: string): Promise<StackService[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/services`));
+ }
+
+ async getStackProfiles(stackName: string): Promise<string[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/profiles`));
+ }
+
+ async getStackChanges(stackName: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/changes`));
+ }
+
+ async getStackStats(stackName: string): Promise<ContainerStats[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/stats`)) as Promise<ContainerStats[]>;
+ }
+
+ async validateStack(stackName: string): Promise<{ valid: boolean; errors?: string[] }> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/validate`));
+ }
+
+ async convertDockerRun(command: string): Promise<{ composeContent: string }> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/convert`, { command }));
+ }
+
+ async discoverExternalStacks(): Promise<Stack[]> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/discover-external`));
+ }
+
+ async importStack(stackId: string, stackName?: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(
+ this.api.post(`/environments/${envId}/stacks/import`, {
+ stackId,
+ stackName
+ })
+ );
+ }
+
+ async migrateStack(stackName: string): Promise<Stack> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/stacks/${stackName}/migrate`));
+ }
+
+ async getStackLogsStream(stackName: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/stacks/${stackName}/logs/stream`));
+ }
+
+ async getImageMaturity(imageId: string): Promise<any> {
+ const envId = await this.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/images/${imageId}/maturity`));
+ }
+
+ async triggerMaturityCheck(imageIds?: string[]): Promise<{ success: boolean; message: string }> {
+ const envId = await this.getCurrentEnvironmentId();
+ const payload = imageIds && imageIds.length > 0 ? { imageIds } : {};
+ return this.handleResponse(this.api.post(`/environments/${envId}/images/maturity/check`, payload));
+ }
}
export const environmentAPI = new EnvironmentAPIService();
diff --git a/frontend/src/lib/services/api/image-api-service.ts b/frontend/src/lib/services/api/image-api-service.ts
index 0228eb45c..aeb745475 100644
--- a/frontend/src/lib/services/api/image-api-service.ts
+++ b/frontend/src/lib/services/api/image-api-service.ts
@@ -1,164 +1,186 @@
import BaseAPIService from './api-service';
+import type { PaginationRequest, SortRequest, PaginatedApiResponse } from '$lib/types/pagination.type';
export default class ImageAPIService extends BaseAPIService {
- async list(filters?: Record<string, string>) {
- return this.handleResponse(this.api.get('/images', { params: { filters } }));
- }
-
- async get(id: string) {
- return this.handleResponse(this.api.get(`/images/${id}`));
- }
-
- async inspect(id: string) {
- return this.handleResponse(this.api.get(`/images/${id}/inspect`));
- }
-
- async search(term: string, limit?: number) {
- return this.handleResponse(
- this.api.get('/images/search', {
- params: { term, limit }
- })
- );
- }
-
- async pull(imageName: string, tag: string = 'latest', auth?: any) {
- return this.handleResponse(
- this.api.post('/images/pull', {
- imageName,
- tag,
- auth
- })
- );
- }
-
- async push(imageName: string, tag: string = 'latest', auth?: any) {
- return this.handleResponse(
- this.api.post('/images/push', {
- imageName,
- tag,
- auth
- })
- );
- }
-
- async remove(id: string, options?: { force?: boolean; noprune?: boolean }) {
- return this.handleResponse(
- this.api.delete(`/images/${id}`, {
- params: options
- })
- );
- }
-
- async tag(id: string, repo: string, tag: string) {
- return this.handleResponse(
- this.api.post(`/images/${id}/tag`, {
- repo,
- tag
- })
- );
- }
-
- async history(id: string) {
- return this.handleResponse(this.api.get(`/images/${id}/history`));
- }
-
- async prune(filters?: Record<string, string>) {
- return this.handleResponse(this.api.post('/images/prune', { filters }));
- }
-
- async build(
- context: FormData,
- options?: {
- dockerfile?: string;
- tags?: string[];
- buildArgs?: Record<string, string>;
- target?: string;
- networkMode?: string;
- platform?: string;
- }
- ) {
- return this.handleResponse(
- this.api.post('/images/build', context, {
- headers: {
- 'Content-Type': 'multipart/form-data'
- },
- params: options
- })
- );
- }
-
- async export(ids: string[]) {
- const response = await this.api.post(
- '/images/export',
- { ids },
- {
- responseType: 'blob'
- }
- );
- return response.data;
- }
-
- async import(source: File | string, repo?: string, tag?: string) {
- const formData = new FormData();
- if (source instanceof File) {
- formData.append('file', source);
- } else {
- formData.append('url', source);
- }
- if (repo) formData.append('repo', repo);
- if (tag) formData.append('tag', tag);
-
- return this.handleResponse(
- this.api.post('/images/import', formData, {
- headers: {
- 'Content-Type': 'multipart/form-data'
- }
- })
- );
- }
-
- async commit(
- containerId: string,
- options?: {
- repo?: string;
- tag?: string;
- comment?: string;
- author?: string;
- pause?: boolean;
- changes?: string[];
- }
- ) {
- return this.handleResponse(
- this.api.post('/images/commit', {
- containerId,
- ...options
- })
- );
- }
-
- async checkMaturity(imageId: string) {
- return this.handleResponse(this.api.get(`/images/maturity/${imageId}`));
- }
-
- async checkMaturityBatch(imageIds: string[]) {
- // Use the first image ID for the endpoint URL since the backend expects it
- if (!imageIds || imageIds.length === 0) {
- throw new Error('No image IDs provided for batch check');
- }
-
- const firstId = imageIds[0];
- return this.handleResponse(this.api.post(`/images/${firstId}/maturity`, { imageIds }));
- }
-
- async updateMaturity(imageId: string, maturityData: any) {
- return this.handleResponse(this.api.put(`/images/maturity/${imageId}`, maturityData));
- }
-
- async getVulnerabilities(imageId: string) {
- return this.handleResponse(this.api.get(`/images/${imageId}/vulnerabilities`));
- }
-
- async scanImage(imageId: string) {
- return this.handleResponse(this.api.post(`/images/${imageId}/scan`));
- }
+ async list(filters?: Record<string, string>) {
+ return this.handleResponse(this.api.get('/images', { params: { filters } }));
+ }
+
+ async listPaginated(
+ pagination: PaginationRequest,
+ sort?: SortRequest,
+ filters?: Record<string, string>
+ ): Promise<PaginatedApiResponse<any>> {
+ const params: any = {
+ page: pagination.page,
+ limit: pagination.limit
+ };
+
+ if (sort) {
+ params.column = sort.column;
+ params.direction = sort.direction;
+ }
+
+ if (filters) {
+ params.filters = filters;
+ }
+
+ return this.handleResponse(this.api.get('/images', { params }));
+ }
+
+ async get(id: string) {
+ return this.handleResponse(this.api.get(`/images/${id}`));
+ }
+
+ async inspect(id: string) {
+ return this.handleResponse(this.api.get(`/images/${id}/inspect`));
+ }
+
+ async search(term: string, limit?: number) {
+ return this.handleResponse(
+ this.api.get('/images/search', {
+ params: { term, limit }
+ })
+ );
+ }
+
+ async pull(imageName: string, tag: string = 'latest', auth?: any) {
+ return this.handleResponse(
+ this.api.post('/images/pull', {
+ imageName,
+ tag,
+ auth
+ })
+ );
+ }
+
+ async push(imageName: string, tag: string = 'latest', auth?: any) {
+ return this.handleResponse(
+ this.api.post('/images/push', {
+ imageName,
+ tag,
+ auth
+ })
+ );
+ }
+
+ async remove(id: string, options?: { force?: boolean; noprune?: boolean }) {
+ return this.handleResponse(
+ this.api.delete(`/images/${id}`, {
+ params: options
+ })
+ );
+ }
+
+ async tag(id: string, repo: string, tag: string) {
+ return this.handleResponse(
+ this.api.post(`/images/${id}/tag`, {
+ repo,
+ tag
+ })
+ );
+ }
+
+ async history(id: string) {
+ return this.handleResponse(this.api.get(`/images/${id}/history`));
+ }
+
+ async prune(filters?: Record<string, string>) {
+ return this.handleResponse(this.api.post('/images/prune', { filters }));
+ }
+
+ async build(
+ context: FormData,
+ options?: {
+ dockerfile?: string;
+ tags?: string[];
+ buildArgs?: Record<string, string>;
+ target?: string;
+ networkMode?: string;
+ platform?: string;
+ }
+ ) {
+ return this.handleResponse(
+ this.api.post('/images/build', context, {
+ headers: {
+ 'Content-Type': 'multipart/form-data'
+ },
+ params: options
+ })
+ );
+ }
+
+ async export(ids: string[]) {
+ const response = await this.api.post(
+ '/images/export',
+ { ids },
+ {
+ responseType: 'blob'
+ }
+ );
+ return response.data;
+ }
+
+ async import(source: File | string, repo?: string, tag?: string) {
+ const formData = new FormData();
+ if (source instanceof File) {
+ formData.append('file', source);
+ } else {
+ formData.append('url', source);
+ }
+ if (repo) formData.append('repo', repo);
+ if (tag) formData.append('tag', tag);
+
+ return this.handleResponse(
+ this.api.post('/images/import', formData, {
+ headers: {
+ 'Content-Type': 'multipart/form-data'
+ }
+ })
+ );
+ }
+
+ async commit(
+ containerId: string,
+ options?: {
+ repo?: string;
+ tag?: string;
+ comment?: string;
+ author?: string;
+ pause?: boolean;
+ changes?: string[];
+ }
+ ) {
+ return this.handleResponse(
+ this.api.post('/images/commit', {
+ containerId,
+ ...options
+ })
+ );
+ }
+
+ async checkMaturity(imageId: string) {
+ return this.handleResponse(this.api.get(`/images/maturity/${imageId}`));
+ }
+
+ async checkMaturityBatch(imageIds: string[]) {
+ if (!imageIds || imageIds.length === 0) {
+ throw new Error('No image IDs provided for batch check');
+ }
+
+ const firstId = imageIds[0];
+ return this.handleResponse(this.api.post(`/images/${firstId}/maturity`, { imageIds }));
+ }
+
+ async updateMaturity(imageId: string, maturityData: any) {
+ return this.handleResponse(this.api.put(`/images/maturity/${imageId}`, maturityData));
+ }
+
+ async getVulnerabilities(imageId: string) {
+ return this.handleResponse(this.api.get(`/images/${imageId}/vulnerabilities`));
+ }
+
+ async scanImage(imageId: string) {
+ return this.handleResponse(this.api.post(`/images/${imageId}/scan`));
+ }
}
diff --git a/frontend/src/lib/services/api/image-maturity-api-service.ts b/frontend/src/lib/services/api/image-maturity-api-service.ts
index 6d7739356..04809dab6 100644
--- a/frontend/src/lib/services/api/image-maturity-api-service.ts
+++ b/frontend/src/lib/services/api/image-maturity-api-service.ts
@@ -53,9 +53,7 @@ export interface ManualCheckResult {
};
}
-// Fixed class name - should be ImageMaturityAPIService not ImageAPIService
export default class ImageMaturityAPIService extends BaseAPIService {
- // Get maturity record for a specific image
async checkMaturity(id: string): Promise<ImageMaturity> {
const res = await this.api.get(`/images/maturity/${id}`);
return res.data;
@@ -88,8 +86,9 @@ export default class ImageMaturityAPIService extends BaseAPIService {
}
// Trigger maturity check for all images
- async triggerMaturityCheck(): Promise<{ success: boolean; message: string }> {
- const res = await this.api.post('/images/maturity/check');
+ async triggerMaturityCheck(imageIds?: string[]): Promise<{ success: boolean; message: string }> {
+ const payload = imageIds && imageIds.length > 0 ? { imageIds } : {};
+ const res = await this.api.post('/images/maturity/check', payload);
return res.data;
}
@@ -133,28 +132,4 @@ export default class ImageMaturityAPIService extends BaseAPIService {
}
};
}
-
- /**
- * @deprecated This endpoint doesn't exist in the backend
- */
- async markImageAsMatured(imageId: string, daysSinceCreation: number) {
- console.warn('markImageAsMatured is not implemented in the backend');
- throw new Error('markImageAsMatured endpoint is not available');
- }
-
- /**
- * @deprecated This endpoint doesn't exist in the backend
- */
- async invalidateImageMaturity(imageIds: string[]) {
- console.warn('invalidateImageMaturity is not implemented in the backend');
- throw new Error('invalidateImageMaturity endpoint is not available');
- }
-
- /**
- * @deprecated This endpoint doesn't exist in the backend
- */
- async cleanupOrphanedMaturityRecords(existingImageIds: string[]) {
- console.warn('cleanupOrphanedMaturityRecords is not implemented in the backend');
- throw new Error('cleanupOrphanedMaturityRecords endpoint is not available');
- }
}
diff --git a/frontend/src/lib/services/api/oidc-api-service.ts b/frontend/src/lib/services/api/oidc-api-service.ts
index b6feb6c2a..1ed0c7431 100644
--- a/frontend/src/lib/services/api/oidc-api-service.ts
+++ b/frontend/src/lib/services/api/oidc-api-service.ts
@@ -6,6 +6,7 @@ export interface OidcUserInfo {
email: string;
name: string;
preferred_username?: string;
+ displayName?: string;
given_name?: string;
family_name?: string;
picture?: string;
diff --git a/frontend/src/lib/services/api/system-api-service.ts b/frontend/src/lib/services/api/system-api-service.ts
index 571e46b40..7b7bf33d7 100644
--- a/frontend/src/lib/services/api/system-api-service.ts
+++ b/frontend/src/lib/services/api/system-api-service.ts
@@ -1,37 +1,38 @@
import type { PruneType } from '$lib/types/actions.type';
+import type { DockerInfo } from '$lib/models/docker-info.type';
import BaseAPIService from './api-service';
export default class SystemAPIService extends BaseAPIService {
- async pruneAll(options: { containers?: boolean; images?: boolean; volumes?: boolean; networks?: boolean; dangling?: boolean; until?: string }) {
- return this.handleResponse(this.api.post('/system/prune', options));
- }
-
- async startAllContainers() {
- return this.handleResponse(this.api.post('/system/containers/start-all'));
- }
-
- async startAllStoppedContainers() {
- return this.handleResponse(this.api.post('/system/containers/start-stopped'));
- }
-
- async stopAllContainers() {
- return this.handleResponse(this.api.post('/system/containers/stop-all'));
- }
-
- async getDockerInfo() {
- return this.handleResponse(this.api.get('/system/docker/info'));
- }
-
- async getStats() {
- return this.handleResponse(this.api.get('/system/stats'));
- }
-
- async testConnection(host?: string) {
- const params = host ? { host } : {};
- return this.handleResponse(this.api.get('/system/docker/test', { params }));
- }
-
- async getSystemInfo() {
- return this.handleResponse(this.api.get('/system/info'));
- }
+ async pruneAll(options: { containers?: boolean; images?: boolean; volumes?: boolean; networks?: boolean; dangling?: boolean; until?: string }) {
+ return this.handleResponse(this.api.post('/system/prune', options));
+ }
+
+ async startAllContainers() {
+ return this.handleResponse(this.api.post('/system/containers/start-all'));
+ }
+
+ async startAllStoppedContainers() {
+ return this.handleResponse(this.api.post('/system/containers/start-stopped'));
+ }
+
+ async stopAllContainers() {
+ return this.handleResponse(this.api.post('/system/containers/stop-all'));
+ }
+
+ async getDockerInfo(): Promise<DockerInfo> {
+ return this.handleResponse(this.api.get('/system/docker/info'));
+ }
+
+ async getStats() {
+ return this.handleResponse(this.api.get('/system/stats'));
+ }
+
+ async testConnection(host?: string) {
+ const params = host ? { host } : {};
+ return this.handleResponse(this.api.get('/system/docker/test', { params }));
+ }
+
+ async getSystemInfo(): Promise<DockerInfo> {
+ return this.handleResponse(this.api.get('/system/info'));
+ }
}
diff --git a/frontend/src/lib/services/api/user-api-service.ts b/frontend/src/lib/services/api/user-api-service.ts
index 43f6b9c4b..89287d82b 100644
--- a/frontend/src/lib/services/api/user-api-service.ts
+++ b/frontend/src/lib/services/api/user-api-service.ts
@@ -1,5 +1,6 @@
import BaseAPIService from './api-service';
import type { User } from '$lib/types/user.type';
+import type { PaginationRequest, SortRequest, PaginatedApiResponse } from '$lib/types/pagination.type';
export interface Role {
id: string;
@@ -18,6 +19,40 @@ export default class UserAPIService extends BaseAPIService {
return response.users;
}
+ async getUsers(
+ pagination?: PaginationRequest,
+ sort?: SortRequest,
+ search?: string,
+ filters?: Record<string, string>
+): Promise<any[] | PaginatedApiResponse<any>> {
+ if (!pagination) {
+ const response = await this.handleResponse<{ users?: any[] }>(this.api.get('/users'));
+ return Array.isArray(response.users) ? response.users : Array.isArray(response) ? response : [];
+ }
+
+ const params: any = {
+ 'pagination[page]': pagination.page,
+ 'pagination[limit]': pagination.limit
+ };
+
+ if (sort) {
+ params['sort[column]'] = sort.column;
+ params['sort[direction]'] = sort.direction;
+ }
+
+ if (search) {
+ params.search = search;
+ }
+
+ if (filters) {
+ Object.entries(filters).forEach(([key, value]) => {
+ params[key] = value;
+ });
+ }
+
+ return this.handleResponse(this.api.get('/users', { params }));
+}
+
async get(id: string): Promise<User> {
return this.handleResponse(this.api.get(`/users/${id}`)) as Promise<User>;
}
@@ -26,7 +61,7 @@ export default class UserAPIService extends BaseAPIService {
return this.handleResponse(this.api.get(`/auth/me`)) as Promise<User>;
}
- async create(user: Omit<User, 'id' | 'createdAt' | 'updatedAt'>): Promise<User> {
+ async create(user: Omit<User, 'ID' | 'CreatedAt' | 'UpdatedAt'>): Promise<User> {
return this.handleResponse(this.api.post('/users', user)) as Promise<User>;
}
diff --git a/frontend/src/lib/stores/maturity-store.ts b/frontend/src/lib/stores/maturity-store.ts
index 2b0f902e6..b3f25c168 100644
--- a/frontend/src/lib/stores/maturity-store.ts
+++ b/frontend/src/lib/stores/maturity-store.ts
@@ -1,129 +1,148 @@
import { writable } from 'svelte/store';
import type { ImageMaturity } from '$lib/models/image.type';
-import ImageAPIService from '$lib/services/api/image-api-service';
-import ImageMaturityAPIService from '$lib/services/api/image-maturity-api-service';
+import { environmentAPI } from '$lib/services/api';
export type MaturityState = {
- lastChecked: Date | null;
- maturityData: Record<string, ImageMaturity>;
- isChecking: boolean;
+ lastChecked: Date | null;
+ maturityData: Record<string, ImageMaturity>;
+ isChecking: boolean;
};
const initialState: MaturityState = {
- lastChecked: null,
- maturityData: {},
- isChecking: false
+ lastChecked: null,
+ maturityData: {},
+ isChecking: false
};
export const maturityStore = writable<MaturityState>(initialState);
-const imageApi = new ImageAPIService();
-const imageMaturityApi = new ImageMaturityAPIService();
-
-// Function to update maturity for a specific image
export function updateImageMaturity(imageId: string, maturity: ImageMaturity | undefined): void {
- maturityStore.update((state) => {
- const newData = { ...state.maturityData };
-
- if (maturity) {
- newData[imageId] = maturity;
- } else {
- delete newData[imageId];
- }
-
- return {
- ...state,
- maturityData: newData
- };
- });
+ maturityStore.update((state) => {
+ const newData = { ...state.maturityData };
+
+ if (maturity) {
+ const processedMaturity = {
+ ...maturity,
+ date: normalizeDate(maturity.date)
+ };
+ newData[imageId] = processedMaturity;
+ } else {
+ delete newData[imageId];
+ }
+
+ return {
+ ...state,
+ maturityData: newData
+ };
+ });
+}
+
+function normalizeDate(dateString: string): string {
+ try {
+ const date = new Date(dateString);
+ if (isNaN(date.getTime())) {
+ return new Date().toISOString();
+ }
+ return date.toISOString();
+ } catch {
+ return new Date().toISOString();
+ }
}
-// Update the checking status
export function setMaturityChecking(isChecking: boolean): void {
- maturityStore.update((state) => ({
- ...state,
- isChecking,
- lastChecked: isChecking ? state.lastChecked : new Date()
- }));
+ maturityStore.update((state) => ({
+ ...state,
+ isChecking,
+ lastChecked: isChecking ? state.lastChecked : new Date()
+ }));
}
-// Load maturity data for a batch of images (from dashboard logic)
export async function loadImageMaturityBatch(imageIds: string[]): Promise<void> {
- if (imageIds.length === 0) return;
-
- try {
- const BATCH_SIZE = 2;
- for (let i = 0; i < imageIds.length; i += BATCH_SIZE) {
- const batch = imageIds.slice(i, i + BATCH_SIZE);
- await imageApi.checkMaturityBatch(batch);
-
- if (i + BATCH_SIZE < imageIds.length) {
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- }
- } catch (error) {
- console.error('Error loading maturity data batch:', error);
- }
+ if (imageIds.length === 0) return;
+
+ try {
+ const BATCH_SIZE = 2;
+ for (let i = 0; i < imageIds.length; i += BATCH_SIZE) {
+ const batch = imageIds.slice(i, i + BATCH_SIZE);
+
+ for (const imageId of batch) {
+ try {
+ const response = await environmentAPI.getImageMaturity(imageId);
+ if (response && response.data) {
+ updateImageMaturity(imageId, response.data);
+ }
+ } catch (error) {
+ console.error(`Failed to load maturity for image ${imageId}:`, error);
+ updateImageMaturity(imageId, {
+ version: 'unknown',
+ date: new Date().toISOString(),
+ status: 'Unknown',
+ updatesAvailable: false
+ });
+ }
+ }
+
+ if (i + BATCH_SIZE < imageIds.length) {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ }
+ } catch (error) {
+ console.error('Error loading maturity data batch:', error);
+ }
}
-// Load maturity data for top images (from dashboard logic)
export async function loadTopImagesMaturity(images: any[]): Promise<void> {
- if (!images || images.length === 0) return;
-
- const topImageIds = [...images]
- .sort((a, b) => (b.Size || 0) - (a.Size || 0))
- .slice(0, 5)
- .filter((img) => img.repo !== '<none>' && img.tag !== '<none>')
- .map((img) => img.Id);
-
- await loadImageMaturityBatch(topImageIds);
+ if (!images || images.length === 0) return;
+
+ const topImageIds = [...images]
+ .sort((a, b) => (b.Size || 0) - (a.Size || 0))
+ .slice(0, 5)
+ .filter((img) => {
+ if (!img.RepoTags || img.RepoTags.length === 0) return false;
+ const repoTag = img.RepoTags[0];
+ return repoTag !== '<none>:<none>';
+ })
+ .map((img) => img.Id);
+
+ await loadImageMaturityBatch(topImageIds);
}
-// Trigger bulk maturity check using the ImageMaturityAPIService
-export async function triggerBulkMaturityCheck(): Promise<{ success: boolean; message: string }> {
- setMaturityChecking(true);
-
- try {
- const result = await imageMaturityApi.triggerMaturityCheck();
-
- if (result.success) {
- return { success: true, message: 'Maturity check completed successfully' };
- } else {
- return { success: false, message: 'Maturity check failed' };
- }
- } catch (error) {
- console.error('Bulk maturity check error:', error);
- return { success: false, message: 'Failed to trigger maturity check' };
- } finally {
- setMaturityChecking(false);
- }
+export async function triggerBulkMaturityCheck(imageIds?: string[]): Promise<{ success: boolean; message: string }> {
+ setMaturityChecking(true);
+
+ try {
+ const result = await environmentAPI.triggerMaturityCheck(imageIds);
+ return result;
+ } catch (error) {
+ console.error('Bulk maturity check error:', error);
+ return { success: false, message: 'Failed to trigger maturity check' };
+ } finally {
+ setMaturityChecking(false);
+ }
}
-// Enhanced image processing that includes maturity data from store
export function enhanceImagesWithMaturity(images: any[], maturityData: Record<string, ImageMaturity>): any[] {
- return images.map((image) => {
- // Parse repo and tag from RepoTags
- let repo = '<none>';
- let tag = '<none>';
- if (image.RepoTags && image.RepoTags.length > 0) {
- const repoTag = image.RepoTags[0];
- if (repoTag.includes(':')) {
- [repo, tag] = repoTag.split(':');
- } else {
- repo = repoTag;
- tag = 'latest';
- }
- }
-
- const storedMaturity = maturityData[image.Id];
-
- return {
- ...image,
- repo,
- tag,
- inUse: image.Containers > 0,
- // Prioritize store data over image data
- maturity: storedMaturity !== undefined ? storedMaturity : image.maturity
- };
- });
+ return images.map((image) => {
+ let repo = '<none>';
+ let tag = '<none>';
+ if (image.RepoTags && image.RepoTags.length > 0) {
+ const repoTag = image.RepoTags[0];
+ if (repoTag !== '<none>:<none>' && repoTag.includes(':')) {
+ [repo, tag] = repoTag.split(':');
+ } else if (repoTag !== '<none>:<none>') {
+ repo = repoTag;
+ tag = 'latest';
+ }
+ }
+
+ const storedMaturity = maturityData[image.Id];
+
+ return {
+ ...image,
+ repo,
+ tag,
+ inUse: image.Containers > 0,
+ maturity: storedMaturity !== undefined ? storedMaturity : image.maturity
+ };
+ });
}
diff --git a/frontend/src/lib/stores/user-store.ts b/frontend/src/lib/stores/user-store.ts
index 19147c50a..f9ea22bc4 100644
--- a/frontend/src/lib/stores/user-store.ts
+++ b/frontend/src/lib/stores/user-store.ts
@@ -4,15 +4,15 @@ import { writable } from 'svelte/store';
const userStore = writable<User | null>(null);
const setUser = (user: User) => {
- userStore.set(user);
+ userStore.set(user);
};
const clearUser = () => {
- userStore.set(null);
+ userStore.set(null);
};
export default {
- subscribe: userStore.subscribe,
- setUser,
- clearUser
+ subscribe: userStore.subscribe,
+ setUser,
+ clearUser
};
diff --git a/frontend/src/lib/types/network.type.ts b/frontend/src/lib/types/network.type.ts
new file mode 100644
index 000000000..9b56c3943
--- /dev/null
+++ b/frontend/src/lib/types/network.type.ts
@@ -0,0 +1,121 @@
+export interface NetworkCreateOptions {
+ name: string;
+ driver?: string;
+ internal?: boolean;
+ attachable?: boolean;
+ ingress?: boolean;
+ ipam?: IPAMConfig;
+ enableIPv6?: boolean;
+ options?: Record<string, string>;
+ labels?: Record<string, string>;
+ checkDuplicate?: boolean;
+}
+
+export interface IPAMConfig {
+ driver?: string;
+ config?: IPAMSubnet[];
+ options?: Record<string, string>;
+}
+
+export interface IPAMSubnet {
+ subnet?: string;
+ gateway?: string;
+ ipRange?: string;
+ auxAddress?: Record<string, string>;
+}
+
+export interface NetworkSummary {
+ ID: string;
+ Name: string;
+ Driver: string;
+ Scope: string;
+ Internal: boolean;
+ Attachable: boolean;
+ Ingress: boolean;
+ ConfigFrom?: NetworkConfigFrom;
+ ConfigOnly: boolean;
+ Containers?: Record<string, ContainerEndpoint> | null;
+ Options?: Record<string, string> | null;
+ Labels?: Record<string, string> | null;
+ Created: string;
+}
+
+export interface NetworkConfigFrom {
+ Network: string;
+}
+
+export interface ContainerEndpoint {
+ Name: string;
+ EndpointID: string;
+ MacAddress: string;
+ IPv4Address: string;
+ IPv6Address: string;
+}
+
+export interface NetworkInspect {
+ Name: string;
+ ID: string;
+ Created: string;
+ Scope: string;
+ Driver: string;
+ EnableIPv6: boolean;
+ IPAM?: IPAM;
+ Internal: boolean;
+ Attachable: boolean;
+ Ingress: boolean;
+ ConfigFrom?: NetworkConfigFrom;
+ ConfigOnly: boolean;
+ Containers?: Record<string, ContainerEndpoint> | null;
+ Options?: Record<string, string> | null;
+ Labels?: Record<string, string> | null;
+}
+
+export interface IPAM {
+ Driver: string;
+ Config?: IPAMSubnetInfo[];
+ Options?: Record<string, string>;
+}
+
+export interface IPAMSubnetInfo {
+ Subnet: string;
+ Gateway?: string;
+ IPRange?: string;
+ AuxAddress?: Record<string, string>;
+}
+
+export interface NetworkConnect {
+ containerId: string;
+ config?: NetworkEndpointSettings;
+}
+
+export interface NetworkDisconnect {
+ containerId: string;
+ force?: boolean;
+}
+
+export interface NetworkEndpointSettings {
+ ipamConfig?: EndpointIPAMConfig;
+ links?: string[];
+ aliases?: string[];
+ networkId?: string;
+ endpointId?: string;
+ gateway?: string;
+ ipAddress?: string;
+ ipPrefixLen?: number;
+ ipv6Gateway?: string;
+ globalIPv6Address?: string;
+ globalIPv6PrefixLen?: number;
+ macAddress?: string;
+ driverOpts?: Record<string, string>;
+}
+
+export interface EndpointIPAMConfig {
+ ipv4Address?: string;
+ ipv6Address?: string;
+ linkLocalIPs?: string[];
+}
+
+export interface NetworkPruneResponse {
+ networksDeleted: string[];
+ spaceReclaimed: number;
+}
\ No newline at end of file
diff --git a/frontend/src/lib/types/pagination.type.ts b/frontend/src/lib/types/pagination.type.ts
new file mode 100644
index 000000000..4742e1ed5
--- /dev/null
+++ b/frontend/src/lib/types/pagination.type.ts
@@ -0,0 +1,57 @@
+export type PaginationRequest = {
+ page: number;
+ limit: number;
+};
+
+export type SortRequest = {
+ column: string;
+ direction: 'asc' | 'desc';
+};
+
+export type FilterMap = Record<string, string>;
+
+export type SearchPaginationSortRequest = {
+ search?: string;
+ pagination?: PaginationRequest;
+ sort?: SortRequest;
+ filters?: FilterMap;
+};
+
+export type PaginationResponse = {
+ totalPages: number;
+ totalItems: number;
+ currentPage: number;
+ itemsPerPage: number;
+};
+
+export type Paginated<T> = {
+ data: T[];
+ pagination: PaginationResponse;
+};
+
+export interface PaginatedApiResponse<T> {
+ success: boolean;
+ data: T[];
+ pagination: PaginationResponse;
+}
+
+export interface SortedPaginationRequest {
+ pagination: {
+ page: number;
+ limit: number;
+ };
+ sort: {
+ column: string;
+ direction: 'asc' | 'desc';
+ };
+}
+
+export interface ExternalPagination {
+ pageSize: number;
+ currentPage: number;
+ totalPages: number;
+ totalItems: number;
+}
+
+export const DEFAULT_PAGE_SIZE = 20;
+export const MAX_PAGE_SIZE = 100;
\ No newline at end of file
diff --git a/frontend/src/lib/types/table-types.ts b/frontend/src/lib/types/table-types.ts
index e68a93fc2..b08620a11 100644
--- a/frontend/src/lib/types/table-types.ts
+++ b/frontend/src/lib/types/table-types.ts
@@ -1,4 +1,5 @@
import { type ColumnDef } from '@tanstack/table-core';
+import type { ExternalPagination } from './pagination.type';
export type FeatureFlags = {
sorting?: boolean;
@@ -31,4 +32,8 @@ export type UniversalTableProps<TData> = {
pagination?: PaginationOptions;
sort?: SortOptions;
selectedIds?: string[];
+ externalPagination?: ExternalPagination;
+ onPageChange?: (page: number) => void;
+ onPageSizeChange?: (size: number) => void;
+ onSort?: (column: string, direction: 'asc' | 'desc') => void;
};
diff --git a/frontend/src/lib/types/user.type.ts b/frontend/src/lib/types/user.type.ts
index db1f61ee1..7d2d742b1 100644
--- a/frontend/src/lib/types/user.type.ts
+++ b/frontend/src/lib/types/user.type.ts
@@ -1,15 +1,15 @@
export type User = {
- id: string;
- username: string;
- passwordHash?: string;
- displayName?: string;
- email?: string;
- roles: string[];
- createdAt: string;
- lastLogin?: string;
- requirePasswordChange?: boolean;
- updatedAt?: string;
- oidcSubjectId?: string;
+ ID: string;
+ Username: string;
+ PasswordHash?: string;
+ DisplayName?: string;
+ Email?: string;
+ Roles: string[];
+ CreatedAt: string;
+ LastLogin?: string;
+ RequirePasswordChange?: boolean;
+ UpdatedAt?: string;
+ OidcSubjectId?: string;
};
export interface UserRole {
diff --git a/frontend/src/lib/utils/redirect.util.ts b/frontend/src/lib/utils/redirect.util.ts
index 2437ab82a..be2f4ca32 100644
--- a/frontend/src/lib/utils/redirect.util.ts
+++ b/frontend/src/lib/utils/redirect.util.ts
@@ -7,19 +7,20 @@ export function getAuthRedirectPath(path: string, user: User | null, settings: S
const isSignedIn = !!user;
const isUnauthenticatedOnlyPath =
- path == '/auth/login' ||
+ path === '/auth/login' ||
path.startsWith('/auth/login/') ||
- path == '/auth/oidc/login' ||
+ path === '/auth/oidc/login' ||
path.startsWith('/auth/oidc/login') ||
- path == '/auth/oidc/callback' ||
+ path === '/auth/oidc/callback' ||
path.startsWith('/auth/oidc/callback') ||
- path == '/img' ||
+ path === '/img' ||
path.startsWith('/img') ||
- path == '/favicon.ico';
+ path === '/favicon.ico';
+
const isPublicPath = ['/authorize', '/device', '/health', '/healthz'].includes(path);
- const isOnboardingPath = path == '/onboarding' || path.startsWith('/onboarding');
+ const isOnboardingPath = path === '/onboarding' || path.startsWith('/onboarding');
- if (!isUnauthenticatedOnlyPath && !isPublicPath && !isSignedIn) {
+ if (!isSignedIn && !isUnauthenticatedOnlyPath && !isPublicPath) {
return '/auth/login';
}
@@ -30,7 +31,7 @@ export function getAuthRedirectPath(path: string, user: User | null, settings: S
}
if (isUnauthenticatedOnlyPath && isSignedIn && settings?.onboarding?.completed) {
- return '/';
+ return '/dashboard';
}
return null;
diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte
index 1526732e0..66cc2d69f 100644
--- a/frontend/src/routes/+layout.svelte
+++ b/frontend/src/routes/+layout.svelte
@@ -13,7 +13,17 @@
let { children, data } = $props();
- const { versionInformation, user, settings } = data;
+ const { versionInformation, user, settings } = $state(data);
+
+ $effect(() => {
+ if (user) {
+ userStore.setUser(user);
+ }
+
+ if (settings) {
+ settingsStore.set(settings);
+ }
+ });
$effect(() => {
const currentUser = $userStore || user;
@@ -26,22 +36,15 @@
});
const isNavigating = $derived(navigating.type !== null);
-
const isOnboardingPage = $derived(page.url.pathname.startsWith('/onboarding'));
const isLoginPage = $derived(
page.url.pathname === '/login' ||
page.url.pathname.startsWith('/auth/login') ||
page.url.pathname === '/auth' ||
- page.url.pathname.includes('/login')
+ page.url.pathname.includes('/login') ||
+ page.url.pathname.includes('/callback')
);
-
- if (user) {
- userStore.setUser(user);
- }
-
- if (settings) {
- settingsStore.set(settings);
- }
+ const currentUser = $derived($userStore || user);
</script>
<svelte:head><title>Arcane</title></svelte:head>
@@ -58,9 +61,9 @@
{/if}
<div class="bg-background flex min-h-screen">
- {#if !!$userStore && !isOnboardingPage && !isLoginPage}
+ {#if currentUser && !isOnboardingPage && !isLoginPage}
<Sidebar.Provider>
- <AppSidebar {versionInformation} {user} />
+ <AppSidebar {versionInformation} user={currentUser} />
<main class="flex-1">
<section class="p-6">
{@render children()}
diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.ts
index decc432a5..a5a93447a 100644
--- a/frontend/src/routes/+layout.ts
+++ b/frontend/src/routes/+layout.ts
@@ -7,38 +7,36 @@ import { tryCatch } from '$lib/utils/try-catch';
export const ssr = false;
-export const load = async ({}) => {
- const updateCheckDisabled = env.PUBLIC_UPDATE_CHECK_DISABLED === 'true';
-
- let arcaneSettings = await tryCatch(settingsAPI.getSettings());
- if (arcaneSettings.error) {
- console.error('Failed to load all setting settings');
- arcaneSettings = await tryCatch(settingsAPI.getPublicSettings());
- }
-
- const arcaneUser = await tryCatch(userAPI.getCurrentUser());
- if (arcaneUser.error) {
- console.error('Failed to load user information');
- }
-
- if (!environmentStore.isInitialized()) {
- const environments = await tryCatch(environmentManagementAPI.list());
-
- await environmentStore.initialize(environments.data || [], true);
- }
-
- let versionInformation: AppVersionInformation;
- if (updateCheckDisabled) {
- versionInformation = { currentVersion: versionService.getCurrentVersion() };
- } else {
- versionInformation = await versionService.getVersionInformation();
- }
-
- return {
- user: arcaneUser.data,
- isAuthenticated: !!arcaneUser.data,
- settings: arcaneSettings.data,
- versionInformation,
- updateCheckDisabled
- };
+export const load = async () => {
+ const updateCheckDisabled = env.PUBLIC_UPDATE_CHECK_DISABLED === 'true';
+
+ let arcaneSettings = await tryCatch(settingsAPI.getSettings());
+ if (arcaneSettings.error) {
+ arcaneSettings = await tryCatch(settingsAPI.getPublicSettings());
+ }
+
+ const arcaneUser = await tryCatch(userAPI.getCurrentUser());
+ const user = arcaneUser.error ? null : arcaneUser.data?.data;
+
+ if (!environmentStore.isInitialized() && user) {
+ const environments = await tryCatch(environmentManagementAPI.list());
+ if (!environments.error) {
+ await environmentStore.initialize(environments.data || [], true);
+ }
+ }
+
+ let versionInformation: AppVersionInformation;
+ if (updateCheckDisabled) {
+ versionInformation = { currentVersion: versionService.getCurrentVersion() };
+ } else {
+ versionInformation = await versionService.getVersionInformation();
+ }
+
+ return {
+ user,
+ isAuthenticated: !!user,
+ settings: arcaneSettings.data,
+ versionInformation,
+ updateCheckDisabled
+ };
};
diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelte
deleted file mode 100644
index 9949552dd..000000000
--- a/frontend/src/routes/+page.svelte
+++ /dev/null
@@ -1,998 +0,0 @@
-<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 UniversalTable from '$lib/components/universal-table.svelte';
- import {
- AlertCircle,
- Box,
- HardDrive,
- Cpu,
- ArrowRight,
- PlayCircle,
- StopCircle,
- Trash2,
- RefreshCw,
- Loader2,
- Monitor
- } from '@lucide/svelte';
- import * as Alert from '$lib/components/ui/alert/index.js';
- import {
- capitalizeFirstLetter,
- truncateString,
- shortId,
- parseStatusTime
- } from '$lib/utils/string.utils';
- import { formatBytes } from '$lib/utils/bytes.util';
- import StatusBadge from '$lib/components/badges/status-badge.svelte';
- 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 { handleApiResultWithCallbacks } from '$lib/utils/api.util';
- import { tryCatch } from '$lib/utils/try-catch';
- import { systemAPI, imageAPI, environmentAPI, settingsAPI } from '$lib/services/api';
- import { openConfirmDialog } from '$lib/components/confirm-dialog';
- import MaturityItem from '$lib/components/maturity-item.svelte';
- import { onMount } from 'svelte';
- import { maturityStore } from '$lib/stores/maturity-store';
- import type { PruneType } from '$lib/types/actions.type';
- import DropdownCard from '$lib/components/dropdown-card.svelte';
- import Meter from '$lib/components/meter.svelte';
- import DockerIcon from '$lib/icons/docker-icon.svelte';
- import GitHubIcon from '$lib/icons/github-icon.svelte';
- import type { SystemStats } from '$lib/models/system-stats';
- import type { ContainerInfo, EnhancedContainerInfo } from '$lib/models/container-info';
- import type { Settings } from '$lib/types/settings.type';
-
- type EnhancedImageInfo = {
- Id: string;
- RepoTags: string[];
- RepoDigests: string[];
- ParentId: string;
- Created: number;
- Size: number;
- SharedSize: number;
- VirtualSize: number;
- Labels: Record<string, string>;
- Containers: number;
- repo?: string;
- tag?: string;
- inUse?: boolean;
- maturity?: any;
- };
-
- let { data }: { data: PageData } = $props();
-
- let dashboardStates = $state({
- dockerInfo: null as any,
- containers: null as ContainerInfo[] | null,
- images: [] as EnhancedImageInfo[],
- settings: null as Settings | null,
- systemStats: null as SystemStats | null,
- error: null as string | null,
- isPruneDialogOpen: false
- });
-
- let isLoading = $state({
- starting: false,
- stopping: false,
- refreshing: false,
- pruning: false,
- loadingStats: true,
- loadingMaturity: true,
- loadingDockerInfo: true,
- loadingContainers: true,
- loadingImages: true,
- loadingSettings: true
- });
-
- let liveSystemStats = $state(null as SystemStats | null);
- let statsInterval: NodeJS.Timeout | null = null;
- let hasInitialStatsLoaded = $state(false);
-
- const runningContainers = $derived(
- dashboardStates.containers?.filter((c: ContainerInfo) => c.State === 'running').length ?? 0
- );
-
- const stoppedContainers = $derived(
- dashboardStates.containers?.filter((c: ContainerInfo) => c.State === 'exited').length ?? 0
- );
-
- const totalImageSize = $derived(
- dashboardStates.images?.reduce((sum, image) => sum + (image.Size || 0), 0) ?? 0
- );
-
- const containerUsagePercent = $derived(
- dashboardStates.containers?.length
- ? (runningContainers / dashboardStates.containers.length) * 100
- : 0
- );
-
- const currentStats = $derived(dashboardStates.systemStats || liveSystemStats);
-
- function getContainerDisplayName(container: ContainerInfo): string {
- if (container.Names && container.Names.length > 0) {
- return container.Names[0].startsWith('/')
- ? container.Names[0].substring(1)
- : container.Names[0];
- }
- return shortId(container.Id);
- }
-
- async function loadInitialData() {
- isLoading.loadingDockerInfo = true;
- isLoading.loadingContainers = true;
- isLoading.loadingImages = true;
- isLoading.loadingSettings = true;
- dashboardStates.error = null;
-
- const [dockerInfoResult, containersResult, imagesResult, settingsResult] =
- await Promise.allSettled([
- tryCatch(systemAPI.getDockerInfo()),
- tryCatch(environmentAPI.getContainers()),
- tryCatch(environmentAPI.getImages()),
- tryCatch(settingsAPI.getSettings())
- ]);
-
- if (dockerInfoResult.status === 'fulfilled' && !dockerInfoResult.value.error) {
- dashboardStates.dockerInfo = dockerInfoResult.value.data;
- } else {
- console.error(
- 'Failed to load Docker Info:',
- dockerInfoResult.status === 'rejected'
- ? dockerInfoResult.reason
- : dockerInfoResult.value.error
- );
- dashboardStates.error = dashboardStates.error || 'Failed to load Docker Info.';
- }
- isLoading.loadingDockerInfo = false;
-
- if (containersResult.status === 'fulfilled' && !containersResult.value.error) {
- dashboardStates.containers = containersResult.value.data;
- } else {
- console.error(
- 'Failed to load Containers:',
- containersResult.status === 'rejected'
- ? containersResult.reason
- : containersResult.value.error
- );
- dashboardStates.containers = [];
- dashboardStates.error = dashboardStates.error || 'Failed to load Containers.';
- }
- isLoading.loadingContainers = false;
-
- if (imagesResult.status === 'fulfilled' && !imagesResult.value.error) {
- dashboardStates.images = imagesResult.value.data;
- } else {
- console.error(
- 'Failed to load Images:',
- imagesResult.status === 'rejected' ? imagesResult.reason : imagesResult.value.error
- );
- dashboardStates.images = [];
- dashboardStates.error = dashboardStates.error || 'Failed to load Images.';
- }
- isLoading.loadingImages = false;
-
- if (settingsResult.status === 'fulfilled' && !settingsResult.value.error) {
- dashboardStates.settings = settingsResult.value.data;
- } else {
- console.error(
- 'Failed to load Settings:',
- settingsResult.status === 'rejected' ? settingsResult.reason : settingsResult.value.error
- );
- dashboardStates.error = dashboardStates.error || 'Failed to load Settings.';
- }
- isLoading.loadingSettings = false;
-
- if (dashboardStates.images && dashboardStates.images.length > 0) {
- loadTopImagesMaturity();
- } else {
- isLoading.loadingMaturity = false;
- }
- }
-
- async function fetchLiveSystemStats() {
- if (!hasInitialStatsLoaded) {
- isLoading.loadingStats = true;
- }
-
- try {
- const response = await systemAPI.getStats();
-
- let stats: SystemStats | null = null;
-
- if (response && typeof response === 'object') {
- if ('success' in response && response.success && 'data' in response) {
- stats = response.data as SystemStats;
- } else if ('cpuUsage' in response) {
- stats = response as SystemStats;
- }
- }
-
- if (stats) {
- liveSystemStats = stats;
- dashboardStates.systemStats = stats;
- } else {
- console.warn('Invalid system stats response format:', response);
- }
- } catch (error) {
- console.error('Failed to fetch live system stats:', error);
- } finally {
- if (!hasInitialStatsLoaded) {
- isLoading.loadingStats = false;
- hasInitialStatsLoaded = true;
- }
- }
- }
-
- async function loadTopImagesMaturity() {
- if (!dashboardStates.images || dashboardStates.images.length === 0) {
- isLoading.loadingMaturity = false;
- return;
- }
-
- isLoading.loadingMaturity = true;
-
- const topImageIds = [...dashboardStates.images]
- .sort((a, b) => (b.Size || 0) - (a.Size || 0))
- .slice(0, 5)
- .filter((img) => img.repo !== '<none>' && img.tag !== '<none>')
- .map((img) => img.Id);
-
- if (topImageIds.length === 0) {
- isLoading.loadingMaturity = false;
- return;
- }
-
- try {
- const BATCH_SIZE = 1;
- for (let i = 0; i < topImageIds.length; i += BATCH_SIZE) {
- const batch = topImageIds.slice(i, i + BATCH_SIZE);
- await imageAPI.checkMaturityBatch(batch);
-
- dashboardStates.images = dashboardStates.images.map((image) => {
- const storedMaturity = $maturityStore.maturityData[image.Id];
- return {
- ...image,
- maturity: storedMaturity !== undefined ? storedMaturity : image.maturity
- };
- });
-
- if (i + BATCH_SIZE < topImageIds.length) {
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- }
- } catch (error) {
- console.error('Error loading maturity data for dashboard images:', error);
- } finally {
- isLoading.loadingMaturity = false;
- }
- }
-
- onMount(() => {
- let mounted = true;
-
- loadInitialData();
- fetchLiveSystemStats();
-
- if (!statsInterval) {
- statsInterval = setInterval(() => {
- if (mounted) {
- fetchLiveSystemStats();
- }
- }, 5000);
- }
-
- return () => {
- mounted = false;
- if (statsInterval) {
- clearInterval(statsInterval);
- statsInterval = null;
- }
- };
- });
-
- async function refreshData() {
- if (isLoading.refreshing) return;
- isLoading.refreshing = true;
- await Promise.all([loadInitialData(), fetchLiveSystemStats()]);
- isLoading.refreshing = false;
- }
-
- async function handleStartAll() {
- if (isLoading.starting || !dashboardStates.dockerInfo || stoppedContainers === 0) return;
- isLoading.starting = true;
- handleApiResultWithCallbacks({
- result: await tryCatch(systemAPI.startAllStoppedContainers()),
- message: 'Failed to Start All Containers',
- setLoadingState: (value) => (isLoading.starting = value),
- onSuccess: async () => {
- toast.success('All Containers Started Successfully.');
- await loadInitialData();
- }
- });
- }
-
- async function handleStopAll() {
- if (isLoading.stopping || !dashboardStates.dockerInfo || runningContainers === 0) return;
- openConfirmDialog({
- title: 'Stop All Containers',
- message: 'Are you sure you want to stop all running containers?',
- confirm: {
- label: 'Confirm',
- destructive: false,
- action: async () => {
- handleApiResultWithCallbacks({
- result: await tryCatch(systemAPI.stopAllContainers()),
- message: 'Failed to Stop All Running Containers',
- setLoadingState: (value) => (isLoading.stopping = value),
- onSuccess: async () => {
- toast.success('All Containers Stopped Successfully.');
- await loadInitialData();
- }
- });
- }
- }
- });
- }
-
- async function confirmPrune(selectedTypes: PruneType[]) {
- if (isLoading.pruning || selectedTypes.length === 0) return;
- isLoading.pruning = true;
-
- const pruneOptions = {
- containers: selectedTypes.includes('containers'),
- images: selectedTypes.includes('images'),
- volumes: selectedTypes.includes('volumes'),
- networks: selectedTypes.includes('networks'),
- dangling: dashboardStates.settings?.pruneMode === 'dangling'
- };
-
- handleApiResultWithCallbacks({
- result: await tryCatch(systemAPI.pruneAll(pruneOptions)),
- message: `Failed to Prune ${selectedTypes.join(', ')}`,
- setLoadingState: (value) => (isLoading.pruning = value),
- onSuccess: async () => {
- dashboardStates.isPruneDialogOpen = false;
- const formattedTypes = selectedTypes.map((type) => capitalizeFirstLetter(type)).join(', ');
- toast.success(
- `${formattedTypes} ${selectedTypes.length > 1 ? 'were' : 'was'} pruned successfully.`
- );
- await loadInitialData();
- }
- });
- }
-</script>
-
-<div class="space-y-8">
- <div class="flex items-center justify-between">
- <div>
- <h1 class="text-3xl font-bold tracking-tight">Dashboard</h1>
- <p class="text-muted-foreground mt-1 text-sm">Overview of your Container Environment</p>
- </div>
- <Button
- variant="outline"
- size="sm"
- class="arcane-button-restart h-9"
- onclick={refreshData}
- disabled={isLoading.refreshing ||
- isLoading.starting ||
- isLoading.stopping ||
- isLoading.pruning}
- >
- {#if isLoading.refreshing}
- <Loader2 class="mr-2 size-4 animate-spin" />
- {:else}
- <RefreshCw class="mr-2 size-4" />
- {/if}
- Refresh
- </Button>
- </div>
-
- {#if dashboardStates.error}
- <Alert.Root variant="destructive">
- <AlertCircle class="mr-2 size-4" />
- <Alert.Title>Connection Error</Alert.Title>
- <Alert.Description>
- {dashboardStates.error} Please check your Docker connection in
- <a href="/settings" class="underline">Settings</a>.
- </Alert.Description>
- </Alert.Root>
- {/if}
-
- <section>
- <DropdownCard
- id="system-overview"
- title="System Overview"
- description="Hardware and Docker engine information"
- icon={Monitor}
- defaultExpanded={true}
- >
- <div class="grid grid-cols-1 gap-6 md:grid-cols-3">
- <!-- Containers Card -->
- <Card.Root class="overflow-hidden">
- <Card.Content class="p-6">
- <div class="mb-4 flex items-center justify-between">
- <div class="flex items-center gap-3">
- <div class="rounded-lg bg-green-500/10 p-2.5">
- <Box class="size-5 text-green-500" />
- </div>
- <div>
- <p class="text-muted-foreground text-sm font-medium">Containers</p>
- {#if isLoading.loadingContainers}
- <div class="bg-muted h-6 w-16 animate-pulse rounded mt-1"></div>
- {:else}
- <p class="text-2xl font-bold">
- {runningContainers}
- <span class="text-muted-foreground text-sm font-normal"
- >/ {dashboardStates.containers?.length || 0}</span
- >
- </p>
- {/if}
- </div>
- </div>
- </div>
-
- {#if isLoading.loadingContainers}
- <div class="bg-muted h-2 w-full animate-pulse rounded mb-6"></div>
- {:else if dashboardStates.containers?.length}
- <div class="mb-6">
- <Meter
- label="Active Containers"
- valueLabel="{runningContainers} running"
- value={runningContainers}
- max={dashboardStates.containers.length}
- variant={containerUsagePercent > 80 ? 'warning' : 'success'}
- size="sm"
- />
- </div>
- {/if}
-
- <div class="space-y-3 border-t pt-4">
- <div class="flex items-center gap-2">
- <DockerIcon class="text-muted-foreground size-4" />
- <p class="text-muted-foreground text-sm font-medium">Docker Engine</p>
- </div>
- {#if isLoading.loadingDockerInfo}
- <div class="grid grid-cols-2 gap-3 text-xs">
- <div class="space-y-1">
- <div class="bg-muted h-3 w-16 animate-pulse rounded"></div>
- <div class="bg-muted h-4 w-20 animate-pulse rounded"></div>
- </div>
- <div class="space-y-1">
- <div class="bg-muted h-3 w-12 animate-pulse rounded"></div>
- <div class="bg-muted h-4 w-16 animate-pulse rounded"></div>
- </div>
- </div>
- {:else}
- <div class="grid grid-cols-2 gap-3 text-xs">
- <div>
- <p class="text-muted-foreground">Version</p>
- <p class="font-medium">{dashboardStates.dockerInfo?.version || 'Unknown'}</p>
- </div>
- <div>
- <p class="text-muted-foreground">OS</p>
- <p class="font-medium">
- {dashboardStates.dockerInfo?.os ||
- dashboardStates.systemStats?.platform ||
- 'Unknown'}
- </p>
- </div>
- </div>
- {/if}
- </div>
- </Card.Content>
- </Card.Root>
-
- <!-- Storage Card -->
- <Card.Root class="overflow-hidden">
- <Card.Content class="p-6">
- <div class="mb-4 flex items-center justify-between">
- <div class="flex items-center gap-3">
- <div class="rounded-lg bg-blue-500/10 p-2.5">
- <HardDrive class="size-5 text-blue-500" />
- </div>
- <div>
- <p class="text-muted-foreground text-sm font-medium">Storage</p>
- {#if isLoading.loadingDockerInfo}
- <div class="bg-muted h-6 w-12 animate-pulse rounded mt-1"></div>
- {:else}
- <p class="text-2xl font-bold">{dashboardStates.dockerInfo?.images || 0}</p>
- <p class="text-muted-foreground text-xs">Docker images</p>
- {/if}
- </div>
- </div>
- </div>
-
- {#if isLoading.loadingStats && !hasInitialStatsLoaded}
- <div class="py-6 text-center">
- <Loader2 class="text-muted-foreground mx-auto mb-2 size-6 animate-spin" />
- <p class="text-muted-foreground text-sm">Loading storage data...</p>
- </div>
- {:else if currentStats?.diskTotal && currentStats?.diskUsage !== undefined}
- {@const storagePercent = Math.min(
- Math.max((currentStats.diskUsage / currentStats.diskTotal) * 100, 0),
- 100
- )}
- <div class="mb-4">
- <Meter
- label="System Storage"
- valueLabel="{storagePercent.toFixed(1)}%"
- value={storagePercent}
- max={100}
- variant={storagePercent > 85
- ? 'destructive'
- : storagePercent > 70
- ? 'warning'
- : 'success'}
- size="sm"
- />
- </div>
- <div class="text-muted-foreground space-y-1 text-xs">
- <div class="flex justify-between">
- <span>Used:</span>
- <span class="font-medium">{formatBytes(currentStats.diskUsage)}</span>
- </div>
- <div class="flex justify-between">
- <span>Total:</span>
- <span class="font-medium">{formatBytes(currentStats.diskTotal)}</span>
- </div>
- {#if totalImageSize > 0}
- <div class="border-border/50 flex justify-between border-t pt-1">
- <span>Docker Images:</span>
- <span class="font-medium">{formatBytes(totalImageSize)}</span>
- </div>
- {/if}
- </div>
- {:else if totalImageSize > 0}
- <div class="mb-4">
- <div class="py-4 text-center">
- <p class="text-muted-foreground text-sm">System storage data unavailable</p>
- </div>
- </div>
- <div class="text-muted-foreground text-xs">
- <div class="flex justify-between">
- <span>Docker Images:</span>
- <span class="font-medium">{formatBytes(totalImageSize)}</span>
- </div>
- </div>
- {:else}
- <div class="py-6 text-center">
- <p class="text-muted-foreground text-sm">No storage data available</p>
- </div>
- {/if}
- </Card.Content>
- </Card.Root>
-
- <!-- Hardware Card -->
- <Card.Root class="overflow-hidden">
- <Card.Content class="p-6">
- <div class="mb-4 flex items-center justify-between">
- <div class="flex items-center gap-3">
- <div class="rounded-lg bg-purple-500/10 p-2.5">
- <Cpu class="size-5 text-purple-500" />
- </div>
- <div>
- <p class="text-muted-foreground text-sm font-medium">Hardware</p>
- {#if isLoading.loadingStats && !hasInitialStatsLoaded}
- <div class="bg-muted h-4 w-24 animate-pulse rounded mt-1 text-xs"></div>
- {:else if currentStats}
- <div class="text-muted-foreground mt-1 flex items-center gap-4 text-xs">
- <span>{currentStats.cpuCount || 'N/A'} cores</span>
- <span
- >{currentStats.memoryTotal
- ? formatBytes(currentStats.memoryTotal, 0)
- : 'N/A'}</span
- >
- </div>
- {#if currentStats.hostname}
- <p class="text-muted-foreground mt-1 text-xs">{currentStats.hostname}</p>
- {/if}
- {:else}
- <div class="text-muted-foreground mt-1 text-xs">No data available</div>
- {/if}
- </div>
- </div>
- </div>
-
- {#if isLoading.loadingStats && !hasInitialStatsLoaded}
- <div class="py-6 text-center">
- <Loader2 class="text-muted-foreground mx-auto mb-2 size-6 animate-spin" />
- <p class="text-muted-foreground text-sm">Loading system stats...</p>
- </div>
- {:else if currentStats}
- {@const cpuPercent = Math.min(Math.max(currentStats.cpuUsage, 0), 100)}
- {@const memoryPercent = Math.min(
- Math.max((currentStats.memoryUsage / currentStats.memoryTotal) * 100, 0),
- 100
- )}
- <div class="space-y-4">
- <Meter
- label="CPU Usage"
- valueLabel="{cpuPercent.toFixed(1)}%"
- value={cpuPercent}
- max={100}
- variant={cpuPercent > 80
- ? 'destructive'
- : cpuPercent > 60
- ? 'warning'
- : 'success'}
- size="sm"
- />
-
- <Meter
- label="Memory Usage"
- valueLabel="{memoryPercent.toFixed(1)}%"
- value={memoryPercent}
- max={100}
- variant={memoryPercent > 80
- ? 'destructive'
- : memoryPercent > 60
- ? 'warning'
- : 'success'}
- size="sm"
- />
- </div>
- <div class="text-muted-foreground space-y-1 pt-3 text-xs">
- {#if currentStats.architecture}
- <div class="flex justify-between">
- <span>Architecture:</span>
- <span class="font-medium">{currentStats.architecture}</span>
- </div>
- {/if}
- {#if currentStats.platform}
- <div class="flex justify-between">
- <span>Platform:</span>
- <span class="font-medium capitalize">{currentStats.platform}</span>
- </div>
- {/if}
- </div>
- {:else}
- <div class="py-6 text-center">
- <p class="text-muted-foreground text-sm">System stats unavailable</p>
- </div>
- {/if}
- </Card.Content>
- </Card.Root>
- </div>
- </DropdownCard>
- </section>
-
- <section>
- <h2 class="mb-4 text-lg font-semibold tracking-tight">Quick Actions</h2>
- {#if isLoading.loadingDockerInfo}
- <div class="grid grid-cols-1 gap-5 sm:grid-cols-3">
- {#each Array(3) as _}
- <div class="bg-card flex flex-col items-center rounded-xl border p-6">
- <div class="bg-muted mb-4 size-12 animate-pulse rounded-full"></div>
- <div class="bg-muted h-4 w-24 animate-pulse rounded"></div>
- <div class="bg-muted mt-2 h-3 w-16 animate-pulse rounded"></div>
- </div>
- {/each}
- </div>
- {:else}
- <div class="grid grid-cols-1 gap-5 sm:grid-cols-3">
- <button
- class="group bg-card relative flex flex-col items-center rounded-xl border p-6 shadow-sm transition-all hover:shadow-md disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:shadow-sm"
- disabled={!dashboardStates.dockerInfo ||
- stoppedContainers === 0 ||
- isLoading.starting ||
- isLoading.stopping ||
- isLoading.pruning}
- onclick={handleStartAll}
- >
- <div
- class="mb-4 flex size-12 items-center justify-center rounded-full bg-green-500/10 transition-colors group-hover:bg-green-500/20"
- >
- {#if isLoading.starting}
- <Loader2 class="size-6 animate-spin text-green-500" />
- {:else}
- <PlayCircle class="size-6 text-green-500" />
- {/if}
- </div>
- <span class="text-center text-base font-medium">Start All Stopped</span>
- <span class="text-muted-foreground mt-1 text-sm">{stoppedContainers} containers</span>
- </button>
-
- <button
- class="group bg-card relative flex flex-col items-center rounded-xl border p-6 shadow-sm transition-all hover:shadow-md disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:shadow-sm"
- disabled={!dashboardStates.dockerInfo ||
- runningContainers === 0 ||
- isLoading.starting ||
- isLoading.stopping ||
- isLoading.pruning}
- onclick={handleStopAll}
- >
- <div
- class="mb-4 flex size-12 items-center justify-center rounded-full bg-blue-500/10 transition-colors group-hover:bg-blue-500/20"
- >
- {#if isLoading.stopping}
- <Loader2 class="size-6 animate-spin text-blue-500" />
- {:else}
- <StopCircle class="size-6 text-blue-500" />
- {/if}
- </div>
- <span class="text-center text-base font-medium">Stop All Running</span>
- <span class="text-muted-foreground mt-1 text-sm">{runningContainers}</span>
- </button>
-
- <button
- class="group bg-card hover:border-destructive/50 disabled:hover:border-border relative flex flex-col items-center rounded-xl border p-6 shadow-sm transition-all hover:shadow-md disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:shadow-sm"
- disabled={!dashboardStates.dockerInfo ||
- isLoading.starting ||
- isLoading.stopping ||
- isLoading.pruning}
- onclick={() => (dashboardStates.isPruneDialogOpen = true)}
- >
- <div
- class="mb-4 flex size-12 items-center justify-center rounded-full bg-red-500/10 transition-colors group-hover:bg-red-500/20"
- >
- {#if isLoading.pruning}
- <Loader2 class="size-6 animate-spin text-red-500" />
- {:else}
- <Trash2 class="size-6 text-red-500" />
- {/if}
- </div>
- <span class="text-center text-base font-medium">Prune System</span>
- <span class="text-muted-foreground mt-1 text-sm">Clean unused resources</span>
- </button>
- </div>
- {/if}
- </section>
-
- <section>
- <h2 class="mb-4 text-lg font-semibold tracking-tight">Resources</h2>
- <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
- <!-- Containers Table Card -->
- <Card.Root class="relative flex flex-col border shadow-sm">
- <Card.Header class="px-6">
- <div class="flex items-center justify-between">
- <div>
- <Card.Title
- ><a class="font-medium hover:underline" href="/containers">Containers</a
- ></Card.Title
- >
- <Card.Description class="pb-3">Recent containers</Card.Description>
- </div>
- <Button
- variant="ghost"
- size="sm"
- href="/containers"
- disabled={isLoading.loadingContainers || !dashboardStates.dockerInfo}
- >
- View All
- <ArrowRight class="ml-2 size-4" />
- </Button>
- </div>
- </Card.Header>
- <Card.Content class="flex-1 p-0">
- {#if isLoading.loadingContainers}
- <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
- <Loader2 class="text-muted-foreground mb-4 size-8 animate-spin" />
- <p class="text-lg font-medium">Loading Containers...</p>
- <p class="text-muted-foreground mt-1 text-sm">
- Please wait while we fetch containers
- </p>
- </div>
- {:else if dashboardStates.containers && dashboardStates.containers.length > 0}
- <div class="flex h-full flex-col">
- <div class="flex-1">
- <UniversalTable
- data={dashboardStates.containers.slice(0, 5).map(
- (c): EnhancedContainerInfo => ({
- ...c,
- displayName: getContainerDisplayName(c),
- statusSortValue: parseStatusTime(c.Status)
- })
- )}
- columns={[
- { accessorKey: 'displayName', header: 'Name' },
- { accessorKey: 'Image', header: 'Image' },
- { accessorKey: 'State', header: 'State' },
- { accessorKey: 'statusSortValue', header: 'Status' }
- ]}
- features={{
- filtering: false,
- selection: false
- }}
- sort={{
- defaultSort: { id: 'statusSortValue', desc: false }
- }}
- pagination={{
- pageSize: 5,
- pageSizeOptions: [5]
- }}
- display={{
- isDashboardTable: true
- }}
- >
- {#snippet rows({ item }: { item: EnhancedContainerInfo })}
- {@const stateVariant = statusVariantMap[item.State.toLowerCase()]}
- <Table.Cell>
- <a class="font-medium hover:underline" href="/containers/{item.Id}/">
- {item.displayName}
- </a>
- </Table.Cell>
- <Table.Cell title={item.Image}>
- {truncateString(item.Image, 40)}
- </Table.Cell>
- <Table.Cell>
- <StatusBadge
- variant={stateVariant}
- text={capitalizeFirstLetter(item.State)}
- />
- </Table.Cell>
- <Table.Cell>{item.Status}</Table.Cell>
- {/snippet}
- </UniversalTable>
- </div>
- {#if dashboardStates.containers.length > 5}
- <div class="bg-muted/40 text-muted-foreground border-t px-6 py-2 text-xs">
- Showing 5 of {dashboardStates.containers.length} containers
- </div>
- {/if}
- </div>
- {:else if !dashboardStates.error}
- <div class="flex flex-col items-center justify-center px-6 py-10 text-center">
- <Box class="text-muted-foreground mb-2 size-8 opacity-40" />
- <p class="text-muted-foreground text-sm">No containers found</p>
- <p class="text-muted-foreground mt-1 text-xs">
- Use Docker CLI or another tool to create containers
- </p>
- </div>
- {/if}
- </Card.Content>
- </Card.Root>
-
- <!-- Images Table Card -->
- <Card.Root class="relative flex flex-col border shadow-sm">
- <Card.Header class="px-6">
- <div class="flex items-center justify-between">
- <div>
- <Card.Title
- ><a class="font-medium hover:underline" href="/images">Images</a></Card.Title
- >
- <Card.Description class="pb-3">Top 5 Largest Images</Card.Description>
- </div>
- <Button
- variant="ghost"
- size="sm"
- href="/images"
- disabled={isLoading.loadingImages || !dashboardStates.dockerInfo}
- >
- View All
- <ArrowRight class="ml-2 size-4" />
- </Button>
- </div>
- </Card.Header>
- <Card.Content class="flex-1 p-0">
- {#if isLoading.loadingImages}
- <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
- <Loader2 class="text-muted-foreground mb-4 size-8 animate-spin" />
- <p class="text-lg font-medium">Loading Images...</p>
- <p class="text-muted-foreground mt-1 text-sm">Please wait while we fetch images</p>
- </div>
- {:else if dashboardStates.images?.length > 0}
- <div class="flex h-full flex-col">
- <div class="flex-1">
- <UniversalTable
- data={dashboardStates.images
- .slice()
- .sort((a, b) => (b.Size || 0) - (a.Size || 0))
- .slice(0, 5)}
- columns={[
- { accessorKey: 'repo', header: 'Name' },
- { accessorKey: 'inUse', header: ' ', enableSorting: false },
- { accessorKey: 'tag', header: 'Tag' },
- { accessorKey: 'Size', header: 'Size' }
- ]}
- features={{
- filtering: false,
- selection: false
- }}
- pagination={{
- pageSize: 5,
- pageSizeOptions: [5]
- }}
- display={{
- isDashboardTable: true
- }}
- sort={{
- defaultSort: { id: 'Size', desc: true }
- }}
- >
- {#snippet rows({ item }: { item: EnhancedImageInfo })}
- <Table.Cell>
- <div class="flex items-center gap-2">
- <div class="flex flex-1 items-center">
- {#if isLoading.loadingMaturity}
- <div class="bg-muted size-4 animate-pulse rounded-full mr-2"></div>
- {:else}
- <MaturityItem
- maturity={item.maturity}
- isLoadingInBackground={!item.maturity}
- imageId={item.Id}
- />
- {/if}
- <a
- class="shrink truncate font-medium hover:underline"
- href="/images/{item.Id}/"
- >
- {#if item.repo && item.repo !== '<none>'}
- {item.repo}
- {:else if item.RepoTags && item.RepoTags.length > 0 && item.RepoTags[0] !== '<none>:<none>'}
- {item.RepoTags[0].split(':')[0]}
- {:else}
- {item.Id.substring(7, 19)}
- {/if}
- </a>
- </div>
- </div>
- </Table.Cell>
- <Table.Cell>
- {#if !item.inUse}
- <StatusBadge text="Unused" variant="amber" />
- {:else}
- <StatusBadge text="In Use" variant="green" />
- {/if}
- </Table.Cell>
- <Table.Cell>
- {#if item.tag && item.tag !== '<none>'}
- {item.tag}
- {:else if item.RepoTags && item.RepoTags.length > 0 && item.RepoTags[0] !== '<none>:<none>'}
- {item.RepoTags[0].split(':')[1] || 'latest'}
- {:else}
- &lt;none&gt;
- {/if}
- </Table.Cell>
- <Table.Cell>{formatBytes(item.Size)}</Table.Cell>
- {/snippet}
- </UniversalTable>
- </div>
- {#if dashboardStates.images.length > 5}
- <div class="bg-muted/40 text-muted-foreground border-t px-6 py-2 text-xs">
- Showing 5 of {dashboardStates.images.length} images
- </div>
- {/if}
- </div>
- {:else if !dashboardStates.error}
- <div class="flex flex-col items-center justify-center px-6 py-10 text-center">
- <HardDrive class="text-muted-foreground mb-2 size-8 opacity-40" />
- <p class="text-muted-foreground text-sm">No images found</p>
- <p class="text-muted-foreground mt-1 text-xs">
- Pull images using Docker CLI or another tool
- </p>
- </div>
- {/if}
- </Card.Content>
- </Card.Root>
- </div>
- </section>
-
- <section class="mt-10 border-t pt-4">
- <div class="text-muted-foreground flex items-center justify-between text-sm">
- <div class="flex items-center">
- <a
- href="https://github.com/ofkm/arcane"
- target="_blank"
- rel="noopener noreferrer"
- class="hover:text-foreground transition-colors"
- title="GitHub"
- >
- <GitHubIcon class="size-4 fill-current" />
- <span class="sr-only">GitHub</span>
- </a>
- </div>
- <div></div>
- </div>
- </section>
-
- <PruneConfirmationDialog
- bind:open={dashboardStates.isPruneDialogOpen}
- isPruning={isLoading.pruning}
- imagePruneMode={(dashboardStates.settings?.pruneMode as 'dangling' | 'all') || 'dangling'}
- onConfirm={confirmPrune}
- onCancel={() => (dashboardStates.isPruneDialogOpen = false)}
- />
-</div>
diff --git a/frontend/src/routes/+page.ts b/frontend/src/routes/+page.ts
deleted file mode 100644
index 170636dda..000000000
--- a/frontend/src/routes/+page.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { systemAPI, settingsAPI, environmentAPI } from '$lib/services/api';
-
-export const load = async () => {
- // try {
- // const [dockerInfoResult, containersResult, imagesResult, settingsResult] =
- // await Promise.allSettled([
- // systemAPI.getDockerInfo(),
- // environmentAPI.getContainers(),
- // environmentAPI.getImages(),
- // settingsAPI.getSettings()
- // ]);
- // const dockerInfo = dockerInfoResult.status === 'fulfilled' ? dockerInfoResult.value : null;
- // const containers = containersResult.status === 'fulfilled' ? containersResult.value : [];
- // const images = imagesResult.status === 'fulfilled' ? imagesResult.value : [];
- // const settings = settingsResult.status === 'fulfilled' ? settingsResult.value : null;
- // return {
- // dockerInfo,
- // containers,
- // images,
- // settings
- // };
- // } catch (error) {
- // console.error('Error loading dashboard data:', error);
- // return {
- // dockerInfo: null,
- // containers: [],
- // images: [],
- // settings: null,
- // error: error instanceof Error ? error.message : String(error)
- // };
- // }
-};
diff --git a/frontend/src/routes/auth/login/+page.svelte b/frontend/src/routes/auth/login/+page.svelte
index 6c78ff8c4..a2f5be1f4 100644
--- a/frontend/src/routes/auth/login/+page.svelte
+++ b/frontend/src/routes/auth/login/+page.svelte
@@ -42,7 +42,7 @@
try {
await authService.login({ username, password });
await invalidateAll();
- const redirectTo = data.redirectTo || '/';
+ const redirectTo = data.redirectTo || '/dashboard';
goto(redirectTo);
} catch (err) {
error = err instanceof Error ? err.message : 'Login failed';
@@ -54,7 +54,9 @@
const showDivider = $derived(showOidcLoginButton && showLocalLoginForm);
</script>
-<div class="bg-background/50 flex min-h-screen flex-col items-center justify-center px-4 py-12 sm:px-6 lg:px-8">
+<div
+ class="bg-background/50 flex min-h-screen flex-col items-center justify-center px-4 py-12 sm:px-6 lg:px-8"
+>
<div class="w-full max-w-md space-y-8">
<!-- Logo and Title -->
<div class="text-center">
@@ -82,7 +84,8 @@
{:else if data.error === 'oidc_missing_sub'}
Your OIDC provider did not return a subject identifier.
{:else if data.error === 'oidc_email_collision'}
- An account with your email already exists but is linked to a different OIDC identity. Please contact an administrator.
+ An account with your email already exists but is linked to a different OIDC identity.
+ Please contact an administrator.
{:else if data.error === 'oidc_token_error'}
There was an error obtaining tokens from the OIDC provider.
{:else if data.error === 'user_processing_failed'}
@@ -106,14 +109,20 @@
<Alert.Root variant="destructive">
<AlertCircle class="mr-2 size-4" />
<Alert.Title>No Login Methods Configured</Alert.Title>
- <Alert.Description>There are currently no login methods enabled. Please contact an administrator.</Alert.Description>
+ <Alert.Description
+ >There are currently no login methods enabled. Please contact an administrator.</Alert.Description
+ >
</Alert.Root>
{/if}
<!-- OIDC Login Button (when only OIDC is available) -->
{#if showOidcLoginButton && !showLocalLoginForm}
<div class="pt-2">
- <Button onclick={handleOidcLogin} variant="default" class="arcane-button-restart w-full py-6 text-base">
+ <Button
+ onclick={handleOidcLogin}
+ variant="default"
+ class="arcane-button-restart w-full py-6 text-base"
+ >
<LogIn class="mr-3 size-5" />
Sign in with OIDC Provider
</Button>
@@ -128,10 +137,22 @@
<div>
<Label for="username" class="mb-1.5 block text-sm font-medium">Username</Label>
<div class="relative">
- <div class="text-muted-foreground pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
+ <div
+ class="text-muted-foreground pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3"
+ >
<User class="size-4" />
</div>
- <Input id="username" name="username" type="text" autocomplete="username" required bind:value={username} class="pl-10" placeholder="Enter your username or email" disabled={loading} />
+ <Input
+ id="username"
+ name="username"
+ type="text"
+ autocomplete="username"
+ required
+ bind:value={username}
+ class="pl-10"
+ placeholder="Enter your username or email"
+ disabled={loading}
+ />
</div>
</div>
@@ -139,19 +160,38 @@
<div>
<Label for="password" class="mb-1.5 block text-sm font-medium">Password</Label>
<div class="relative">
- <div class="text-muted-foreground pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
+ <div
+ class="text-muted-foreground pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3"
+ >
<Lock class="size-4" />
</div>
- <Input id="password" name="password" type="password" autocomplete="current-password" required bind:value={password} class="pl-10" placeholder="Enter your password" disabled={loading} />
+ <Input
+ id="password"
+ name="password"
+ type="password"
+ autocomplete="current-password"
+ required
+ bind:value={password}
+ class="pl-10"
+ placeholder="Enter your password"
+ disabled={loading}
+ />
</div>
</div>
</div>
<!-- Sign In Button -->
<div class="pt-2">
- <Button type="submit" class="arcane-button-create w-full py-6 text-base" disabled={loading} aria-busy={loading}>
+ <Button
+ type="submit"
+ class="arcane-button-create w-full py-6 text-base"
+ disabled={loading}
+ aria-busy={loading}
+ >
{#if loading}
- <div class="mr-2 size-4 animate-spin rounded-full border-2 border-t-transparent"></div>
+ <div
+ class="mr-2 size-4 animate-spin rounded-full border-2 border-t-transparent"
+ ></div>
{/if}
Sign in
</Button>
@@ -172,7 +212,11 @@
<!-- OIDC Login Button (when both methods are available) -->
{#if showOidcLoginButton && showDivider}
- <Button onclick={handleOidcLogin} variant="outline" class="arcane-button-restart w-full py-5">
+ <Button
+ onclick={handleOidcLogin}
+ variant="outline"
+ class="arcane-button-restart w-full py-5"
+ >
<LogIn class="mr-2 size-4" />
Sign in with OIDC Provider
</Button>
@@ -182,7 +226,12 @@
<!-- Footer Text -->
<p class="text-muted-foreground text-center text-xs">
- <a href="https://github.com/ofkm/arcane" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">View on GitHub</a>
+ <a
+ href="https://github.com/ofkm/arcane"
+ target="_blank"
+ rel="noopener noreferrer"
+ class="text-primary hover:underline">View on GitHub</a
+ >
</p>
</div>
</div>
diff --git a/frontend/src/routes/auth/login/+page.ts b/frontend/src/routes/auth/login/+page.ts
index e55b1e1ad..f262c7228 100644
--- a/frontend/src/routes/auth/login/+page.ts
+++ b/frontend/src/routes/auth/login/+page.ts
@@ -5,11 +5,11 @@ export const load = async ({ parent, url }) => {
// If already authenticated, redirect to dashboard
if (data.user && data.isAuthenticated) {
- throw redirect(302, '/');
+ throw redirect(302, '/dashboard');
}
// Get redirect parameter from URL
- const redirectTo = url.searchParams.get('redirect') || '/';
+ const redirectTo = url.searchParams.get('redirect') || '/dashboard';
// Get error parameter if any
const error = url.searchParams.get('error');
diff --git a/frontend/src/routes/auth/logout/+page.ts b/frontend/src/routes/auth/logout/+page.ts
index a72601d80..1f5d21ad6 100644
--- a/frontend/src/routes/auth/logout/+page.ts
+++ b/frontend/src/routes/auth/logout/+page.ts
@@ -3,17 +3,14 @@ import { browser } from '$app/environment';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({ fetch }) => {
- // Only perform logout on the client side
if (browser) {
try {
- // Call the Go backend logout endpoint
await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'include'
});
} catch (error) {
console.error('Logout error:', error);
- // Continue with redirect even if logout fails
}
}
diff --git a/frontend/src/routes/auth/oidc/callback/+page.svelte b/frontend/src/routes/auth/oidc/callback/+page.svelte
index 40127929c..5f92a4edd 100644
--- a/frontend/src/routes/auth/oidc/callback/+page.svelte
+++ b/frontend/src/routes/auth/oidc/callback/+page.svelte
@@ -5,6 +5,7 @@
import { oidcAPI } from '$lib/services/api';
import { toast } from 'svelte-sonner';
import userStore from '$lib/stores/user-store';
+ import type { User } from '$lib/types/user.type';
let isProcessing = $state(true);
let error = $state('');
@@ -17,32 +18,38 @@
localStorage.removeItem('oidc_redirect');
if (!code || !stateFromUrl) {
- console.error('OIDC callback error: missing code or state in URL.');
error = 'Invalid OIDC response (missing parameters). Please try logging in again.';
setTimeout(() => goto('/auth/login?error=oidc_invalid_response'), 3000);
isProcessing = false;
return;
}
+
const authResult = await oidcAPI.handleCallback(code, stateFromUrl);
if (!authResult.success) {
- console.error('OIDC authentication failed via backend:', authResult.error);
error = authResult.error || 'Authentication failed. Please try again.';
- const errorCode = authResult.error?.toLowerCase().replace(/\s+/g, '_') || 'oidc_auth_failed';
+ const errorCode =
+ authResult.error?.toLowerCase().replace(/\s+/g, '_') || 'oidc_auth_failed';
setTimeout(() => goto(`/auth/login?error=${errorCode}`), 3000);
isProcessing = false;
return;
}
if (authResult.user) {
- const user = {
- id: authResult.user.sub || authResult.user.email,
- username: authResult.user.preferred_username || authResult.user.email,
- email: authResult.user.email,
- roles: (authResult.user as any).roles || [],
- createdAt: new Date().toISOString()
+ const user: User = {
+ ID: authResult.user.sub || authResult.user.email || '',
+ Username: authResult.user.preferred_username || authResult.user.email || '',
+ Email: authResult.user.email,
+ DisplayName:
+ authResult.user.name ||
+ authResult.user.given_name ||
+ authResult.user.preferred_username ||
+ authResult.user.email ||
+ 'User',
+ Roles: ['user'],
+ CreatedAt: new Date().toISOString()
};
- localStorage.setItem('user_data', JSON.stringify(user));
+
userStore.setUser(user);
}
@@ -50,7 +57,6 @@
toast.success('Successfully logged in!');
goto(finalRedirectTo);
} catch (err: any) {
- console.error('🔥 OIDC callback processing error:', err);
error = err.message || 'An error occurred during authentication. Please try again.';
setTimeout(() => goto('/auth/login?error=oidc_generic_error'), 3000);
} finally {
@@ -59,10 +65,6 @@
});
</script>
-<svelte:head>
- <title>Authenticating... - Arcane</title>
-</svelte:head>
-
<div class="flex min-h-screen items-center justify-center bg-gray-50">
<div class="w-full max-w-md space-y-8">
<div class="text-center">
@@ -73,7 +75,12 @@
{:else if error}
<div class="text-red-600">
<svg class="mx-auto h-12 w-12" fill="none" viewBox="0 0 24 24" stroke="currentColor">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.5 0L3.341 16.5c-.77.833.192 2.5 1.732 2.5z" />
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.5 0L3.341 16.5c-.77.833.192 2.5 1.732 2.5z"
+ />
</svg>
<h2 class="mt-6 text-2xl font-bold text-gray-900">Authentication Error</h2>
<p class="mt-2 text-sm text-gray-600">{error}</p>
diff --git a/frontend/src/routes/compose/+page.svelte b/frontend/src/routes/compose/+page.svelte
index 45a134c1d..f20071fc8 100644
--- a/frontend/src/routes/compose/+page.svelte
+++ b/frontend/src/routes/compose/+page.svelte
@@ -1,59 +1,33 @@
<script lang="ts">
import type { PageData } from './$types';
- import * as Card from '$lib/components/ui/card/index.js';
+ import type { Stack } from '$lib/models/stack.type';
import { Button } from '$lib/components/ui/button/index.js';
- import {
- AlertCircle,
- Layers,
- FileStack,
- Loader2,
- Play,
- RotateCcw,
- StopCircle,
- Trash2,
- Ellipsis,
- Pen,
- PlayCircle
- } from '@lucide/svelte';
- import UniversalTable from '$lib/components/universal-table.svelte';
- 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 { AlertCircle, FileStack, Loader2, PlayCircle, StopCircle } from '@lucide/svelte';
import * as Alert from '$lib/components/ui/alert/index.js';
- 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 * as Card from '$lib/components/ui/card/index.js';
import { toast } from 'svelte-sonner';
- import { tryCatch } from '$lib/utils/try-catch';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
- import type { StackActions } from '$lib/types/actions.type';
+ import { tryCatch } from '$lib/utils/try-catch';
import ArcaneButton from '$lib/components/arcane-button.svelte';
- import { tablePersistence } from '$lib/stores/table-store';
- import { formatFriendlyDate } from '$lib/utils/date.utils';
import { autoUpdateAPI, environmentAPI } from '$lib/services/api';
import { onMount } from 'svelte';
- import type { Stack } from '$lib/models/stack.type';
import StatCard from '$lib/components/stat-card.svelte';
+ import StackTable from './compose-table.svelte';
+ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import { goto } from '$app/navigation';
let { data }: { data: PageData } = $props();
- let stacks = $state(<Stack[]>[]);
+ let stacks = $state<Stack[]>(Array.isArray(data.stacks) ? data.stacks : data.stacks.data || []);
let error = $state<string | null>(null);
- let isLoadingStacks = $state(true);
+ let selectedIds = $state<string[]>([]);
+ let isLoadingStacks = $state(false);
+ let requestOptions = $state<SearchPaginationSortRequest>(data.stackRequestOptions);
- const isLoading = $state<
- Record<'start' | 'stop' | 'restart' | 'remove' | 'destroy' | 'pull' | 'update', boolean>
- >({
- start: false,
- stop: false,
- restart: false,
- remove: false,
- destroy: false,
- pull: false,
- update: false
+ let isLoading = $state({
+ updating: false,
+ refreshing: false
});
- const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
const totalStacks = $derived(stacks.length);
const runningStacks = $derived(stacks.filter((s) => s.status === 'running').length);
@@ -62,8 +36,13 @@
async function loadStacks() {
try {
isLoadingStacks = true;
- const response = await environmentAPI.getStacks();
- stacks = response || [];
+ const response = await environmentAPI.getStacks(
+ requestOptions.pagination,
+ requestOptions.sort,
+ requestOptions.search,
+ requestOptions.filters
+ );
+ stacks = Array.isArray(response) ? response : response.data || [];
error = null;
} catch (err) {
console.error('Failed to load compose page:', err);
@@ -75,93 +54,49 @@
}
onMount(() => {
- loadStacks();
+ if (stacks.length === 0) {
+ loadStacks();
+ }
});
- async function performStackAction(action: StackActions, id: string) {
- isLoading[action as keyof typeof isLoading] = true;
-
+ async function refreshStacks() {
+ isLoading.refreshing = true;
try {
- if (action === 'start') {
- handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.startStack(id)),
- message: 'Failed to Start Stack',
- setLoadingState: (value) => (isLoading.start = value),
- onSuccess: async () => {
- toast.success('Stack Started Successfully.');
- await loadStacks();
- }
- });
- } else if (action === 'stop') {
- handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.downStack(id)),
- message: 'Failed to Stop Stack',
- setLoadingState: (value) => (isLoading.stop = value),
- onSuccess: async () => {
- toast.success('Stack Stopped Successfully.');
- await loadStacks();
- }
- });
- } else if (action === 'restart') {
- handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.restartStack(id)),
- message: 'Failed to Restart Stack',
- setLoadingState: (value) => (isLoading.restart = value),
- onSuccess: async () => {
- toast.success('Stack Restarted Successfully.');
- await loadStacks();
- }
- });
- } else if (action === 'pull') {
- handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.pullStackImages(id)),
- message: 'Failed to pull Stack',
- setLoadingState: (value) => (isLoading.pull = value),
- onSuccess: async () => {
- toast.success('Stack Pulled successfully.');
- await loadStacks();
- }
- });
- } 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 () => {
- handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.destroyStack(id)),
- message: 'Failed to Remove Stack',
- setLoadingState: (value) => (isLoading.destroy = value),
- onSuccess: async () => {
- toast.success('Stack Removed Successfully');
- await loadStacks();
- }
- });
- }
- }
- });
- }
+ await loadStacks();
} catch (error) {
- console.error('Stack action failed:', error);
- toast.error('An error occurred while performing the action');
- isLoading[action as keyof typeof isLoading] = false;
+ console.error('Failed to refresh stacks:', error);
+ toast.error('Failed to refresh stacks');
+ } finally {
+ isLoading.refreshing = false;
}
}
async function handleCheckForUpdates() {
- isLoading.update = true;
+ isLoading.updating = true;
handleApiResultWithCallbacks({
result: await tryCatch(autoUpdateAPI.checkStacks()),
message: 'Failed to Check Compose Projects for Updates',
- setLoadingState: (value) => (isLoading.update = value),
+ setLoadingState: (value) => (isLoading.updating = value),
async onSuccess() {
toast.success('Compose Projects Updated Successfully.');
await loadStacks();
}
});
}
+
+ async function onRefresh(options: SearchPaginationSortRequest) {
+ requestOptions = options;
+ await loadStacks();
+ return {
+ data: stacks,
+ pagination: {
+ totalPages: Math.ceil(stacks.length / (requestOptions.pagination?.limit || 20)),
+ totalItems: stacks.length,
+ currentPage: requestOptions.pagination?.page || 1,
+ itemsPerPage: requestOptions.pagination?.limit || 20
+ }
+ };
+ }
</script>
<div class="space-y-6">
@@ -170,6 +105,20 @@
<h1 class="text-3xl font-bold tracking-tight">Compose Projects</h1>
<p class="text-muted-foreground mt-1 text-sm">View and Manage Compose Projects</p>
</div>
+ <div class="flex items-center gap-2">
+ <ArcaneButton
+ action="restart"
+ onClick={refreshStacks}
+ label="Refresh"
+ loading={isLoading.refreshing}
+ disabled={isLoading.refreshing}
+ />
+ <ArcaneButton
+ action="create"
+ customLabel="Create Project"
+ onClick={() => goto(`/compose/new`)}
+ />
+ </div>
</div>
{#if error}
@@ -240,184 +189,13 @@
/>
</div>
- <Card.Root class="border shadow-sm">
- <Card.Header class="px-6">
- <div class="flex items-center justify-between">
- <div>
- <Card.Title>Compose Projects List</Card.Title>
- </div>
- <div class="flex items-center gap-2">
- {#if stacks.length > 0}
- <ArcaneButton
- action="inspect"
- label="Update Compose Projects"
- onClick={() => handleCheckForUpdates()}
- loading={isLoading.update}
- loadingLabel="Updating..."
- disabled={isLoading.update}
- />
- <ArcaneButton
- action="create"
- customLabel="Create Compose Project"
- onClick={() => goto(`/compose/new`)}
- />
- {/if}
- </div>
- </div>
- </Card.Header>
- <Card.Content>
- {#if stacks.length > 0}
- <UniversalTable
- data={stacks}
- columns={[
- { accessorKey: 'name', header: 'Name' },
- { accessorKey: 'service_count', header: 'Services' },
- { accessorKey: 'status', header: 'Status' },
- { accessorKey: 'created_at', header: 'Created' },
- { accessorKey: 'actions', header: ' ', enableSorting: false }
- ]}
- features={{
- selection: false
- }}
- pagination={{
- pageSize: tablePersistence.getPageSize('stacks')
- }}
- onPageSizeChange={(newSize) => {
- tablePersistence.setPageSize('stacks', newSize);
- }}
- sort={{
- defaultSort: { id: 'name', desc: false }
- }}
- display={{
- filterPlaceholder: 'Search compose projects...',
- noResultsMessage: 'No stacks found'
- }}
- >
- {#snippet rows({ item })}
- {@const stateVariant = item.status
- ? statusVariantMap[item.status.toLowerCase()]
- : 'gray'}
- <Table.Cell>
- <a class="font-medium hover:underline" href="/compose/{item.id}/">
- {item.name}
- </a>
- </Table.Cell>
- <Table.Cell>{item.serviceCount || 0}</Table.Cell>
- <Table.Cell
- ><StatusBadge
- variant={stateVariant}
- text={capitalizeFirstLetter(item.status)}
- /></Table.Cell
- >
- <Table.Cell>{formatFriendlyDate(item.createdAt || '')}</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(`/compose/${item.id}`)}
- disabled={isAnyLoading}
- >
- <Pen class="size-4" />
- Edit
- </DropdownMenu.Item>
-
- {#if item.status !== 'running'}
- <DropdownMenu.Item
- onclick={() => performStackAction('start', item.id)}
- disabled={isLoading.start || isAnyLoading}
- >
- {#if isLoading.start}
- <Loader2 class="size-4 animate-spin" />
- {:else}
- <Play class="size-4" />
- {/if}
- Start
- </DropdownMenu.Item>
- {:else}
- <DropdownMenu.Item
- onclick={() => performStackAction('restart', item.id)}
- disabled={isLoading.restart || isAnyLoading}
- >
- {#if isLoading.restart}
- <Loader2 class="size-4 animate-spin" />
- {:else}
- <RotateCcw class="size-4" />
- {/if}
- Restart
- </DropdownMenu.Item>
-
- <DropdownMenu.Item
- onclick={() => performStackAction('stop', item.id)}
- disabled={isLoading.stop || isAnyLoading}
- >
- {#if isLoading.stop}
- <Loader2 class="size-4 animate-spin" />
- {:else}
- <StopCircle class="size-4" />
- {/if}
- Stop
- </DropdownMenu.Item>
- {/if}
-
- <DropdownMenu.Item
- onclick={() => performStackAction('pull', item.id)}
- disabled={isLoading.pull || isAnyLoading}
- >
- {#if isLoading.pull}
- <Loader2 class="size-4 animate-spin" />
- {:else}
- <RotateCcw class="size-4" />
- {/if}
- Pull & Redeploy
- </DropdownMenu.Item>
-
- <DropdownMenu.Separator />
-
- <DropdownMenu.Item
- class="focus:text-red-700! text-red-500"
- onclick={() => performStackAction('destroy', item.id)}
- disabled={isLoading.remove || isAnyLoading}
- >
- {#if isLoading.remove}
- <Loader2 class="size-4 animate-spin" />
- {:else}
- <Trash2 class="size-4" />
- {/if}
- Destroy
- </DropdownMenu.Item>
- </DropdownMenu.Group>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- </Table.Cell>
- {/snippet}
- </UniversalTable>
- {:else if !error}
- <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
- <FileStack class="text-muted-foreground mb-4 size-12 opacity-40" />
- <p class="text-lg font-medium">No Projects found</p>
- <p class="text-muted-foreground mt-1 max-w-md text-sm">
- Create a new stack using the "Create Project" button above
- </p>
- <div class="mt-4 flex gap-3">
- <ArcaneButton
- action="create"
- customLabel="Create Project"
- onClick={() => goto(`/compose/new`)}
- size="sm"
- />
- </div>
- </div>
- {/if}
- </Card.Content>
- </Card.Root>
+ <StackTable
+ {stacks}
+ bind:selectedIds
+ {requestOptions}
+ {onRefresh}
+ onStacksChanged={loadStacks}
+ onCheckForUpdates={handleCheckForUpdates}
+ />
{/if}
</div>
diff --git a/frontend/src/routes/compose/+page.ts b/frontend/src/routes/compose/+page.ts
new file mode 100644
index 000000000..67cd98eb3
--- /dev/null
+++ b/frontend/src/routes/compose/+page.ts
@@ -0,0 +1,25 @@
+import { environmentAPI } from '$lib/services/api';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async () => {
+ const stackRequestOptions: SearchPaginationSortRequest = {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'created_at',
+ direction: 'desc' as const
+ }
+ };
+
+ const stacks = await environmentAPI.getStacks(
+ stackRequestOptions.pagination,
+ stackRequestOptions.sort,
+ stackRequestOptions.search,
+ stackRequestOptions.filters
+ );
+
+ return { stacks, stackRequestOptions };
+};
\ No newline at end of file
diff --git a/frontend/src/routes/compose/[composeId]/+page.svelte b/frontend/src/routes/compose/[composeId]/+page.svelte
index ce07a513a..9545a9065 100644
--- a/frontend/src/routes/compose/[composeId]/+page.svelte
+++ b/frontend/src/routes/compose/[composeId]/+page.svelte
@@ -113,7 +113,7 @@
console.log(
`Stack ID changed from ${currentStackId} to ${updatedStack.id}. Navigating...`
);
- await goto(`/compose/${name}`, { invalidateAll: true });
+ await invalidateAll();
} else {
await invalidateAll();
}
diff --git a/frontend/src/routes/compose/compose-table.svelte b/frontend/src/routes/compose/compose-table.svelte
new file mode 100644
index 000000000..f12fef808
--- /dev/null
+++ b/frontend/src/routes/compose/compose-table.svelte
@@ -0,0 +1,313 @@
+<script lang="ts">
+ import type { Stack } from '$lib/models/stack.type';
+ import ArcaneTable from '$lib/components/arcane-table.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import {
+ Trash2,
+ Loader2,
+ Ellipsis,
+ Pen,
+ Play,
+ RotateCcw,
+ StopCircle,
+ FileStack
+ } from '@lucide/svelte';
+ import * as Card from '$lib/components/ui/card/index.js';
+ import { goto } from '$app/navigation';
+ import { toast } from 'svelte-sonner';
+ 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 StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import ArcaneButton from '$lib/components/arcane-button.svelte';
+ import { environmentAPI } from '$lib/services/api';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import { statusVariantMap } from '$lib/types/statuses';
+ import { capitalizeFirstLetter } from '$lib/utils/string.utils';
+ import { formatFriendlyDate } from '$lib/utils/date.utils';
+
+ interface StackWithId extends Stack {
+ id: string;
+ }
+
+ let {
+ stacks,
+ selectedIds = $bindable(),
+ requestOptions = $bindable(),
+ onRefresh,
+ onStacksChanged,
+ onCheckForUpdates
+ }: {
+ stacks: Stack[];
+ selectedIds: string[];
+ requestOptions: SearchPaginationSortRequest;
+ onRefresh: (options: SearchPaginationSortRequest) => Promise<any>;
+ onStacksChanged: () => Promise<void>;
+ onCheckForUpdates: () => Promise<void>;
+ } = $props();
+
+ let isLoading = $state({
+ start: false,
+ stop: false,
+ restart: false,
+ remove: false,
+ destroy: false,
+ pull: false,
+ updating: false
+ });
+
+ const stacksWithId = $derived(
+ stacks.map((stack) => ({
+ ...stack,
+ id: stack.id || stack.name
+ }))
+ );
+
+ const paginatedStacks: Paginated<StackWithId> = $derived({
+ data: stacksWithId,
+ pagination: {
+ totalPages: Math.ceil(stacksWithId.length / (requestOptions.pagination?.limit || 20)),
+ totalItems: stacksWithId.length,
+ currentPage: requestOptions.pagination?.page || 1,
+ itemsPerPage: requestOptions.pagination?.limit || 20
+ }
+ });
+
+ async function performStackAction(action: string, id: string) {
+ isLoading[action as keyof typeof isLoading] = true;
+
+ try {
+ if (action === 'start') {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.startStack(id)),
+ message: 'Failed to Start Stack',
+ setLoadingState: (value) => (isLoading.start = value),
+ onSuccess: async () => {
+ toast.success('Stack Started Successfully.');
+ await onStacksChanged();
+ }
+ });
+ } else if (action === 'stop') {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.downStack(id)),
+ message: 'Failed to Stop Stack',
+ setLoadingState: (value) => (isLoading.stop = value),
+ onSuccess: async () => {
+ toast.success('Stack Stopped Successfully.');
+ await onStacksChanged();
+ }
+ });
+ } else if (action === 'restart') {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.restartStack(id)),
+ message: 'Failed to Restart Stack',
+ setLoadingState: (value) => (isLoading.restart = value),
+ onSuccess: async () => {
+ toast.success('Stack Restarted Successfully.');
+ await onStacksChanged();
+ }
+ });
+ } else if (action === 'pull') {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.pullStackImages(id)),
+ message: 'Failed to pull Stack',
+ setLoadingState: (value) => (isLoading.pull = value),
+ onSuccess: async () => {
+ toast.success('Stack Pulled successfully.');
+ await onStacksChanged();
+ }
+ });
+ } 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 () => {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.destroyStack(id)),
+ message: 'Failed to Remove Stack',
+ setLoadingState: (value) => (isLoading.destroy = value),
+ onSuccess: async () => {
+ toast.success('Stack Removed Successfully');
+ await onStacksChanged();
+ }
+ });
+ }
+ }
+ });
+ }
+ } catch (error) {
+ console.error('Stack action failed:', error);
+ toast.error('An error occurred while performing the action');
+ isLoading[action as keyof typeof isLoading] = false;
+ }
+ }
+
+ const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
+</script>
+
+{#if stacksWithId.length > 0}
+ <Card.Root class="border shadow-sm">
+ <Card.Header class="px-6">
+ <div class="flex items-center justify-between">
+ <div>
+ <Card.Title>Compose Projects List</Card.Title>
+ </div>
+ <div class="flex items-center gap-2">
+ <ArcaneButton
+ action="inspect"
+ label="Update Compose Projects"
+ onClick={onCheckForUpdates}
+ loading={isLoading.updating}
+ loadingLabel="Updating..."
+ disabled={isLoading.updating}
+ />
+ <ArcaneButton
+ action="create"
+ customLabel="Create Compose Project"
+ onClick={() => goto(`/compose/new`)}
+ />
+ </div>
+ </div>
+ </Card.Header>
+ <Card.Content>
+ <ArcaneTable
+ items={paginatedStacks}
+ bind:requestOptions
+ bind:selectedIds
+ {onRefresh}
+ columns={[
+ { label: 'Name', sortColumn: 'name' },
+ { label: 'Services', sortColumn: 'service_count' },
+ { label: 'Status', sortColumn: 'status' },
+ { label: 'Created', sortColumn: 'created_at' },
+ { label: ' ' }
+ ]}
+ filterPlaceholder="Search projects..."
+ noResultsMessage="No projects found"
+ >
+ {#snippet rows({ item })}
+ {@const stateVariant = item.status ? statusVariantMap[item.status.toLowerCase()] : 'gray'}
+ <Table.Cell>
+ <a class="font-medium hover:underline" href="/compose/{item.id}/">
+ {item.name}
+ </a>
+ </Table.Cell>
+ <Table.Cell>{item.serviceCount || 0}</Table.Cell>
+ <Table.Cell>
+ <StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.status)} />
+ </Table.Cell>
+ <Table.Cell>{formatFriendlyDate(item.createdAt || '')}</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(`/compose/${item.id}`)}
+ disabled={isAnyLoading}
+ >
+ <Pen class="size-4" />
+ Edit
+ </DropdownMenu.Item>
+
+ {#if item.status !== 'running'}
+ <DropdownMenu.Item
+ onclick={() => performStackAction('start', item.id)}
+ disabled={isLoading.start || isAnyLoading}
+ >
+ {#if isLoading.start}
+ <Loader2 class="size-4 animate-spin" />
+ {:else}
+ <Play class="size-4" />
+ {/if}
+ Start
+ </DropdownMenu.Item>
+ {:else}
+ <DropdownMenu.Item
+ onclick={() => performStackAction('restart', item.id)}
+ disabled={isLoading.restart || isAnyLoading}
+ >
+ {#if isLoading.restart}
+ <Loader2 class="size-4 animate-spin" />
+ {:else}
+ <RotateCcw class="size-4" />
+ {/if}
+ Restart
+ </DropdownMenu.Item>
+
+ <DropdownMenu.Item
+ onclick={() => performStackAction('stop', item.id)}
+ disabled={isLoading.stop || isAnyLoading}
+ >
+ {#if isLoading.stop}
+ <Loader2 class="size-4 animate-spin" />
+ {:else}
+ <StopCircle class="size-4" />
+ {/if}
+ Stop
+ </DropdownMenu.Item>
+ {/if}
+
+ <DropdownMenu.Item
+ onclick={() => performStackAction('pull', item.id)}
+ disabled={isLoading.pull || isAnyLoading}
+ >
+ {#if isLoading.pull}
+ <Loader2 class="size-4 animate-spin" />
+ {:else}
+ <RotateCcw class="size-4" />
+ {/if}
+ Pull & Redeploy
+ </DropdownMenu.Item>
+
+ <DropdownMenu.Separator />
+
+ <DropdownMenu.Item
+ class="focus:text-red-700! text-red-500"
+ onclick={() => performStackAction('destroy', item.id)}
+ disabled={isLoading.remove || isAnyLoading}
+ >
+ {#if isLoading.remove}
+ <Loader2 class="size-4 animate-spin" />
+ {:else}
+ <Trash2 class="size-4" />
+ {/if}
+ Destroy
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </ArcaneTable>
+ </Card.Content>
+ </Card.Root>
+{:else}
+ <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
+ <FileStack class="text-muted-foreground mb-4 size-12 opacity-40" />
+ <p class="text-lg font-medium">No Projects found</p>
+ <p class="text-muted-foreground mt-1 max-w-md text-sm">
+ Create a new stack using the "Create Project" button above
+ </p>
+ <div class="mt-4 flex gap-3">
+ <ArcaneButton
+ action="create"
+ customLabel="Create Project"
+ onClick={() => goto(`/compose/new`)}
+ size="sm"
+ />
+ </div>
+ </div>
+{/if}
diff --git a/frontend/src/routes/compose/new/+page.svelte b/frontend/src/routes/compose/new/+page.svelte
index a22fdbba9..c9103349a 100644
--- a/frontend/src/routes/compose/new/+page.svelte
+++ b/frontend/src/routes/compose/new/+page.svelte
@@ -43,7 +43,7 @@
onSuccess: async (stack) => {
toast.success(`Stack "${name}" created successfully.`);
await invalidateAll();
- goto(`/compose/${stack.name}`);
+ goto(`/compose/${stack.id}`);
}
});
}
diff --git a/frontend/src/routes/containers/+page.svelte b/frontend/src/routes/containers/+page.svelte
index 51dc9722e..ae0a0eab0 100644
--- a/frontend/src/routes/containers/+page.svelte
+++ b/frontend/src/routes/containers/+page.svelte
@@ -1,56 +1,33 @@
<script lang="ts">
- import {
- ScanSearch,
- Play,
- RotateCcw,
- StopCircle,
- Trash2,
- Loader2,
- 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 UniversalTable from '$lib/components/universal-table.svelte';
- 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 { Box } from '@lucide/svelte';
import CreateContainerSheet from '$lib/components/sheets/create-container-sheet.svelte';
- import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
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 { handleApiResultWithCallbacks } from '$lib/utils/api.util';
- import { shortId } from '$lib/utils/string.utils';
import type { PageData } from './$types';
- import ArcaneButton from '$lib/components/arcane-button.svelte';
- import { tablePersistence } from '$lib/stores/table-store';
import StatCard from '$lib/components/stat-card.svelte';
- import { parseStatusTime } from '$lib/utils/string.utils';
- import type { ContainerInfo } from 'dockerode';
+ import type { ContainerInfo } from '$lib/models/container-info';
import { autoUpdateAPI, environmentAPI } from '$lib/services/api';
- import { onMount } from 'svelte';
+ import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
+ import ContainerTable from './container-table.svelte';
+
+ interface ContainerWithId extends ContainerInfo {
+ id: string;
+ }
let { data }: { data: PageData } = $props();
let containers = $state<ContainerInfo[]>([]);
- let isLoadingContainers = $state(true);
+ let paginatedContainers = $state<Paginated<ContainerWithId> | null>(null);
let selectedIds = $state([]);
let isCreateDialogOpen = $state(false);
let isLoading = $state({
- start: false,
- stop: false,
- restart: false,
- remove: false,
checking: false,
- create: false
+ create: false,
+ refreshing: false
});
- const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
const runningContainers = $derived(
containers?.filter((c: ContainerInfo) => c.State === 'running').length || 0
);
@@ -59,95 +36,79 @@
);
const totalContainers = $derived(containers?.length || 0);
- function getContainerDisplayName(container: ContainerInfo): string {
- if (container.Names && container.Names.length > 0) {
- return container.Names[0].startsWith('/')
- ? container.Names[0].substring(1)
- : container.Names[0];
+ let requestOptions = $state<SearchPaginationSortRequest>(data.containerRequestOptions);
+
+ $effect(() => {
+ if (data.containers) {
+ if (Array.isArray(data.containers)) {
+ containers = data.containers;
+ const paginatedData: Paginated<ContainerWithId> = {
+ data: data.containers.map((c) => ({ ...c, id: c.Id })),
+ pagination: {
+ totalPages: 1,
+ totalItems: data.containers.length,
+ currentPage: 1,
+ itemsPerPage: data.containers.length
+ }
+ };
+ paginatedContainers = paginatedData;
+ } else {
+ const paginatedData: Paginated<ContainerWithId> = {
+ data: data.containers.data.map((c) => ({ ...c, id: c.Id })),
+ pagination: data.containers.pagination
+ };
+ paginatedContainers = paginatedData;
+ containers = data.containers.data || [];
+ }
}
- return shortId(container.Id);
- }
+ });
- async function loadContainers() {
- try {
- isLoadingContainers = true;
- const response = await environmentAPI.getContainers();
- containers = response || [];
- } catch (error) {
- console.error('Failed to load containers:', error);
- containers = [];
- } finally {
- isLoadingContainers = false;
+ async function onRefresh(
+ options: SearchPaginationSortRequest
+ ): Promise<Paginated<ContainerWithId>> {
+ const response = await environmentAPI.getContainers(
+ options.pagination,
+ options.sort,
+ options.search,
+ options.filters
+ );
+
+ if (Array.isArray(response)) {
+ containers = response;
+ const paginatedResponse: Paginated<ContainerWithId> = {
+ data: response.map((c) => ({ ...c, id: c.Id })),
+ pagination: {
+ totalPages: 1,
+ totalItems: response.length,
+ currentPage: options.pagination?.page || 1,
+ itemsPerPage: response.length
+ }
+ };
+ paginatedContainers = paginatedResponse;
+ return paginatedResponse;
+ } else {
+ const paginatedResponse: Paginated<ContainerWithId> = {
+ data: response.data.map((c) => ({ ...c, id: c.Id })),
+ pagination: response.pagination
+ };
+ paginatedContainers = paginatedResponse;
+ containers = response.data || [];
+ return paginatedResponse;
}
}
- onMount(() => {
- loadContainers();
- });
-
- async function performContainerAction(action: string, id: string) {
- isLoading[action as keyof typeof isLoading] = true;
-
+ async function refreshContainers() {
+ isLoading.refreshing = true;
try {
- if (action === 'start') {
- handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.startContainer(id)),
- message: 'Failed to Start Container',
- setLoadingState: (value) => (isLoading.start = value),
- async onSuccess() {
- toast.success('Container Started Successfully.');
- await loadContainers();
- }
- });
- } else if (action === 'stop') {
- handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.stopContainer(id)),
- message: 'Failed to Stop Container',
- setLoadingState: (value) => (isLoading.stop = value),
- async onSuccess() {
- toast.success('Container Stopped Successfully.');
- await loadContainers();
- }
- });
- } else if (action === 'restart') {
- handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.restartContainer(id)),
- message: 'Failed to Restart Container',
- setLoadingState: (value) => (isLoading.restart = value),
- async onSuccess() {
- toast.success('Container Restarted Successfully.');
- await loadContainers();
- }
- });
- }
+ await onRefresh(requestOptions);
} catch (error) {
- console.error('Container action failed:', error);
- isLoading[action as keyof typeof isLoading] = false;
+ console.error('Failed to refresh containers:', error);
+ toast.error('Failed to refresh containers');
+ } finally {
+ isLoading.refreshing = false;
}
}
- async function handleRemoveContainer(id: string) {
- openConfirmDialog({
- title: 'Confirm Container Removal',
- message: 'Are you sure you want to remove this container? This action cannot be undone.',
- confirm: {
- label: 'Remove',
- destructive: true,
- action: async () => {
- handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.deleteContainer(id)),
- message: 'Failed to Remove Container',
- setLoadingState: (value) => (isLoading.remove = value),
- async onSuccess() {
- toast.success('Container Removed Successfully.');
- await loadContainers();
- }
- });
- }
- }
- });
- }
-
async function handleCheckForUpdates() {
isLoading.checking = true;
handleApiResultWithCallbacks({
@@ -156,13 +117,13 @@
setLoadingState: (value) => (isLoading.checking = value),
async onSuccess() {
toast.success('Containers Updated Successfully.');
- await loadContainers();
+ await refreshContainers();
}
});
}
- function openCreateDialog() {
- isCreateDialogOpen = true;
+ async function onContainersChanged() {
+ await refreshContainers();
}
</script>
@@ -174,256 +135,65 @@
</div>
</div>
- {#if isLoadingContainers}
- <div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
- {#each Array(3) as _}
- <Card.Root>
- <Card.Content class="flex items-center justify-between p-4">
- <div class="space-y-2">
- <div class="bg-muted h-4 w-24 animate-pulse rounded"></div>
- <div class="bg-muted h-8 w-12 animate-pulse rounded"></div>
- </div>
- <div class="bg-muted size-10 animate-pulse rounded-full"></div>
- </Card.Content>
- </Card.Root>
- {/each}
- </div>
-
- <Card.Root class="border shadow-sm">
- <Card.Header class="px-6">
- <div class="flex items-center justify-between">
- <div>
- <Card.Title>Container List</Card.Title>
- </div>
- <div class="flex items-center gap-2">
- <div class="bg-muted h-9 w-32 animate-pulse rounded"></div>
- <div class="bg-muted h-9 w-28 animate-pulse rounded"></div>
- </div>
- </div>
- </Card.Header>
- <Card.Content>
- <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
- <Loader2 class="text-muted-foreground mb-4 size-8 animate-spin" />
- <p class="text-lg font-medium">Loading Containers...</p>
- <p class="text-muted-foreground mt-1 text-sm">
- Please wait while we fetch your containers
- </p>
- </div>
- </Card.Content>
- </Card.Root>
- {:else}
- <div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
- <StatCard
- title="Total"
- value={totalContainers}
- icon={Box}
- class="border-l-primary border-l-4 transition-shadow hover:shadow-lg"
- />
- <StatCard
- title="Running"
- value={runningContainers}
- icon={Box}
- iconColor="text-green-500"
- bgColor="bg-green-500/10"
- class="border-l-4 border-l-green-500"
- />
- <StatCard
- title="Stopped"
- value={stoppedContainers}
- icon={Box}
- iconColor="text-amber-500"
- class="border-l-4 border-l-amber-500"
- />
- </div>
-
- {#if containers?.length === 0}
- <div
- class="bg-card flex flex-col items-center justify-center rounded-lg border px-6 py-12 text-center"
- >
- <Box class="text-muted-foreground mb-4 size-12 opacity-40" />
- <p class="text-lg font-medium">No containers found</p>
- <p class="text-muted-foreground mt-1 max-w-md text-sm">
- Create a new container using the "Create Container" button above or use the Docker CLI
- </p>
- <div class="mt-4 flex gap-3">
- <Button variant="secondary" onclick={loadContainers}>
- <RefreshCw class="size-4" />
- Refresh
- </Button>
- <ArcaneButton action="create" label="Create Container" onClick={openCreateDialog} />
- </div>
- </div>
- {:else}
- <Card.Root class="border shadow-sm">
- <Card.Header class="px-6">
- <div class="flex items-center justify-between">
- <div>
- <Card.Title>Container List</Card.Title>
- </div>
- <div class="flex items-center gap-2">
- <ArcaneButton
- action="inspect"
- label="Update Containers"
- onClick={() => handleCheckForUpdates()}
- loading={isLoading.checking}
- loadingLabel="Updating..."
- disabled={isLoading.checking}
- />
- <ArcaneButton action="create" label="Create Container" onClick={openCreateDialog} />
- </div>
- </div>
- </Card.Header>
- <Card.Content>
- <UniversalTable
- data={containers.map((c: any) => ({
- ...c,
- displayName: getContainerDisplayName(c),
- statusSortValue: parseStatusTime(c.Status)
- }))}
- columns={[
- { accessorKey: 'displayName', header: 'Name' },
- { accessorKey: 'Id', header: 'ID' },
- { accessorKey: 'Image', header: 'Image' },
- { accessorKey: 'State', header: 'State' },
- { accessorKey: 'statusSortValue', header: 'Status' },
- { accessorKey: 'actions', header: ' ', enableSorting: false }
- ]}
- features={{
- selection: false
- }}
- pagination={{
- pageSize: tablePersistence.getPageSize('containers')
- }}
- onPageSizeChange={(newSize) => {
- tablePersistence.setPageSize('containers', newSize);
- }}
- sort={{
- defaultSort: { id: 'displayName', desc: false }
- }}
- display={{
- filterPlaceholder: 'Search containers...',
- noResultsMessage: 'No containers found'
- }}
- bind:selectedIds
- >
- {#snippet rows({
- item
- }: {
- item: ContainerInfo & { displayName: string; statusSortValue: number };
- })}
- {@const stateVariant = statusVariantMap[item.State.toLowerCase()]}
- <Table.Cell
- ><a class="font-medium hover:underline" href="/containers/{item.Id}/"
- >{item.displayName}</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="size-4" />
- Inspect
- </DropdownMenu.Item>
-
- {#if item.State !== 'running'}
- <DropdownMenu.Item
- onclick={() => performContainerAction('start', item.Id)}
- disabled={isLoading.start || isAnyLoading}
- >
- {#if isLoading.start}
- <Loader2 class="size-4 animate-spin" />
- {:else}
- <Play class="size-4" />
- {/if}
- Start
- </DropdownMenu.Item>
- {:else}
- <DropdownMenu.Item
- onclick={() => performContainerAction('restart', item.Id)}
- disabled={isLoading.restart || isAnyLoading}
- >
- {#if isLoading.restart}
- <Loader2 class="size-4 animate-spin" />
- {:else}
- <RotateCcw class="size-4" />
- {/if}
- Restart
- </DropdownMenu.Item>
-
- <DropdownMenu.Item
- onclick={() => performContainerAction('stop', item.Id)}
- disabled={isLoading.stop || isAnyLoading}
- >
- {#if isLoading.stop}
- <Loader2 class="size-4 animate-spin" />
- {:else}
- <StopCircle class="size-4" />
- {/if}
- Stop
- </DropdownMenu.Item>
- {/if}
-
- <DropdownMenu.Separator />
-
- <DropdownMenu.Item
- class="focus:text-red-700! text-red-500"
- onclick={() => handleRemoveContainer(item.Id)}
- disabled={isLoading.remove || isAnyLoading}
- >
- {#if isLoading.remove}
- <Loader2 class="size-4 animate-spin" />
- {:else}
- <Trash2 class="size-4" />
- {/if}
- Remove
- </DropdownMenu.Item>
- </DropdownMenu.Group>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- </Table.Cell>
- {/snippet}
- </UniversalTable>
- </Card.Content>
- </Card.Root>
- {/if}
-
- <CreateContainerSheet
- bind:open={isCreateDialogOpen}
- availableVolumes={[]}
- availableNetworks={[]}
- availableImages={[]}
- isLoading={isLoading.create}
- onSubmit={async (options) => {
- isLoading.create = true;
- handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.createContainer(options)),
- message: 'Failed to Create Container',
- setLoadingState: (value) => (isLoading.create = value),
- onSuccess: async () => {
- toast.success('Container Created Successfully.');
- await loadContainers();
- isCreateDialogOpen = false;
- }
- });
- }}
+ <div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
+ <StatCard
+ title="Total"
+ value={totalContainers}
+ icon={Box}
+ class="border-l-primary border-l-4 transition-shadow hover:shadow-lg"
+ />
+ <StatCard
+ title="Running"
+ value={runningContainers}
+ icon={Box}
+ iconColor="text-green-500"
+ bgColor="bg-green-500/10"
+ class="border-l-4 border-l-green-500"
+ />
+ <StatCard
+ title="Stopped"
+ value={stoppedContainers}
+ icon={Box}
+ iconColor="text-amber-500"
+ class="border-l-4 border-l-amber-500"
/>
- {/if}
+ </div>
+
+ <ContainerTable
+ containers={paginatedContainers || {
+ data: containers.map((c) => ({ ...c, id: c.Id })),
+ pagination: {
+ totalPages: 1,
+ totalItems: containers.length,
+ currentPage: 1,
+ itemsPerPage: containers.length
+ }
+ }}
+ bind:selectedIds
+ bind:requestOptions
+ {onRefresh}
+ {onContainersChanged}
+ onCheckForUpdates={handleCheckForUpdates}
+ />
+
+ <CreateContainerSheet
+ bind:open={isCreateDialogOpen}
+ availableVolumes={[]}
+ availableNetworks={[]}
+ availableImages={[]}
+ isLoading={isLoading.create}
+ onSubmit={async (options) => {
+ isLoading.create = true;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.createContainer(options)),
+ message: 'Failed to Create Container',
+ setLoadingState: (value) => (isLoading.create = value),
+ onSuccess: async () => {
+ toast.success('Container Created Successfully.');
+ await refreshContainers();
+ isCreateDialogOpen = false;
+ }
+ });
+ }}
+ />
</div>
diff --git a/frontend/src/routes/containers/+page.ts b/frontend/src/routes/containers/+page.ts
new file mode 100644
index 000000000..0e2b26cf7
--- /dev/null
+++ b/frontend/src/routes/containers/+page.ts
@@ -0,0 +1,25 @@
+import { environmentAPI } from '$lib/services/api';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async () => {
+ const containerRequestOptions: SearchPaginationSortRequest = {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'created',
+ direction: 'desc' as const
+ }
+ };
+
+ const containers = await environmentAPI.getContainers(
+ containerRequestOptions.pagination,
+ containerRequestOptions.sort,
+ containerRequestOptions.search,
+ containerRequestOptions.filters
+ );
+
+ return { containers, containerRequestOptions };
+};
\ No newline at end of file
diff --git a/frontend/src/routes/containers/[containerId]/+page.svelte b/frontend/src/routes/containers/[containerId]/+page.svelte
index cf3c3c545..5cf9ebc01 100644
--- a/frontend/src/routes/containers/[containerId]/+page.svelte
+++ b/frontend/src/routes/containers/[containerId]/+page.svelte
@@ -2,7 +2,19 @@
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, Settings, Activity, FileText, Database } from '@lucide/svelte';
+ import {
+ ArrowLeft,
+ AlertCircle,
+ RefreshCw,
+ HardDrive,
+ Clock,
+ Network,
+ Terminal,
+ Settings,
+ Activity,
+ FileText,
+ Database
+ } from '@lucide/svelte';
import { invalidateAll } from '$app/navigation';
import { Badge } from '$lib/components/ui/badge/index.js';
import ActionButtons from '$lib/components/action-buttons.svelte';
@@ -13,7 +25,7 @@
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import { onDestroy } from 'svelte';
import LogViewer from '$lib/components/LogViewer.svelte';
- import Meter from '$lib/components/meter.svelte';
+ import Meter from '$lib/components/ui/meter/meter.svelte';
interface NetworkConfig {
IPAddress?: string;
@@ -31,6 +43,7 @@
let { data }: { data: PageData } = $props();
let { container, stats } = $derived(data);
+ console.log(data);
let starting = $state(false);
let stopping = $state(false);
@@ -113,9 +126,13 @@
return 0;
}
- const cpuDelta = statsData.cpu_stats.cpu_usage.total_usage - (statsData.precpu_stats.cpu_usage?.total_usage || 0);
- const systemDelta = statsData.cpu_stats.system_cpu_usage - (statsData.precpu_stats.system_cpu_usage || 0);
- const numberCPUs = statsData.cpu_stats.online_cpus || statsData.cpu_stats.cpu_usage?.percpu_usage?.length || 1;
+ const cpuDelta =
+ statsData.cpu_stats.cpu_usage.total_usage -
+ (statsData.precpu_stats.cpu_usage?.total_usage || 0);
+ const systemDelta =
+ statsData.cpu_stats.system_cpu_usage - (statsData.precpu_stats.system_cpu_usage || 0);
+ const numberCPUs =
+ statsData.cpu_stats.online_cpus || statsData.cpu_stats.cpu_usage?.percpu_usage?.length || 1;
if (systemDelta > 0 && cpuDelta > 0) {
const cpuPercent = (cpuDelta / systemDelta) * numberCPUs * 100.0;
@@ -129,9 +146,13 @@
const memoryLimitBytes = $derived(stats?.memory_stats?.limit || 0);
const memoryUsageFormatted = $derived(formatBytes(memoryUsageBytes));
const memoryLimitFormatted = $derived(formatBytes(memoryLimitBytes));
- const memoryUsagePercent = $derived(memoryLimitBytes > 0 ? (memoryUsageBytes / memoryLimitBytes) * 100 : 0);
+ const memoryUsagePercent = $derived(
+ memoryLimitBytes > 0 ? (memoryUsageBytes / memoryLimitBytes) * 100 : 0
+ );
- const getPrimaryIpAddress = (networkSettings: ContainerInspectInfo['NetworkSettings'] | undefined | null): string => {
+ const getPrimaryIpAddress = (
+ networkSettings: ContainerInspectInfo['NetworkSettings'] | undefined | null
+ ): string => {
if (!networkSettings) return 'N/A';
if (networkSettings.IPAddress) {
@@ -222,7 +243,14 @@
{containerDisplayName}
</h1>
{#if container?.State}
- <StatusBadge variant={container.State.Status === 'running' ? 'green' : container.State.Status === 'exited' ? 'red' : 'amber'} text={container.State.Status} />
+ <StatusBadge
+ variant={container.State.Status === 'running'
+ ? 'green'
+ : container.State.Status === 'exited'
+ ? 'red'
+ : 'amber'}
+ text={container.State.Status}
+ />
{/if}
</div>
</div>
@@ -260,7 +288,9 @@
<button
onclick={() => scrollToSection(section.id)}
class="flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors
- {activeSection === section.id ? 'bg-primary/10 text-primary border-primary/20 border' : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'}"
+ {activeSection === section.id
+ ? 'bg-primary/10 text-primary border-primary/20 border'
+ : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'}"
>
<IconComponent class="size-4 shrink-0" />
<span class="truncate">{section.label}</span>
@@ -343,9 +373,29 @@
</Card.Header>
<Card.Content class="space-y-6">
{#if stats && container.State?.Running}
- <Meter label="CPU Usage" valueLabel="{cpuUsagePercent.toFixed(1)}%" value={cpuUsagePercent} max={100} variant={cpuUsagePercent > 80 ? 'destructive' : cpuUsagePercent > 60 ? 'warning' : 'default'} />
-
- <Meter label="Memory Usage" valueLabel="{memoryUsageFormatted} / {memoryLimitFormatted}" value={memoryUsagePercent} max={100} variant={memoryUsagePercent > 80 ? 'destructive' : memoryUsagePercent > 60 ? 'warning' : 'default'} />
+ <Meter
+ label="CPU Usage"
+ valueLabel="{cpuUsagePercent.toFixed(1)}%"
+ value={cpuUsagePercent}
+ max={100}
+ variant={cpuUsagePercent > 80
+ ? 'destructive'
+ : cpuUsagePercent > 60
+ ? 'warning'
+ : 'default'}
+ />
+
+ <Meter
+ label="Memory Usage"
+ valueLabel="{memoryUsageFormatted} / {memoryLimitFormatted}"
+ value={memoryUsagePercent}
+ max={100}
+ variant={memoryUsagePercent > 80
+ ? 'destructive'
+ : memoryUsagePercent > 60
+ ? 'warning'
+ : 'default'}
+ />
{:else}
<div class="text-muted-foreground py-8 text-center">
{container.State?.Running ? 'Loading stats...' : 'Container not running'}
@@ -388,10 +438,19 @@
<div>
<div class="text-muted-foreground mb-2 text-sm">Health Status</div>
<div class="flex items-center gap-3">
- <StatusBadge variant={container.State.Health.Status === 'healthy' ? 'green' : container.State.Health.Status === 'unhealthy' ? 'red' : 'amber'} text={container.State.Health.Status} />
+ <StatusBadge
+ variant={container.State.Health.Status === 'healthy'
+ ? 'green'
+ : container.State.Health.Status === 'unhealthy'
+ ? 'red'
+ : 'amber'}
+ text={container.State.Health.Status}
+ />
{#if container.State.Health.Log && container.State.Health.Log.length > 0}
<span class="text-muted-foreground text-sm">
- Last check: {new Date(container.State.Health.Log[0].Start).toLocaleString()}
+ Last check: {new Date(
+ container.State.Health.Log[0].Start
+ ).toLocaleString()}
</span>
{/if}
</div>
@@ -414,9 +473,33 @@
<div class="grid grid-cols-1 gap-8 lg:grid-cols-2">
<!-- CPU and Memory -->
<div class="space-y-6">
- <Meter label="CPU Usage" valueLabel="{cpuUsagePercent.toFixed(2)}%" value={cpuUsagePercent} max={100} variant={cpuUsagePercent > 80 ? 'destructive' : cpuUsagePercent > 60 ? 'warning' : 'default'} size="lg" />
-
- <Meter label="Memory Usage" valueLabel="{memoryUsageFormatted} / {memoryLimitFormatted} ({memoryUsagePercent.toFixed(1)}%)" value={memoryUsagePercent} max={100} variant={memoryUsagePercent > 80 ? 'destructive' : memoryUsagePercent > 60 ? 'warning' : 'default'} size="lg" />
+ <Meter
+ label="CPU Usage"
+ valueLabel="{cpuUsagePercent.toFixed(2)}%"
+ value={cpuUsagePercent}
+ max={100}
+ variant={cpuUsagePercent > 80
+ ? 'destructive'
+ : cpuUsagePercent > 60
+ ? 'warning'
+ : 'default'}
+ size="lg"
+ />
+
+ <Meter
+ label="Memory Usage"
+ valueLabel="{memoryUsageFormatted} / {memoryLimitFormatted} ({memoryUsagePercent.toFixed(
+ 1
+ )}%)"
+ value={memoryUsagePercent}
+ max={100}
+ variant={memoryUsagePercent > 80
+ ? 'destructive'
+ : memoryUsagePercent > 60
+ ? 'warning'
+ : 'default'}
+ size="lg"
+ />
</div>
<!-- Network I/O -->
@@ -448,13 +531,21 @@
<div class="bg-muted/30 rounded p-4">
<div class="text-muted-foreground text-sm">Read</div>
<div class="mt-1 font-medium">
- {formatBytes(stats.blkio_stats.io_service_bytes_recursive.filter((item) => item.op === 'Read').reduce((acc, item) => acc + item.value, 0))}
+ {formatBytes(
+ stats.blkio_stats.io_service_bytes_recursive
+ .filter((item) => item.op === 'Read')
+ .reduce((acc, item) => acc + item.value, 0)
+ )}
</div>
</div>
<div class="bg-muted/30 rounded p-4">
<div class="text-muted-foreground text-sm">Write</div>
<div class="mt-1 font-medium">
- {formatBytes(stats.blkio_stats.io_service_bytes_recursive.filter((item) => item.op === 'Write').reduce((acc, item) => acc + item.value, 0))}
+ {formatBytes(
+ stats.blkio_stats.io_service_bytes_recursive
+ .filter((item) => item.op === 'Write')
+ .reduce((acc, item) => acc + item.value, 0)
+ )}
</div>
</div>
</div>
@@ -472,7 +563,9 @@
</div>
{/if}
{:else if !container.State?.Running}
- <div class="text-muted-foreground py-12 text-center">Container is not running. Stats unavailable.</div>
+ <div class="text-muted-foreground py-12 text-center">
+ Container is not running. Stats unavailable.
+ </div>
{:else}
<div class="text-muted-foreground py-12 text-center">Loading stats...</div>
{/if}
@@ -492,22 +585,43 @@
<input type="checkbox" bind:checked={autoScrollLogs} class="size-4" />
Auto-scroll
</label>
- <Button variant="outline" size="sm" onclick={() => logViewer?.clearLogs()}>Clear</Button>
+ <Button variant="outline" size="sm" onclick={() => logViewer?.clearLogs()}
+ >Clear</Button
+ >
{#if isStreaming}
<div class="flex items-center gap-2">
<div class="size-2 animate-pulse rounded-full bg-green-500"></div>
<span class="text-sm font-medium text-green-600">Live</span>
</div>
- <Button variant="outline" size="sm" onclick={() => logViewer?.stopLogStream()}>Stop</Button>
+ <Button variant="outline" size="sm" onclick={() => logViewer?.stopLogStream()}
+ >Stop</Button
+ >
{:else}
- <Button variant="outline" size="sm" onclick={() => logViewer?.startLogStream()} disabled={!container?.Id}>Start</Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onclick={() => logViewer?.startLogStream()}
+ disabled={!container?.Id}>Start</Button
+ >
{/if}
</div>
</div>
<Card.Root class="border">
<Card.Content class="p-0">
- <LogViewer bind:this={logViewer} bind:autoScroll={autoScrollLogs} type="container" containerId={container?.Id} maxLines={500} showTimestamps={true} height="400px" onStart={handleLogStart} onStop={handleLogStop} onClear={handleLogClear} onToggleAutoScroll={handleToggleAutoScroll} />
+ <LogViewer
+ bind:this={logViewer}
+ bind:autoScroll={autoScrollLogs}
+ type="container"
+ containerId={container?.Id}
+ maxLines={500}
+ showTimestamps={true}
+ height="400px"
+ onStart={handleLogStart}
+ onStop={handleLogStop}
+ onClear={handleLogClear}
+ onToggleAutoScroll={handleToggleAutoScroll}
+ />
</Card.Content>
</Card.Root>
</section>
@@ -534,7 +648,9 @@
{@const value = valueParts.join('=')}
<div class="border-muted/30 flex border-b py-2">
<span class="w-1/3 truncate pr-3 font-medium" title={key}>{key}</span>
- <span class="text-muted-foreground w-2/3 truncate" title={value}>{value}</span>
+ <span class="text-muted-foreground w-2/3 truncate" title={value}
+ >{value}</span
+ >
</div>
{:else}
<div class="border-muted/30 border-b py-2">{env}</div>
@@ -542,7 +658,9 @@
{/each}
</div>
{:else}
- <div class="text-muted-foreground py-8 text-center">No environment variables</div>
+ <div class="text-muted-foreground py-8 text-center">
+ No environment variables
+ </div>
{/if}
</Card.Content>
</Card.Root>
@@ -591,7 +709,10 @@
{#each Object.entries(container.Config.Labels) as [key, value] (key)}
<div class="border-muted/30 flex border-b py-2">
<span class="w-1/3 truncate pr-3 font-medium" title={key}>{key}</span>
- <span class="text-muted-foreground w-2/3 truncate" title={value?.toString()}>{value?.toString() || ''}</span>
+ <span
+ class="text-muted-foreground w-2/3 truncate"
+ title={value?.toString()}>{value?.toString() || ''}</span
+ >
</div>
{/each}
</div>
@@ -633,7 +754,9 @@
<div>
<div class="text-muted-foreground text-sm">Subnet</div>
<div class="font-mono">
- {networkConfig.IPPrefixLen ? `${networkConfig.IPAddress}/${networkConfig.IPPrefixLen}` : 'N/A'}
+ {networkConfig.IPPrefixLen
+ ? `${networkConfig.IPAddress}/${networkConfig.IPPrefixLen}`
+ : 'N/A'}
</div>
</div>
{#if networkConfig.Aliases && networkConfig.Aliases.length > 0}
@@ -668,7 +791,13 @@
<div class="overflow-hidden rounded border">
<div class="bg-muted/20 flex items-center justify-between p-4">
<div class="flex items-center gap-3">
- <div class="rounded p-2 {mount.Type === 'volume' ? 'bg-purple-100 dark:bg-purple-950' : mount.Type === 'bind' ? 'bg-blue-100 dark:bg-blue-950' : 'bg-amber-100 dark:bg-amber-950'}">
+ <div
+ class="rounded p-2 {mount.Type === 'volume'
+ ? 'bg-purple-100 dark:bg-purple-950'
+ : mount.Type === 'bind'
+ ? 'bg-blue-100 dark:bg-blue-950'
+ : 'bg-amber-100 dark:bg-amber-950'}"
+ >
{#if mount.Type === 'volume'}
<Database class="size-4 text-purple-600" />
{:else if mount.Type === 'bind'}
@@ -679,7 +808,11 @@
</div>
<div>
<div class="font-medium">
- {mount.Type === 'tmpfs' ? 'Temporary filesystem' : mount.Type === 'volume' ? mount.Name || 'Docker volume' : 'Host directory'}
+ {mount.Type === 'tmpfs'
+ ? 'Temporary filesystem'
+ : mount.Type === 'volume'
+ ? mount.Name || 'Docker volume'
+ : 'Host directory'}
</div>
<div class="text-muted-foreground text-sm">
{mount.Type} mount {mount.RW ? '(read-write)' : '(read-only)'}
@@ -693,13 +826,21 @@
<div class="space-y-3 p-4">
<div class="flex">
<span class="text-muted-foreground w-24 font-medium">Container:</span>
- <span class="bg-muted/50 flex-1 rounded px-2 py-1 font-mono">{mount.Destination}</span>
+ <span class="bg-muted/50 flex-1 rounded px-2 py-1 font-mono"
+ >{mount.Destination}</span
+ >
</div>
<div class="flex">
<span class="text-muted-foreground w-24 font-medium">
- {mount.Type === 'volume' ? 'Volume:' : mount.Type === 'bind' ? 'Host:' : 'Source:'}
+ {mount.Type === 'volume'
+ ? 'Volume:'
+ : mount.Type === 'bind'
+ ? 'Host:'
+ : 'Source:'}
</span>
- <span class="bg-muted/50 flex-1 rounded px-2 py-1 font-mono">{mount.Source}</span>
+ <span class="bg-muted/50 flex-1 rounded px-2 py-1 font-mono"
+ >{mount.Source}</span
+ >
</div>
</div>
</div>
@@ -707,7 +848,9 @@
</div>
{:else}
<div class="py-12 text-center">
- <div class="bg-muted/50 mx-auto mb-4 flex size-16 items-center justify-center rounded-full">
+ <div
+ class="bg-muted/50 mx-auto mb-4 flex size-16 items-center justify-center rounded-full"
+ >
<Database class="text-muted-foreground size-6" />
</div>
<div class="text-muted-foreground">No volumes or mounts configured</div>
@@ -727,7 +870,10 @@
<AlertCircle class="text-muted-foreground size-10" />
</div>
<h2 class="mb-3 text-2xl font-medium">Container Not Found</h2>
- <p class="text-muted-foreground mb-8 max-w-md text-center">Could not load container data. It may have been removed or the Docker engine is not accessible.</p>
+ <p class="text-muted-foreground mb-8 max-w-md text-center">
+ Could not load container data. It may have been removed or the Docker engine is not
+ accessible.
+ </p>
<div class="flex justify-center gap-4">
<Button variant="outline" href="/containers">
<ArrowLeft class="mr-2 size-4" />
diff --git a/frontend/src/routes/containers/[containerId]/+page.ts b/frontend/src/routes/containers/[containerId]/+page.ts
index f7dde7442..c28a2b781 100644
--- a/frontend/src/routes/containers/[containerId]/+page.ts
+++ b/frontend/src/routes/containers/[containerId]/+page.ts
@@ -14,7 +14,7 @@ export const load: PageLoad = async ({ params }) => {
}
return {
- container,
+ container: container.data,
stats: containerStats
};
} catch (err: any) {
diff --git a/frontend/src/routes/containers/container-table.svelte b/frontend/src/routes/containers/container-table.svelte
new file mode 100644
index 000000000..989d2c623
--- /dev/null
+++ b/frontend/src/routes/containers/container-table.svelte
@@ -0,0 +1,289 @@
+<script lang="ts">
+ import type { ContainerInfo } from '$lib/models/container-info';
+ import ArcaneTable from '$lib/components/arcane-table.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import {
+ ScanSearch,
+ Play,
+ RotateCcw,
+ StopCircle,
+ Trash2,
+ Loader2,
+ Ellipsis,
+ Box
+ } from '@lucide/svelte';
+ import * as Card from '$lib/components/ui/card/index.js';
+ import { goto } from '$app/navigation';
+ import { toast } from 'svelte-sonner';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import ArcaneButton from '$lib/components/arcane-button.svelte';
+ import { environmentAPI } from '$lib/services/api';
+ import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
+ import * as Table from '$lib/components/ui/table';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { formatFriendlyDate } from '$lib/utils/date.utils';
+
+ interface ContainerWithId extends ContainerInfo {
+ id: string;
+ }
+
+ let {
+ containers,
+ selectedIds = $bindable(),
+ requestOptions = $bindable(),
+ onRefresh,
+ onContainersChanged,
+ onCheckForUpdates
+ }: {
+ containers: Paginated<ContainerWithId>;
+ selectedIds: string[];
+ requestOptions: SearchPaginationSortRequest;
+ onRefresh: (options: SearchPaginationSortRequest) => Promise<Paginated<ContainerWithId>>;
+ onContainersChanged: () => Promise<void>;
+ onCheckForUpdates: () => Promise<void>;
+ } = $props();
+
+ let isLoading = $state({
+ start: false,
+ stop: false,
+ restart: false,
+ remove: false,
+ updating: false
+ });
+
+ async function performContainerAction(action: string, id: string) {
+ isLoading[action as keyof typeof isLoading] = true;
+
+ try {
+ if (action === 'start') {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.startContainer(id)),
+ message: 'Failed to Start Container',
+ setLoadingState: (value) => (isLoading.start = value),
+ async onSuccess() {
+ toast.success('Container Started Successfully.');
+ await onContainersChanged();
+ }
+ });
+ } else if (action === 'stop') {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.stopContainer(id)),
+ message: 'Failed to Stop Container',
+ setLoadingState: (value) => (isLoading.stop = value),
+ async onSuccess() {
+ toast.success('Container Stopped Successfully.');
+ await onContainersChanged();
+ }
+ });
+ } else if (action === 'restart') {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.restartContainer(id)),
+ message: 'Failed to Restart Container',
+ setLoadingState: (value) => (isLoading.restart = value),
+ async onSuccess() {
+ toast.success('Container Restarted Successfully.');
+ await onContainersChanged();
+ }
+ });
+ }
+ } catch (error) {
+ console.error('Container action failed:', error);
+ toast.error('An error occurred while performing the action');
+ isLoading[action as keyof typeof isLoading] = false;
+ }
+ }
+
+ async function handleRemoveContainer(id: string) {
+ openConfirmDialog({
+ title: 'Confirm Container Removal',
+ message: 'Are you sure you want to remove this container? This action cannot be undone.',
+ confirm: {
+ label: 'Remove',
+ destructive: true,
+ action: async () => {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.deleteContainer(id)),
+ message: 'Failed to Remove Container',
+ setLoadingState: (value) => (isLoading.remove = value),
+ async onSuccess() {
+ toast.success('Container Removed Successfully.');
+ await onContainersChanged();
+ }
+ });
+ }
+ }
+ });
+ }
+
+ const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
+ const hasContainers = $derived(containers?.data?.length > 0);
+</script>
+
+{#if hasContainers}
+ <Card.Root class="border shadow-sm">
+ <Card.Header class="px-6">
+ <div class="flex items-center justify-between">
+ <div>
+ <Card.Title>Container List</Card.Title>
+ </div>
+ <div class="flex items-center gap-2">
+ <ArcaneButton
+ action="inspect"
+ label="Update Containers"
+ onClick={onCheckForUpdates}
+ loading={isLoading.updating}
+ loadingLabel="Updating..."
+ disabled={isLoading.updating}
+ />
+ <ArcaneButton
+ action="create"
+ customLabel="Create Container"
+ onClick={() => goto('/containers/create')}
+ />
+ </div>
+ </div>
+ </Card.Header>
+ <Card.Content>
+ <ArcaneTable
+ items={containers}
+ bind:requestOptions
+ bind:selectedIds
+ {onRefresh}
+ columns={[
+ { label: 'Name', sortColumn: 'name' },
+ { label: 'ID', sortColumn: 'id' },
+ { label: 'Image', sortColumn: 'image' },
+ { label: 'State', sortColumn: 'state' },
+ { label: 'Status', sortColumn: 'status' },
+ { label: 'Created', sortColumn: 'created' },
+ { label: ' ' }
+ ]}
+ filterPlaceholder="Search containers..."
+ noResultsMessage="No containers found"
+ >
+ {#snippet rows({ item })}
+ <Table.Cell>
+ <a class="font-medium hover:underline" href="/containers/{item.Id || item.id}/">
+ {#if item.Names && item.Names.length > 0}
+ {item.Names[0].startsWith('/') ? item.Names[0].substring(1) : item.Names[0]}
+ {:else}
+ {(item.Id || item.id).substring(0, 12)}
+ {/if}
+ </a>
+ </Table.Cell>
+ <Table.Cell>
+ <span class="font-mono text-sm">{(item.Id || item.id).substring(0, 12)}</span>
+ </Table.Cell>
+ <Table.Cell>
+ <span class="text-sm">{item.Image}</span>
+ </Table.Cell>
+ <Table.Cell>
+ <StatusBadge
+ variant={item.State === 'running'
+ ? 'green'
+ : item.State === 'exited'
+ ? 'red'
+ : 'amber'}
+ text={item.State}
+ />
+ </Table.Cell>
+ <Table.Cell>
+ <span class="text-sm">{item.Status}</span>
+ </Table.Cell>
+ <Table.Cell>
+ <span class="text-sm">
+ {item.Created ? formatFriendlyDate(new Date(item.Created * 1000).toISOString()) : ''}
+ </span>
+ </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 || item.id}`)}
+ disabled={isAnyLoading}
+ >
+ <ScanSearch class="size-4" />
+ Inspect
+ </DropdownMenu.Item>
+
+ {#if item.State !== 'running'}
+ <DropdownMenu.Item
+ onclick={() => performContainerAction('start', item.Id || item.id)}
+ disabled={isLoading.start || isAnyLoading}
+ >
+ {#if isLoading.start}
+ <Loader2 class="size-4 animate-spin" />
+ {:else}
+ <Play class="size-4" />
+ {/if}
+ Start
+ </DropdownMenu.Item>
+ {:else}
+ <DropdownMenu.Item
+ onclick={() => performContainerAction('restart', item.Id || item.id)}
+ disabled={isLoading.restart || isAnyLoading}
+ >
+ {#if isLoading.restart}
+ <Loader2 class="size-4 animate-spin" />
+ {:else}
+ <RotateCcw class="size-4" />
+ {/if}
+ Restart
+ </DropdownMenu.Item>
+
+ <DropdownMenu.Item
+ onclick={() => performContainerAction('stop', item.Id || item.id)}
+ disabled={isLoading.stop || isAnyLoading}
+ >
+ {#if isLoading.stop}
+ <Loader2 class="size-4 animate-spin" />
+ {:else}
+ <StopCircle class="size-4" />
+ {/if}
+ Stop
+ </DropdownMenu.Item>
+ {/if}
+
+ <DropdownMenu.Separator />
+
+ <DropdownMenu.Item
+ class="focus:text-red-700! text-red-500"
+ onclick={() => handleRemoveContainer(item.Id || item.id)}
+ disabled={isLoading.remove || isAnyLoading}
+ >
+ {#if isLoading.remove}
+ <Loader2 class="size-4 animate-spin" />
+ {:else}
+ <Trash2 class="size-4" />
+ {/if}
+ Remove
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </ArcaneTable>
+ </Card.Content>
+ </Card.Root>
+{:else}
+ <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
+ <Box class="text-muted-foreground mb-4 size-12 opacity-40" />
+ <p class="text-lg font-medium">No containers found</p>
+ <p class="text-muted-foreground mt-1 text-sm">
+ Create a new container using the "Create Container" button above or use the Docker CLI
+ </p>
+ </div>
+{/if}
diff --git a/frontend/src/routes/customize/registries/+page.svelte b/frontend/src/routes/customize/registries/+page.svelte
index f89ad138a..2f99ce7d5 100644
--- a/frontend/src/routes/customize/registries/+page.svelte
+++ b/frontend/src/routes/customize/registries/+page.svelte
@@ -1,33 +1,109 @@
<script lang="ts">
import * as Card from '$lib/components/ui/card/index.js';
- import { Button } from '$lib/components/ui/button/index.js';
- import { Key, Plus, Trash2, Ellipsis, Pencil, RefreshCw, TestTube } from '@lucide/svelte';
- import UniversalTable from '$lib/components/universal-table.svelte';
- import * as Table from '$lib/components/ui/table';
- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
- import ContainerRegistryFormSheet from '$lib/components/sheets/container-registry-sheet.svelte';
- import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import { Key } from '@lucide/svelte';
import { toast } from 'svelte-sonner';
import type { ContainerRegistry } from '$lib/models/container-registry';
- import type { ContainerRegistryCreateDto, ContainerRegistryUpdateDto } from '$lib/dto/container-registry-dto';
+ import type {
+ ContainerRegistryCreateDto,
+ ContainerRegistryUpdateDto
+ } from '$lib/dto/container-registry-dto';
import { containerRegistryAPI } from '$lib/services/api';
+ import ContainerRegistryFormSheet from '$lib/components/sheets/container-registry-sheet.svelte';
+ import RegistryTable from './registry-table.svelte';
+ import ArcaneButton from '$lib/components/arcane-button.svelte';
+ import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
+ import type { PageData } from './$types';
- let { data } = $props();
- let registries = $state<ContainerRegistry[]>(data.registries || []);
+ let { data }: { data: PageData } = $props();
+ let registries = $state<ContainerRegistry[]>([]);
+ let paginatedRegistries = $state<Paginated<ContainerRegistry> | null>(null);
+ let selectedIds = $state<string[]>([]);
let isRegistryDialogOpen = $state(false);
let registryToEdit = $state<ContainerRegistry | null>(null);
- let isLoadingAction = $state(false);
+ let requestOptions = $state<SearchPaginationSortRequest>(data.registryRequestOptions);
+
+ let isLoading = $state({
+ create: false,
+ edit: false,
+ refresh: false
+ });
+
+ $effect(() => {
+ if (data.registries) {
+ if (Array.isArray(data.registries)) {
+ registries = data.registries;
+ const paginatedData: Paginated<ContainerRegistry> = {
+ data: data.registries,
+ pagination: {
+ totalPages: 1,
+ totalItems: data.registries.length,
+ currentPage: 1,
+ itemsPerPage: data.registries.length
+ }
+ };
+ paginatedRegistries = paginatedData;
+ } else {
+ const paginatedData: Paginated<ContainerRegistry> = {
+ data: data.registries.data,
+ pagination: data.registries.pagination
+ };
+ paginatedRegistries = paginatedData;
+ registries = data.registries.data || [];
+ }
+ }
+ });
+
+ async function onRefresh(
+ options: SearchPaginationSortRequest
+ ): Promise<Paginated<ContainerRegistry>> {
+ const response = await containerRegistryAPI.getRegistries(
+ options.pagination,
+ options.sort,
+ options.search,
+ options.filters
+ );
+
+ if (Array.isArray(response)) {
+ registries = response;
+ const paginatedResponse: Paginated<ContainerRegistry> = {
+ data: response,
+ pagination: {
+ totalPages: 1,
+ totalItems: response.length,
+ currentPage: options.pagination?.page || 1,
+ itemsPerPage: response.length
+ }
+ };
+ paginatedRegistries = paginatedResponse;
+ return paginatedResponse;
+ } else {
+ const paginatedResponse: Paginated<ContainerRegistry> = {
+ data: response.data,
+ pagination: response.pagination
+ };
+ paginatedRegistries = paginatedResponse;
+ registries = response.data || [];
+ return paginatedResponse;
+ }
+ }
- async function loadRegistries() {
+ async function refreshRegistries() {
+ isLoading.refresh = true;
try {
- registries = await containerRegistryAPI.getAllRegistries();
+ await onRefresh(requestOptions);
} catch (error) {
- console.error('Error loading registries:', error);
- toast.error('Failed to load registries');
+ console.error('Failed to refresh registries:', error);
+ toast.error('Failed to refresh registries');
+ } finally {
+ isLoading.refresh = false;
}
}
+ async function onRegistriesChanged() {
+ await refreshRegistries();
+ }
+
function openCreateRegistryDialog() {
registryToEdit = null;
isRegistryDialogOpen = true;
@@ -38,72 +114,33 @@
isRegistryDialogOpen = true;
}
- // Updated function signature - now receives detail directly
- async function handleRegistryDialogSubmit(detail: { registry: ContainerRegistryCreateDto | ContainerRegistryUpdateDto; isEditMode: boolean }) {
+ async function handleRegistryDialogSubmit(detail: {
+ registry: ContainerRegistryCreateDto | ContainerRegistryUpdateDto;
+ isEditMode: boolean;
+ }) {
const { registry, isEditMode } = detail;
- isLoadingAction = true;
+ const loadingKey = isEditMode ? 'edit' : 'create';
+ isLoading[loadingKey] = true;
try {
if (isEditMode && registryToEdit?.id) {
- await containerRegistryAPI.updateRegistry(registryToEdit.id, registry as ContainerRegistryUpdateDto);
+ await containerRegistryAPI.updateRegistry(
+ registryToEdit.id,
+ registry as ContainerRegistryUpdateDto
+ );
toast.success('Registry updated successfully');
} else {
await containerRegistryAPI.createRegistry(registry as ContainerRegistryCreateDto);
toast.success('Registry created successfully');
}
- await loadRegistries();
+ await refreshRegistries();
isRegistryDialogOpen = false;
} catch (error) {
console.error('Error saving registry:', error);
toast.error(error instanceof Error ? error.message : 'Failed to save registry');
} finally {
- isLoadingAction = false;
- }
- }
-
- function confirmRemoveRegistry(registry: ContainerRegistry) {
- openConfirmDialog({
- title: 'Remove Registry',
- message: `Are you sure you want to remove the registry "${registry.url}"? This action cannot be undone.`,
- confirm: {
- label: 'Remove',
- destructive: true,
- action: async () => {
- if (registry.id) {
- await removeRegistry(registry.id);
- }
- }
- }
- });
- }
-
- async function removeRegistry(id: string) {
- isLoadingAction = true;
-
- try {
- await containerRegistryAPI.deleteRegistry(id);
- toast.success('Registry removed successfully');
- await loadRegistries();
- } catch (error) {
- console.error('Error removing registry:', error);
- toast.error(error instanceof Error ? error.message : 'Failed to remove registry');
- } finally {
- isLoadingAction = false;
- }
- }
-
- async function testRegistry(id: string, url: string) {
- isLoadingAction = true;
-
- try {
- const result = await containerRegistryAPI.testRegistry(id);
- toast.success(`Registry test passed: ${result.message}`);
- } catch (error) {
- console.error('Error testing registry:', error);
- toast.error(error instanceof Error ? error.message : 'Failed to test registry');
- } finally {
- isLoadingAction = false;
+ isLoading[loadingKey] = false;
}
}
</script>
@@ -112,29 +149,30 @@
<title>Container Registries - Arcane</title>
</svelte:head>
-<ContainerRegistryFormSheet bind:open={isRegistryDialogOpen} bind:registryToEdit onSubmit={handleRegistryDialogSubmit} isLoading={isLoadingAction} />
+<ContainerRegistryFormSheet
+ bind:open={isRegistryDialogOpen}
+ bind:registryToEdit
+ onSubmit={handleRegistryDialogSubmit}
+ isLoading={isLoading.create || isLoading.edit}
+/>
<div class="space-y-6">
<div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
<div>
<h1 class="text-3xl font-bold tracking-tight">Container Registries</h1>
- <p class="text-muted-foreground mt-1 text-sm">Configure access credentials for private Docker registries and container repositories</p>
+ <p class="text-muted-foreground mt-1 text-sm">
+ Configure access credentials for private Docker registries and container repositories
+ </p>
</div>
-
- <div class="flex gap-2">
- <Button onclick={loadRegistries} disabled={isLoadingAction} variant="outline" class="h-10">
- <RefreshCw class="size-4" />
- Refresh
- </Button>
- <Button onclick={openCreateRegistryDialog} disabled={isLoadingAction} class="arcane-button-save h-10">
- {#if isLoadingAction}
- <RefreshCw class="size-4 animate-spin" />
- Processing...
- {:else}
- <Plus class="size-4" />
- Add Registry
- {/if}
- </Button>
+ <div class="flex items-center gap-2">
+ <ArcaneButton
+ action="restart"
+ onClick={refreshRegistries}
+ label="Refresh"
+ loading={isLoading.refresh}
+ disabled={isLoading.refresh}
+ />
+ <ArcaneButton action="create" onClick={openCreateRegistryDialog} label="Add Registry" />
</div>
</div>
@@ -146,119 +184,34 @@
</div>
<div>
<Card.Title>Docker Registry Credentials</Card.Title>
- <Card.Description>Manage authentication credentials for private Docker registries like Docker Hub, GitHub Container Registry, Google Container Registry, and custom registries</Card.Description>
+ <Card.Description>
+ Manage authentication credentials for private Docker registries like Docker Hub, GitHub
+ Container Registry, Google Container Registry, and custom registries
+ </Card.Description>
</div>
</div>
</Card.Header>
<Card.Content>
- {#if !registries || registries.length === 0}
- <div class="py-12 text-center">
- <div class="bg-muted/30 mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full">
- <Key class="text-muted-foreground size-8" />
- </div>
- <h3 class="mb-2 text-lg font-medium">No Registry Credentials</h3>
- <p class="text-muted-foreground mx-auto mb-4 max-w-sm text-sm">Add registry credentials to authenticate with private Docker registries when pulling images.</p>
- <Button onclick={openCreateRegistryDialog} class="arcane-button-save">
- <Plus class="size-4" />
- Add Your First Registry
- </Button>
- </div>
- {:else}
- <UniversalTable
- data={registries}
- columns={[
- { accessorKey: 'url', header: 'Registry URL' },
- { accessorKey: 'username', header: 'Username' },
- { accessorKey: 'description', header: 'Description' },
- { accessorKey: 'enabled', header: 'Status' },
- { accessorKey: 'actions', header: 'Actions', enableSorting: false }
- ]}
- features={{
- sorting: true,
- filtering: true,
- selection: false
- }}
- pagination={{
- pageSize: 10,
- pageSizeOptions: [5, 10, 20]
- }}
- sort={{
- defaultSort: { id: 'url', desc: false }
- }}
- display={{
- noResultsMessage: 'No registry credentials found.',
- filterPlaceholder: 'Search registries...'
- }}
- >
- {#snippet rows({ item, index })}
- {#if typeof index === 'number'}
- <Table.Cell class="font-medium">
- <div class="flex flex-col">
- <span class="font-medium">
- {item.url || 'docker.io (Docker Hub)'}
- </span>
- {#if item.url && (item.url.includes('ghcr.io') || item.url.includes('gcr.io') || item.url.includes('quay.io'))}
- <span class="text-muted-foreground text-xs">
- {#if item.url.includes('ghcr.io')}
- GitHub Container Registry
- {:else if item.url.includes('gcr.io')}
- Google Container Registry
- {:else if item.url.includes('quay.io')}
- Quay.io Registry
- {/if}
- </span>
- {/if}
- </div>
- </Table.Cell>
- <Table.Cell>
- <div class="flex items-center gap-2">
- <span class="font-mono text-sm">{item.username || '-'}</span>
- </div>
- </Table.Cell>
- <Table.Cell>
- <span class="text-muted-foreground text-sm">
- {item.description || 'No description provided'}
- </span>
- </Table.Cell>
- <Table.Cell>
- <span class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium {item.enabled ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}">
- {item.enabled ? 'Enabled' : 'Disabled'}
- </span>
- </Table.Cell>
- <Table.Cell class="text-right">
- <DropdownMenu.Root>
- <DropdownMenu.Trigger>
- <Button variant="ghost" size="icon" class="size-8">
- <Ellipsis class="size-4" />
- <span class="sr-only">Open menu</span>
- </Button>
- </DropdownMenu.Trigger>
- <DropdownMenu.Content align="end">
- {#if item.id}
- <DropdownMenu.Item onclick={() => testRegistry(item.id!, item.url)}>
- <TestTube class="mr-2 size-4" />
- Test Connection
- </DropdownMenu.Item>
- {/if}
- <DropdownMenu.Item onclick={() => openEditRegistryDialog(item)}>
- <Pencil class="mr-2 size-4" />
- Edit
- </DropdownMenu.Item>
- <DropdownMenu.Item onclick={() => confirmRemoveRegistry(item)} class="focus:bg-destructive/10 text-red-500 focus:text-red-700!">
- <Trash2 class="mr-2 size-4" />
- Remove
- </DropdownMenu.Item>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- </Table.Cell>
- {/if}
- {/snippet}
- </UniversalTable>
- {/if}
+ <RegistryTable
+ registries={paginatedRegistries || {
+ data: registries,
+ pagination: {
+ totalPages: 1,
+ totalItems: registries.length,
+ currentPage: 1,
+ itemsPerPage: registries.length
+ }
+ }}
+ bind:selectedIds
+ bind:requestOptions
+ {onRefresh}
+ {onRegistriesChanged}
+ onCreateRegistry={openCreateRegistryDialog}
+ onEditRegistry={openEditRegistryDialog}
+ />
</Card.Content>
</Card.Root>
- <!-- Registry Information Card -->
<Card.Root class="border shadow-sm">
<Card.Header>
<Card.Title class="text-lg">Registry Information</Card.Title>
diff --git a/frontend/src/routes/customize/registries/+page.ts b/frontend/src/routes/customize/registries/+page.ts
index 230d3647b..4b01591e1 100644
--- a/frontend/src/routes/customize/registries/+page.ts
+++ b/frontend/src/routes/customize/registries/+page.ts
@@ -1,7 +1,25 @@
import { containerRegistryAPI } from '$lib/services/api';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import type { PageLoad } from './$types';
-export const load = async () => {
- const registries = await containerRegistryAPI.getAllRegistries();
+export const load: PageLoad = async () => {
+ const registryRequestOptions: SearchPaginationSortRequest = {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'url',
+ direction: 'asc' as const
+ }
+ };
- return { registries };
+ const registries = await containerRegistryAPI.getRegistries(
+ registryRequestOptions.pagination,
+ registryRequestOptions.sort,
+ registryRequestOptions.search,
+ registryRequestOptions.filters
+ );
+
+ return { registries, registryRequestOptions };
};
diff --git a/frontend/src/routes/customize/registries/registry-table.svelte b/frontend/src/routes/customize/registries/registry-table.svelte
new file mode 100644
index 000000000..417aa2e34
--- /dev/null
+++ b/frontend/src/routes/customize/registries/registry-table.svelte
@@ -0,0 +1,278 @@
+<script lang="ts">
+ import type { ContainerRegistry } from '$lib/models/container-registry';
+ import ArcaneTable from '$lib/components/arcane-table.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { Trash2, Ellipsis, Pencil, TestTube, Key } from '@lucide/svelte';
+ import * as Card from '$lib/components/ui/card/index.js';
+ import { toast } from 'svelte-sonner';
+ 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 { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import ArcaneButton from '$lib/components/arcane-button.svelte';
+ import { containerRegistryAPI } from '$lib/services/api';
+ import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
+
+ interface RegistryWithId extends ContainerRegistry {
+ id: string;
+ }
+
+ let {
+ registries,
+ selectedIds = $bindable(),
+ requestOptions = $bindable(),
+ onRefresh,
+ onRegistriesChanged,
+ onCreateRegistry,
+ onEditRegistry
+ }: {
+ registries: Paginated<ContainerRegistry>;
+ selectedIds: string[];
+ requestOptions: SearchPaginationSortRequest;
+ onRefresh: (options: SearchPaginationSortRequest) => Promise<Paginated<ContainerRegistry>>;
+ onRegistriesChanged: () => Promise<void>;
+ onCreateRegistry: () => void;
+ onEditRegistry: (registry: ContainerRegistry) => void;
+ } = $props();
+
+ let isLoading = $state({
+ remove: false,
+ test: false
+ });
+
+ const transformedRegistries = $derived.by(() => {
+ const transformed: RegistryWithId[] = registries.data.map((registry) => ({
+ ...registry,
+ id: registry.id
+ }));
+
+ return {
+ data: transformed,
+ pagination: registries.pagination
+ };
+ });
+
+ async function handleRefresh(
+ options: SearchPaginationSortRequest
+ ): Promise<Paginated<RegistryWithId>> {
+ const result = await onRefresh(options);
+ const transformed: RegistryWithId[] = result.data.map((registry) => ({
+ ...registry,
+ id: registry.id
+ }));
+
+ return {
+ data: transformed,
+ pagination: result.pagination
+ };
+ }
+
+ async function handleDeleteRegistry(id: string, url: string) {
+ openConfirmDialog({
+ title: 'Remove Registry',
+ message: `Are you sure you want to remove the registry "${url}"? This action cannot be undone.`,
+ confirm: {
+ label: 'Remove',
+ destructive: true,
+ action: async () => {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(containerRegistryAPI.deleteRegistry(id)),
+ message: `Failed to remove registry "${url}"`,
+ setLoadingState: (value) => (isLoading.remove = value),
+ onSuccess: async () => {
+ toast.success(`Registry "${url}" removed successfully.`);
+ await onRegistriesChanged();
+ }
+ });
+ }
+ }
+ });
+ }
+
+ async function handleDeleteSelectedRegistries() {
+ const selectedRegistryList = registries.data.filter((registry) =>
+ selectedIds.includes(registry.id)
+ );
+
+ openConfirmDialog({
+ title: 'Remove Selected Registries',
+ message: `Are you sure you want to remove ${selectedIds.length} selected registr${selectedIds.length === 1 ? 'y' : 'ies'}? This action cannot be undone.`,
+ confirm: {
+ label: 'Remove',
+ destructive: true,
+ action: async () => {
+ isLoading.remove = true;
+
+ let successCount = 0;
+ let failureCount = 0;
+
+ for (const registryId of selectedIds) {
+ const registry = registries.data.find((r) => r.id === registryId);
+ if (!registry) continue;
+
+ const result = await tryCatch(containerRegistryAPI.deleteRegistry(registryId));
+ if (result.error) {
+ failureCount++;
+ toast.error(`Failed to delete registry "${registry.url}": ${result.error.message}`);
+ } else {
+ successCount++;
+ toast.success(`Registry "${registry.url}" deleted successfully.`);
+ }
+ }
+
+ isLoading.remove = false;
+ if (successCount > 0) {
+ setTimeout(async () => {
+ await onRegistriesChanged();
+ }, 500);
+ }
+ selectedIds = [];
+ }
+ }
+ });
+ }
+
+ async function handleTestRegistry(id: string, url: string) {
+ isLoading.test = true;
+ try {
+ const result = await containerRegistryAPI.testRegistry(id);
+ toast.success(`Registry test passed: ${result.message || 'Connection successful'}`);
+ } catch (error) {
+ console.error('Error testing registry:', error);
+ toast.error(error instanceof Error ? error.message : 'Failed to test registry');
+ } finally {
+ isLoading.test = false;
+ }
+ }
+
+ const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
+ const hasRegistries = $derived(registries?.data?.length > 0);
+
+ function getRegistryDisplayName(url: string) {
+ if (!url || url === 'docker.io') return 'Docker Hub';
+ if (url.includes('ghcr.io')) return 'GitHub Container Registry';
+ if (url.includes('gcr.io')) return 'Google Container Registry';
+ if (url.includes('quay.io')) return 'Quay.io Registry';
+ return url;
+ }
+</script>
+
+{#if hasRegistries}
+ <Card.Root class="border shadow-sm">
+ <Card.Header class="px-6">
+ <div class="flex items-center justify-between">
+ <div>
+ <Card.Title>Registry Credentials</Card.Title>
+ </div>
+ <div class="flex items-center gap-2">
+ {#if selectedIds.length > 0}
+ <ArcaneButton
+ action="remove"
+ onClick={handleDeleteSelectedRegistries}
+ loading={isLoading.remove}
+ disabled={isLoading.remove}
+ />
+ {/if}
+ <ArcaneButton action="create" label="Add Registry" onClick={onCreateRegistry} />
+ </div>
+ </div>
+ </Card.Header>
+ <Card.Content>
+ <ArcaneTable
+ items={transformedRegistries}
+ bind:requestOptions
+ bind:selectedIds
+ onRefresh={handleRefresh}
+ columns={[
+ { label: 'Registry URL', sortColumn: 'url' },
+ { label: 'Username', sortColumn: 'username' },
+ { label: 'Description', sortColumn: 'description' },
+ { label: 'Status', sortColumn: 'enabled' },
+ { label: 'Created', sortColumn: 'createdAt' },
+ { label: ' ' }
+ ]}
+ filterPlaceholder="Search registries..."
+ noResultsMessage="No registry credentials found"
+ >
+ {#snippet rows({ item })}
+ <Table.Cell class="font-medium">
+ <div class="flex flex-col">
+ <span class="font-medium">
+ {item.url || 'docker.io'}
+ </span>
+ <span class="text-muted-foreground text-xs">
+ {getRegistryDisplayName(item.url)}
+ </span>
+ </div>
+ </Table.Cell>
+ <Table.Cell>
+ <span class="font-mono text-sm">{item.username || '-'}</span>
+ </Table.Cell>
+ <Table.Cell>
+ <span class="text-muted-foreground text-sm">
+ {item.description || 'No description provided'}
+ </span>
+ </Table.Cell>
+ <Table.Cell>
+ <span
+ class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium {item.enabled
+ ? 'bg-green-100 text-green-800'
+ : 'bg-gray-100 text-gray-800'}"
+ >
+ {item.enabled ? 'Enabled' : 'Disabled'}
+ </span>
+ </Table.Cell>
+ <Table.Cell>
+ <span class="text-sm">
+ {item.createdAt ? new Date(item.createdAt).toLocaleDateString() : 'N/A'}
+ </span>
+ </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={() => handleTestRegistry(item.id, item.url)}
+ disabled={isAnyLoading}
+ >
+ <TestTube class="size-4" />
+ Test Connection
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onEditRegistry(item)} disabled={isAnyLoading}>
+ <Pencil class="size-4" />
+ Edit
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ class="focus:text-red-700! text-red-500"
+ onclick={() => handleDeleteRegistry(item.id, item.url)}
+ disabled={isAnyLoading}
+ >
+ <Trash2 class="size-4" />
+ Remove
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </ArcaneTable>
+ </Card.Content>
+ </Card.Root>
+{:else}
+ <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
+ <Key class="text-muted-foreground mb-4 size-12 opacity-40" />
+ <p class="text-lg font-medium">No registry credentials found</p>
+ <p class="text-muted-foreground mt-1 text-sm">
+ Add registry credentials to authenticate with private Docker registries when pulling images.
+ </p>
+ </div>
+{/if}
diff --git a/frontend/src/routes/dashboard/+page.svelte b/frontend/src/routes/dashboard/+page.svelte
new file mode 100644
index 000000000..bfed5d710
--- /dev/null
+++ b/frontend/src/routes/dashboard/+page.svelte
@@ -0,0 +1,694 @@
+<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 {
+ AlertCircle,
+ Box,
+ HardDrive,
+ RefreshCw,
+ Loader2,
+ Monitor,
+ PlayCircle,
+ StopCircle,
+ Trash2
+ } from '@lucide/svelte';
+ import * as Alert from '$lib/components/ui/alert/index.js';
+ import { capitalizeFirstLetter } from '$lib/utils/string.utils';
+ import { formatBytes } from '$lib/utils/bytes.util';
+ import { toast } from 'svelte-sonner';
+ import PruneConfirmationDialog from '$lib/components/dialogs/prune-confirmation-dialog.svelte';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import { systemAPI, imageAPI, environmentAPI, settingsAPI } from '$lib/services/api';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import { onMount } from 'svelte';
+ import { maturityStore } from '$lib/stores/maturity-store';
+ import type { PruneType } from '$lib/types/actions.type';
+ import DropdownCard from '$lib/components/dropdown-card.svelte';
+ import MeterMetric from '$lib/components/meter-metric.svelte';
+ import DockerIcon from '$lib/icons/docker-icon.svelte';
+ import GitHubIcon from '$lib/icons/github-icon.svelte';
+ import type { SystemStats } from '$lib/models/system-stats';
+ import type { ContainerInfo } from '$lib/models/container-info';
+ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import DashboardContainerTable from './dash-container-table.svelte';
+ import DashboardImageTable from './dash-image-table.svelte';
+
+ let { data }: { data: PageData } = $props();
+
+ let dashboardStates = $state({
+ dockerInfo: data.dockerInfo,
+ containers: Array.isArray(data.containers) ? data.containers : data.containers?.data || [],
+ images: Array.isArray(data.images) ? data.images : data.images?.data || [],
+ settings: data.settings,
+ systemStats: null as SystemStats | null,
+ error: data.error || null,
+ isPruneDialogOpen: false
+ });
+
+ let isLoading = $state({
+ starting: false,
+ stopping: false,
+ refreshing: false,
+ pruning: false,
+ loadingStats: true,
+ loadingMaturity: true,
+ loadingContainers: false,
+ loadingDockerInfo: false,
+ loadingImages: false
+ });
+
+ let liveSystemStats = $state(null as SystemStats | null);
+ let statsInterval: NodeJS.Timeout | null = null;
+ let hasInitialStatsLoaded = $state(false);
+
+ let historicalData = $state({
+ cpu: [] as Array<{ date: Date; value: number }>,
+ memory: [] as Array<{ date: Date; value: number }>,
+ disk: [] as Array<{ date: Date; value: number }>,
+ containers: [] as Array<{ date: Date; value: number }>
+ });
+
+ const runningContainers = $derived(
+ dashboardStates.containers?.filter((c: ContainerInfo) => c.State === 'running').length ?? 0
+ );
+
+ const stoppedContainers = $derived(
+ dashboardStates.containers?.filter((c: ContainerInfo) => c.State === 'exited').length ?? 0
+ );
+
+ const totalImageSize = $derived(
+ dashboardStates.images?.reduce((sum, image) => sum + (image.Size || 0), 0) ?? 0
+ );
+
+ const containerUsagePercent = $derived(
+ dashboardStates.containers?.length
+ ? (runningContainers / dashboardStates.containers.length) * 100
+ : 0
+ );
+
+ const currentStats = $derived(dashboardStates.systemStats || liveSystemStats);
+
+ function addToHistoricalData(stats: SystemStats) {
+ const now = new Date();
+ const maxPoints = 20;
+
+ if (stats.cpuUsage !== undefined) {
+ historicalData.cpu.push({ date: now, value: stats.cpuUsage });
+ if (historicalData.cpu.length > maxPoints) {
+ historicalData.cpu = historicalData.cpu.slice(-maxPoints);
+ }
+ }
+
+ if (stats.memoryUsage !== undefined && stats.memoryTotal !== undefined) {
+ const memoryPercent = (stats.memoryUsage / stats.memoryTotal) * 100;
+ historicalData.memory.push({ date: now, value: memoryPercent });
+ if (historicalData.memory.length > maxPoints) {
+ historicalData.memory = historicalData.memory.slice(-maxPoints);
+ }
+ }
+
+ if (stats.diskUsage !== undefined && stats.diskTotal !== undefined) {
+ const diskPercent = (stats.diskUsage / stats.diskTotal) * 100;
+ historicalData.disk.push({ date: now, value: diskPercent });
+ if (historicalData.disk.length > maxPoints) {
+ historicalData.disk = historicalData.disk.slice(-maxPoints);
+ }
+ }
+
+ historicalData.containers.push({ date: now, value: runningContainers });
+ if (historicalData.containers.length > maxPoints) {
+ historicalData.containers = historicalData.containers.slice(-maxPoints);
+ }
+ }
+
+ function getContainerDisplayName(container: ContainerInfo): string {
+ if (container.Names && container.Names.length > 0) {
+ return container.Names[0].startsWith('/')
+ ? container.Names[0].substring(1)
+ : container.Names[0];
+ }
+ return container.Id?.substring(0, 12) || 'Unknown';
+ }
+
+ async function onContainerRefresh(options: SearchPaginationSortRequest) {
+ const response = await environmentAPI.getContainers(
+ options.pagination,
+ options.sort,
+ options.search,
+ options.filters
+ );
+
+ if (Array.isArray(response)) {
+ dashboardStates.containers = response;
+ return {
+ data: response,
+ pagination: {
+ totalPages: 1,
+ totalItems: response.length,
+ currentPage: options.pagination?.page || 1,
+ itemsPerPage: response.length
+ }
+ };
+ } else {
+ dashboardStates.containers = response.data || [];
+ return {
+ data: response.data || [],
+ pagination: response.pagination
+ };
+ }
+ }
+
+ async function onImageRefresh(options: SearchPaginationSortRequest) {
+ const response = await environmentAPI.getImages(
+ options.pagination,
+ options.sort,
+ options.search,
+ options.filters
+ );
+
+ if (Array.isArray(response)) {
+ dashboardStates.images = response;
+ return {
+ data: response,
+ pagination: {
+ totalPages: 1,
+ totalItems: response.length,
+ currentPage: options.pagination?.page || 1,
+ itemsPerPage: response.length
+ }
+ };
+ } else {
+ dashboardStates.images = response.data || [];
+ return {
+ data: response.data || [],
+ pagination: response.pagination
+ };
+ }
+ }
+
+ async function fetchLiveSystemStats() {
+ if (!hasInitialStatsLoaded) {
+ isLoading.loadingStats = true;
+ }
+
+ try {
+ const response = await systemAPI.getStats();
+
+ let stats: SystemStats | null = null;
+
+ if (response && typeof response === 'object') {
+ if ('success' in response && response.success && 'data' in response) {
+ stats = response.data as SystemStats;
+ } else if ('cpuUsage' in response) {
+ stats = response as SystemStats;
+ }
+ }
+
+ if (stats) {
+ liveSystemStats = stats;
+ dashboardStates.systemStats = stats;
+ addToHistoricalData(stats);
+ } else {
+ console.warn('Invalid system stats response format:', response);
+ }
+ } catch (error) {
+ console.error('Failed to fetch live system stats:', error);
+ } finally {
+ if (!hasInitialStatsLoaded) {
+ isLoading.loadingStats = false;
+ hasInitialStatsLoaded = true;
+ }
+ }
+ }
+
+ async function loadTopImagesMaturity() {
+ if (!dashboardStates.images || dashboardStates.images.length === 0) {
+ isLoading.loadingMaturity = false;
+ return;
+ }
+
+ isLoading.loadingMaturity = true;
+
+ const topImageIds = [...dashboardStates.images]
+ .sort((a, b) => (b.Size || 0) - (a.Size || 0))
+ .slice(0, 5)
+ .filter((img) => img.RepoTags && img.RepoTags[0] !== '<none>:<none>')
+ .map((img) => img.Id);
+
+ if (topImageIds.length === 0) {
+ isLoading.loadingMaturity = false;
+ return;
+ }
+
+ try {
+ const BATCH_SIZE = 1;
+ for (let i = 0; i < topImageIds.length; i += BATCH_SIZE) {
+ const batch = topImageIds.slice(i, i + BATCH_SIZE);
+ await imageAPI.checkMaturityBatch(batch);
+
+ dashboardStates.images = dashboardStates.images.map((image) => {
+ const storedMaturity = $maturityStore.maturityData[image.Id];
+ return {
+ ...image,
+ maturity: storedMaturity !== undefined ? storedMaturity : image.maturity
+ };
+ });
+
+ if (i + BATCH_SIZE < topImageIds.length) {
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ }
+ } catch (error) {
+ console.error('Error loading maturity data for dashboard images:', error);
+ } finally {
+ isLoading.loadingMaturity = false;
+ }
+ }
+
+ async function refreshData() {
+ if (isLoading.refreshing) return;
+ isLoading.refreshing = true;
+
+ const [dockerInfoResult, containersResult, imagesResult, settingsResult] =
+ await Promise.allSettled([
+ tryCatch(systemAPI.getDockerInfo()),
+ tryCatch(
+ environmentAPI.getContainers(
+ data.containerRequestOptions.pagination,
+ data.containerRequestOptions.sort,
+ data.containerRequestOptions.search,
+ data.containerRequestOptions.filters
+ )
+ ),
+ tryCatch(
+ environmentAPI.getImages(
+ data.imageRequestOptions.pagination,
+ data.imageRequestOptions.sort,
+ data.imageRequestOptions.search,
+ data.imageRequestOptions.filters
+ )
+ ),
+ tryCatch(settingsAPI.getSettings())
+ ]);
+
+ if (dockerInfoResult.status === 'fulfilled' && !dockerInfoResult.value.error) {
+ dashboardStates.dockerInfo = dockerInfoResult.value.data;
+ }
+
+ if (containersResult.status === 'fulfilled' && !containersResult.value.error) {
+ const containerData = containersResult.value.data;
+ dashboardStates.containers = Array.isArray(containerData)
+ ? containerData
+ : containerData?.data || [];
+ }
+
+ if (imagesResult.status === 'fulfilled' && !imagesResult.value.error) {
+ const imageData = imagesResult.value.data;
+ dashboardStates.images = Array.isArray(imageData) ? imageData : imageData?.data || [];
+ }
+
+ if (settingsResult.status === 'fulfilled' && !settingsResult.value.error) {
+ dashboardStates.settings = settingsResult.value.data;
+ }
+
+ await fetchLiveSystemStats();
+
+ if (dashboardStates.images && dashboardStates.images.length > 0) {
+ loadTopImagesMaturity();
+ }
+
+ isLoading.refreshing = false;
+ }
+
+ onMount(() => {
+ let mounted = true;
+
+ fetchLiveSystemStats();
+
+ if (dashboardStates.images && dashboardStates.images.length > 0) {
+ loadTopImagesMaturity();
+ } else {
+ isLoading.loadingMaturity = false;
+ }
+
+ if (!statsInterval) {
+ statsInterval = setInterval(() => {
+ if (mounted) {
+ fetchLiveSystemStats();
+ }
+ }, 5000);
+ }
+
+ return () => {
+ mounted = false;
+ if (statsInterval) {
+ clearInterval(statsInterval);
+ statsInterval = null;
+ }
+ };
+ });
+
+ async function handleStartAll() {
+ if (isLoading.starting || !dashboardStates.dockerInfo || stoppedContainers === 0) return;
+ isLoading.starting = true;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(systemAPI.startAllStoppedContainers()),
+ message: 'Failed to Start All Containers',
+ setLoadingState: (value) => (isLoading.starting = value),
+ onSuccess: async () => {
+ toast.success('All Containers Started Successfully.');
+ await refreshData();
+ }
+ });
+ }
+
+ async function handleStopAll() {
+ if (isLoading.stopping || !dashboardStates.dockerInfo || runningContainers === 0) return;
+ openConfirmDialog({
+ title: 'Stop All Containers',
+ message: 'Are you sure you want to stop all running containers?',
+ confirm: {
+ label: 'Confirm',
+ destructive: false,
+ action: async () => {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(systemAPI.stopAllContainers()),
+ message: 'Failed to Stop All Running Containers',
+ setLoadingState: (value) => (isLoading.stopping = value),
+ onSuccess: async () => {
+ toast.success('All Containers Stopped Successfully.');
+ await refreshData();
+ }
+ });
+ }
+ }
+ });
+ }
+
+ async function confirmPrune(selectedTypes: PruneType[]) {
+ if (isLoading.pruning || selectedTypes.length === 0) return;
+ isLoading.pruning = true;
+
+ const pruneOptions = {
+ containers: selectedTypes.includes('containers'),
+ images: selectedTypes.includes('images'),
+ volumes: selectedTypes.includes('volumes'),
+ networks: selectedTypes.includes('networks'),
+ dangling: dashboardStates.settings?.pruneMode === 'dangling'
+ };
+
+ handleApiResultWithCallbacks({
+ result: await tryCatch(systemAPI.pruneAll(pruneOptions)),
+ message: `Failed to Prune ${selectedTypes.join(', ')}`,
+ setLoadingState: (value) => (isLoading.pruning = value),
+ onSuccess: async () => {
+ dashboardStates.isPruneDialogOpen = false;
+ const formattedTypes = selectedTypes.map((type) => capitalizeFirstLetter(type)).join(', ');
+ toast.success(
+ `${formattedTypes} ${selectedTypes.length > 1 ? 'were' : 'was'} pruned successfully.`
+ );
+ await refreshData();
+ }
+ });
+ }
+</script>
+
+<div class="space-y-8">
+ <div class="flex items-center justify-between">
+ <div>
+ <h1 class="text-3xl font-bold tracking-tight">Dashboard</h1>
+ <p class="text-muted-foreground mt-1 text-sm">Overview of your Container Environment</p>
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ class="arcane-button-restart h-9"
+ onclick={refreshData}
+ disabled={isLoading.refreshing ||
+ isLoading.starting ||
+ isLoading.stopping ||
+ isLoading.pruning}
+ >
+ {#if isLoading.refreshing}
+ <Loader2 class="mr-2 size-4 animate-spin" />
+ {:else}
+ <RefreshCw class="mr-2 size-4" />
+ {/if}
+ Refresh
+ </Button>
+ </div>
+
+ {#if dashboardStates.error}
+ <Alert.Root variant="destructive">
+ <AlertCircle class="mr-2 size-4" />
+ <Alert.Title>Connection Error</Alert.Title>
+ <Alert.Description>
+ {dashboardStates.error} Please check your Docker connection in
+ <a href="/settings" class="underline">Settings</a>.
+ </Alert.Description>
+ </Alert.Root>
+ {/if}
+
+ <section>
+ <DropdownCard
+ id="system-overview"
+ title="System Overview"
+ description="Hardware and Docker engine information"
+ icon={Monitor}
+ defaultExpanded={true}
+ >
+ <div class="grid grid-cols-2 gap-4 md:grid-cols-4">
+ <MeterMetric
+ title="Running Containers"
+ description="Active containers"
+ currentValue={runningContainers}
+ data={historicalData.containers}
+ formatValue={(v) => v.toString()}
+ color="var(--chart-1)"
+ maxValue={dashboardStates.containers?.length || 10}
+ unit="containers"
+ />
+
+ {#if currentStats?.cpuUsage !== undefined}
+ <MeterMetric
+ title="CPU Usage"
+ description="Processor utilization"
+ currentValue={currentStats.cpuUsage}
+ data={historicalData.cpu}
+ unit="%"
+ color="var(--chart-2)"
+ maxValue={100}
+ />
+ {/if}
+
+ {#if currentStats?.memoryUsage !== undefined && currentStats?.memoryTotal !== undefined}
+ <MeterMetric
+ title="Memory Usage"
+ description="RAM utilization"
+ currentValue={(currentStats.memoryUsage / currentStats.memoryTotal) * 100}
+ data={historicalData.memory}
+ unit="%"
+ formatValue={(v) => `${v.toFixed(1)}`}
+ color="var(--chart-3)"
+ maxValue={100}
+ />
+ {/if}
+
+ {#if currentStats?.diskUsage !== undefined && currentStats?.diskTotal !== undefined}
+ <MeterMetric
+ title="Disk Usage"
+ description="Storage utilization"
+ currentValue={(currentStats.diskUsage / currentStats.diskTotal) * 100}
+ data={historicalData.disk}
+ unit="%"
+ formatValue={(v) => `${v.toFixed(1)}`}
+ color="var(--chart-4)"
+ maxValue={100}
+ />
+ {/if}
+ </div>
+
+ <div class="mt-6 grid grid-cols-1 gap-4 md:grid-cols-3">
+ <Card.Root>
+ <Card.Content class="p-4">
+ <div class="flex items-center gap-3">
+ <div class="rounded-lg bg-blue-500/10 p-2">
+ <DockerIcon class="size-5 text-blue-500" />
+ </div>
+ <div>
+ <p class="text-sm font-medium">Docker Engine</p>
+ <p class="text-xs text-muted-foreground">
+ {dashboardStates.dockerInfo?.version || 'Unknown'} •
+ {dashboardStates.dockerInfo?.os || 'Unknown'}
+ </p>
+ </div>
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root>
+ <Card.Content class="p-4">
+ <div class="flex items-center gap-3">
+ <div class="rounded-lg bg-green-500/10 p-2">
+ <Box class="size-5 text-green-500" />
+ </div>
+ <div>
+ <p class="text-sm font-medium">Total Containers</p>
+ <p class="text-xs text-muted-foreground">
+ {dashboardStates.containers?.length || 0} total •
+ {stoppedContainers} stopped
+ </p>
+ </div>
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root>
+ <Card.Content class="p-4">
+ <div class="flex items-center gap-3">
+ <div class="rounded-lg bg-purple-500/10 p-2">
+ <HardDrive class="size-5 text-purple-500" />
+ </div>
+ <div>
+ <p class="text-sm font-medium">Docker Images</p>
+ <p class="text-xs text-muted-foreground">
+ {dashboardStates.dockerInfo?.images || 0} images •
+ {formatBytes(totalImageSize)}
+ </p>
+ </div>
+ </div>
+ </Card.Content>
+ </Card.Root>
+ </div>
+ </DropdownCard>
+ </section>
+
+ <section>
+ <h2 class="mb-4 text-lg font-semibold tracking-tight">Quick Actions</h2>
+ {#if isLoading.loadingDockerInfo}
+ <div class="grid grid-cols-1 gap-5 sm:grid-cols-3">
+ {#each Array(3) as _}
+ <div class="bg-card flex flex-col items-center rounded-xl border p-6">
+ <div class="bg-muted mb-4 size-12 animate-pulse rounded-full"></div>
+ <div class="bg-muted h-4 w-24 animate-pulse rounded"></div>
+ <div class="bg-muted mt-2 h-3 w-16 animate-pulse rounded"></div>
+ </div>
+ {/each}
+ </div>
+ {:else}
+ <div class="grid grid-cols-1 gap-5 sm:grid-cols-3">
+ <button
+ class="group bg-card relative flex flex-col items-center rounded-xl border p-6 shadow-sm transition-all hover:shadow-md disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:shadow-sm"
+ disabled={!dashboardStates.dockerInfo ||
+ stoppedContainers === 0 ||
+ isLoading.starting ||
+ isLoading.stopping ||
+ isLoading.pruning}
+ onclick={handleStartAll}
+ >
+ <div
+ class="mb-4 flex size-12 items-center justify-center rounded-full bg-green-500/10 transition-colors group-hover:bg-green-500/20"
+ >
+ {#if isLoading.starting}
+ <Loader2 class="size-6 animate-spin text-green-500" />
+ {:else}
+ <PlayCircle class="size-6 text-green-500" />
+ {/if}
+ </div>
+ <span class="text-center text-base font-medium">Start All Stopped</span>
+ <span class="text-muted-foreground mt-1 text-sm">{stoppedContainers} containers</span>
+ </button>
+
+ <button
+ class="group bg-card relative flex flex-col items-center rounded-xl border p-6 shadow-sm transition-all hover:shadow-md disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:shadow-sm"
+ disabled={!dashboardStates.dockerInfo ||
+ runningContainers === 0 ||
+ isLoading.starting ||
+ isLoading.stopping ||
+ isLoading.pruning}
+ onclick={handleStopAll}
+ >
+ <div
+ class="mb-4 flex size-12 items-center justify-center rounded-full bg-blue-500/10 transition-colors group-hover:bg-blue-500/20"
+ >
+ {#if isLoading.stopping}
+ <Loader2 class="size-6 animate-spin text-blue-500" />
+ {:else}
+ <StopCircle class="size-6 text-blue-500" />
+ {/if}
+ </div>
+ <span class="text-center text-base font-medium">Stop All Running</span>
+ <span class="text-muted-foreground mt-1 text-sm">{runningContainers}</span>
+ </button>
+
+ <button
+ class="group bg-card hover:border-destructive/50 disabled:hover:border-border relative flex flex-col items-center rounded-xl border p-6 shadow-sm transition-all hover:shadow-md disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:shadow-sm"
+ disabled={!dashboardStates.dockerInfo ||
+ isLoading.starting ||
+ isLoading.stopping ||
+ isLoading.pruning}
+ onclick={() => (dashboardStates.isPruneDialogOpen = true)}
+ >
+ <div
+ class="mb-4 flex size-12 items-center justify-center rounded-full bg-red-500/10 transition-colors group-hover:bg-red-500/20"
+ >
+ {#if isLoading.pruning}
+ <Loader2 class="size-6 animate-spin text-red-500" />
+ {:else}
+ <Trash2 class="size-6 text-red-500" />
+ {/if}
+ </div>
+ <span class="text-center text-base font-medium">Prune System</span>
+ <span class="text-muted-foreground mt-1 text-sm">Clean unused resources</span>
+ </button>
+ </div>
+ {/if}
+ </section>
+
+ <section>
+ <h2 class="mb-4 text-lg font-semibold tracking-tight">Resources</h2>
+ <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
+ <DashboardContainerTable
+ containers={dashboardStates.containers || []}
+ isLoading={isLoading.loadingContainers}
+ onRefresh={onContainerRefresh}
+ {getContainerDisplayName}
+ />
+
+ <DashboardImageTable
+ images={dashboardStates.images}
+ isLoading={isLoading.loadingImages}
+ isLoadingMaturity={isLoading.loadingMaturity}
+ onRefresh={onImageRefresh}
+ />
+ </div>
+ </section>
+
+ <section class="mt-10 border-t pt-4">
+ <div class="text-muted-foreground flex items-center justify-between text-sm">
+ <div class="flex items-center">
+ <a
+ href="https://github.com/ofkm/arcane"
+ target="_blank"
+ rel="noopener noreferrer"
+ class="hover:text-foreground transition-colors"
+ title="GitHub"
+ >
+ <GitHubIcon class="size-4 fill-current" />
+ <span class="sr-only">GitHub</span>
+ </a>
+ </div>
+ <div></div>
+ </div>
+ </section>
+
+ <PruneConfirmationDialog
+ bind:open={dashboardStates.isPruneDialogOpen}
+ isPruning={isLoading.pruning}
+ imagePruneMode={(dashboardStates.settings?.pruneMode as 'dangling' | 'all') || 'dangling'}
+ onConfirm={confirmPrune}
+ onCancel={() => (dashboardStates.isPruneDialogOpen = false)}
+ />
+</div>
diff --git a/frontend/src/routes/dashboard/+page.ts b/frontend/src/routes/dashboard/+page.ts
new file mode 100644
index 000000000..109be49fb
--- /dev/null
+++ b/frontend/src/routes/dashboard/+page.ts
@@ -0,0 +1,71 @@
+import { systemAPI, settingsAPI, environmentAPI } from '$lib/services/api';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async () => {
+ const containerRequestOptions: SearchPaginationSortRequest = {
+ pagination: {
+ page: 1,
+ limit: 5
+ },
+ sort: {
+ column: 'created',
+ direction: 'desc' as const
+ }
+ },
+ imageRequestOptions: SearchPaginationSortRequest = {
+ pagination: {
+ page: 1,
+ limit: 5
+ },
+ sort: {
+ column: 'Created',
+ direction: 'desc' as const
+ }
+ };
+
+ try {
+ const [dockerInfoResult, containersResult, imagesResult, settingsResult] =
+ await Promise.allSettled([
+ systemAPI.getDockerInfo(),
+ environmentAPI.getContainers(
+ containerRequestOptions.pagination,
+ containerRequestOptions.sort,
+ containerRequestOptions.search,
+ containerRequestOptions.filters
+ ),
+ environmentAPI.getImages(
+ imageRequestOptions.pagination,
+ imageRequestOptions.sort,
+ imageRequestOptions.search,
+ imageRequestOptions.filters
+ ),
+ settingsAPI.getSettings()
+ ]);
+
+ const dockerInfo = dockerInfoResult.status === 'fulfilled' ? dockerInfoResult.value : null;
+ const containers = containersResult.status === 'fulfilled' ? containersResult.value : [];
+ const images = imagesResult.status === 'fulfilled' ? imagesResult.value : [];
+ const settings = settingsResult.status === 'fulfilled' ? settingsResult.value : null;
+
+ return {
+ dockerInfo,
+ containers,
+ images,
+ settings,
+ containerRequestOptions,
+ imageRequestOptions
+ };
+ } catch (error) {
+ console.error('Error loading dashboard data:', error);
+ return {
+ dockerInfo: null,
+ containers: [],
+ images: [],
+ settings: null,
+ containerRequestOptions,
+ imageRequestOptions,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+};
diff --git a/frontend/src/routes/dashboard/dash-container-table.svelte b/frontend/src/routes/dashboard/dash-container-table.svelte
new file mode 100644
index 000000000..f21c7dd82
--- /dev/null
+++ b/frontend/src/routes/dashboard/dash-container-table.svelte
@@ -0,0 +1,120 @@
+<script lang="ts">
+ import type { ContainerInfo, EnhancedContainerInfo } from '$lib/models/container-info';
+ import ArcaneTable from '$lib/components/arcane-table.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { ArrowRight, Box, Loader2 } from '@lucide/svelte';
+ import * as Card from '$lib/components/ui/card/index.js';
+ import * as Table from '$lib/components/ui/table';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { statusVariantMap } from '$lib/types/statuses';
+ import { capitalizeFirstLetter, truncateString } from '$lib/utils/string.utils';
+ import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
+
+ interface ContainerWithId extends ContainerInfo {
+ id: string;
+ }
+
+ let {
+ containers,
+ isLoading,
+ onRefresh,
+ getContainerDisplayName
+ }: {
+ containers: ContainerInfo[];
+ isLoading: boolean;
+ onRefresh: (options: SearchPaginationSortRequest) => Promise<Paginated<ContainerWithId>>;
+ getContainerDisplayName: (container: ContainerInfo) => string;
+ } = $props();
+
+ let requestOptions = $state<SearchPaginationSortRequest>({
+ pagination: { page: 1, limit: 5 },
+ sort: { column: 'created', direction: 'desc' }
+ });
+
+ let selectedIds = $state<string[]>([]);
+
+ const paginatedContainers: Paginated<ContainerWithId> = $derived({
+ data: containers.slice(0, 5).map((c) => ({ ...c, id: c.Id })),
+ pagination: {
+ totalPages: Math.ceil(containers.length / 5),
+ totalItems: containers.length,
+ currentPage: 1,
+ itemsPerPage: 5
+ }
+ });
+</script>
+
+<Card.Root class="relative flex flex-col border shadow-sm">
+ <Card.Header class="px-6">
+ <div class="flex items-center justify-between">
+ <div>
+ <Card.Title>
+ <a class="font-medium hover:underline" href="/containers">Containers</a>
+ </Card.Title>
+ <Card.Description class="pb-3">Recent containers</Card.Description>
+ </div>
+ <Button variant="ghost" size="sm" href="/containers" disabled={isLoading}>
+ View All
+ <ArrowRight class="ml-2 size-4" />
+ </Button>
+ </div>
+ </Card.Header>
+ <Card.Content class="flex-1 p-0">
+ {#if isLoading}
+ <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
+ <Loader2 class="text-muted-foreground mb-4 size-8 animate-spin" />
+ <p class="text-lg font-medium">Loading Containers...</p>
+ <p class="text-muted-foreground mt-1 text-sm">Please wait while we fetch containers</p>
+ </div>
+ {:else if containers?.length > 0}
+ <div class="flex h-full flex-col">
+ <ArcaneTable
+ items={paginatedContainers}
+ bind:requestOptions
+ bind:selectedIds
+ {onRefresh}
+ withoutSearch={true}
+ withoutPagination={true}
+ selectionDisabled={true}
+ columns={[
+ { label: 'Name', sortColumn: 'name' },
+ { label: 'Image', sortColumn: 'image' },
+ { label: 'State', sortColumn: 'state' },
+ { label: 'Status', sortColumn: 'status' }
+ ]}
+ filterPlaceholder="Search containers..."
+ noResultsMessage="No containers found"
+ >
+ {#snippet rows({ item })}
+ {@const stateVariant = statusVariantMap[item.State?.toLowerCase()] || 'secondary'}
+ <Table.Cell>
+ <a class="font-medium hover:underline" href="/containers/{item.Id}/">
+ {getContainerDisplayName(item)}
+ </a>
+ </Table.Cell>
+ <Table.Cell title={item.Image}>
+ {truncateString(item.Image, 40)}
+ </Table.Cell>
+ <Table.Cell>
+ <StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.State)} />
+ </Table.Cell>
+ <Table.Cell>{item.Status}</Table.Cell>
+ {/snippet}
+ </ArcaneTable>
+ {#if containers.length > 5}
+ <div class="bg-muted/40 text-muted-foreground border-t px-6 py-2 text-xs">
+ Showing 5 of {containers.length} containers
+ </div>
+ {/if}
+ </div>
+ {:else}
+ <div class="flex flex-col items-center justify-center px-6 py-10 text-center">
+ <Box class="text-muted-foreground mb-2 size-8 opacity-40" />
+ <p class="text-muted-foreground text-sm">No containers found</p>
+ <p class="text-muted-foreground mt-1 text-xs">
+ Use Docker CLI or another tool to create containers
+ </p>
+ </div>
+ {/if}
+ </Card.Content>
+</Card.Root>
diff --git a/frontend/src/routes/dashboard/dash-image-table.svelte b/frontend/src/routes/dashboard/dash-image-table.svelte
new file mode 100644
index 000000000..c57cfabec
--- /dev/null
+++ b/frontend/src/routes/dashboard/dash-image-table.svelte
@@ -0,0 +1,151 @@
+<script lang="ts">
+ import type { EnhancedImageInfo } from '$lib/models/image.type';
+ import ArcaneTable from '$lib/components/arcane-table.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { ArrowRight, HardDrive, Loader2 } from '@lucide/svelte';
+ import * as Card from '$lib/components/ui/card/index.js';
+ import * as Table from '$lib/components/ui/table';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import MaturityItem from '$lib/components/maturity-item.svelte';
+ import { formatBytes } from '$lib/utils/bytes.util';
+ import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
+
+ interface ImageWithId extends EnhancedImageInfo {
+ id: string;
+ }
+
+ let {
+ images,
+ isLoading,
+ isLoadingMaturity,
+ onRefresh
+ }: {
+ images: EnhancedImageInfo[];
+ isLoading: boolean;
+ isLoadingMaturity: boolean;
+ onRefresh: (options: SearchPaginationSortRequest) => Promise<Paginated<ImageWithId>>;
+ } = $props();
+
+ let requestOptions = $state<SearchPaginationSortRequest>({
+ pagination: { page: 1, limit: 5 },
+ sort: { column: 'Size', direction: 'desc' }
+ });
+
+ let selectedIds = $state<string[]>([]);
+
+ const sortedImages = $derived(
+ images
+ .slice()
+ .sort((a, b) => (b.Size || 0) - (a.Size || 0))
+ .slice(0, 5)
+ );
+
+ const paginatedImages: Paginated<ImageWithId> = $derived({
+ data: sortedImages.map((img) => ({ ...img, id: img.Id })),
+ pagination: {
+ totalPages: Math.ceil(images.length / 5),
+ totalItems: images.length,
+ currentPage: 1,
+ itemsPerPage: 5
+ }
+ });
+</script>
+
+<Card.Root class="relative flex flex-col border shadow-sm">
+ <Card.Header class="px-6">
+ <div class="flex items-center justify-between">
+ <div>
+ <Card.Title>
+ <a class="font-medium hover:underline" href="/images">Images</a>
+ </Card.Title>
+ <Card.Description class="pb-3">Top 5 Largest Images</Card.Description>
+ </div>
+ <Button variant="ghost" size="sm" href="/images" disabled={isLoading}>
+ View All
+ <ArrowRight class="ml-2 size-4" />
+ </Button>
+ </div>
+ </Card.Header>
+ <Card.Content class="flex-1 p-0">
+ {#if isLoading}
+ <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
+ <Loader2 class="text-muted-foreground mb-4 size-8 animate-spin" />
+ <p class="text-lg font-medium">Loading Images...</p>
+ <p class="text-muted-foreground mt-1 text-sm">Please wait while we fetch images</p>
+ </div>
+ {:else if images?.length > 0}
+ <div class="flex h-full flex-col">
+ <ArcaneTable
+ items={paginatedImages}
+ bind:requestOptions
+ bind:selectedIds
+ {onRefresh}
+ withoutSearch={true}
+ selectionDisabled={true}
+ withoutPagination={true}
+ columns={[
+ { label: 'Name', sortColumn: 'RepoTags' },
+ { label: 'Status', sortColumn: 'InUse' },
+ { label: 'Tag', sortColumn: 'tag' },
+ { label: 'Size', sortColumn: 'Size' }
+ ]}
+ filterPlaceholder="Search images..."
+ noResultsMessage="No images found"
+ >
+ {#snippet rows({ item })}
+ <Table.Cell>
+ <div class="flex items-center gap-2">
+ <div class="flex flex-1 items-center">
+ {#if isLoadingMaturity}
+ <div class="bg-muted size-4 animate-pulse rounded-full mr-2"></div>
+ {:else}
+ <MaturityItem
+ maturity={item.maturity}
+ isLoadingInBackground={!item.maturity}
+ imageId={item.Id}
+ />
+ {/if}
+ <a class="shrink truncate font-medium hover:underline" href="/images/{item.Id}/">
+ {#if item.RepoTags && item.RepoTags.length > 0 && item.RepoTags[0] !== '<none>:<none>'}
+ {item.RepoTags[0].split(':')[0]}
+ {:else}
+ <span class="text-muted-foreground italic">Untagged</span>
+ {/if}
+ </a>
+ </div>
+ </div>
+ </Table.Cell>
+ <Table.Cell>
+ {#if item.InUse}
+ <StatusBadge text="In Use" variant="green" />
+ {:else}
+ <StatusBadge text="Unused" variant="amber" />
+ {/if}
+ </Table.Cell>
+ <Table.Cell>
+ {#if item.RepoTags && item.RepoTags.length > 0 && item.RepoTags[0] !== '<none>:<none>'}
+ {item.RepoTags[0].split(':')[1] || 'latest'}
+ {:else}
+ <span class="text-muted-foreground italic">&lt;none&gt;</span>
+ {/if}
+ </Table.Cell>
+ <Table.Cell>{formatBytes(item.Size || 0)}</Table.Cell>
+ {/snippet}
+ </ArcaneTable>
+ {#if images.length > 5}
+ <div class="bg-muted/40 text-muted-foreground border-t px-6 py-2 text-xs">
+ Showing 5 of {images.length} images
+ </div>
+ {/if}
+ </div>
+ {:else}
+ <div class="flex flex-col items-center justify-center px-6 py-10 text-center">
+ <HardDrive class="text-muted-foreground mb-2 size-8 opacity-40" />
+ <p class="text-muted-foreground text-sm">No images found</p>
+ <p class="text-muted-foreground mt-1 text-xs">
+ Pull images using Docker CLI or another tool
+ </p>
+ </div>
+ {/if}
+ </Card.Content>
+</Card.Root>
diff --git a/frontend/src/routes/images/+page.svelte b/frontend/src/routes/images/+page.svelte
index 24da51189..db6f1ff94 100644
--- a/frontend/src/routes/images/+page.svelte
+++ b/frontend/src/routes/images/+page.svelte
@@ -1,85 +1,59 @@
<script lang="ts">
import type { PageData } from './$types';
import type { EnhancedImageInfo } from '$lib/models/image.type';
- import UniversalTable from '$lib/components/universal-table.svelte';
import { Button } from '$lib/components/ui/button/index.js';
- import {
- Download,
- AlertCircle,
- HardDrive,
- Trash2,
- Loader2,
- ChevronDown,
- Ellipsis,
- ScanSearch,
- Funnel,
- Package
- } from '@lucide/svelte';
+ import { AlertCircle, HardDrive, Loader2, Package } from '@lucide/svelte';
import * as Alert from '$lib/components/ui/alert/index.js';
import * as Card from '$lib/components/ui/card/index.js';
- import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
import ImagePullSheet from '$lib/components/sheets/image-pull-sheet.svelte';
import { formatBytes } from '$lib/utils/bytes.util';
- 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 { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import ArcaneButton from '$lib/components/arcane-button.svelte';
- import { tablePersistence } from '$lib/stores/table-store';
- import MaturityItem from '$lib/components/maturity-item.svelte';
import {
maturityStore,
triggerBulkMaturityCheck,
- enhanceImagesWithMaturity,
- loadImageMaturityBatch
+ enhanceImagesWithMaturity
} from '$lib/stores/maturity-store';
import { environmentAPI } from '$lib/services/api';
- import { onMount } from 'svelte';
import StatCard from '$lib/components/stat-card.svelte';
+ import ImageTable from './image-table.svelte';
+ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
let { data }: { data: PageData } = $props();
- let images = $state<EnhancedImageInfo[]>([]);
+ let images = $state<EnhancedImageInfo[]>(
+ Array.isArray(data.images) ? data.images : data.images.data || []
+ );
let error = $state<string | null>(null);
let selectedIds = $state<string[]>([]);
- let isLoadingImages = $state(true);
-
- let imageFilters = $state({
- showUsed: true,
- showUnused: true
- });
+ let isLoadingImages = $state(false);
+ let requestOptions = $state<SearchPaginationSortRequest>(data.imageRequestOptions);
let isLoading = $state({
pulling: false,
- removing: false,
refreshing: false,
- pruning: false,
- checking: false
+ pruning: false
});
- let isPullingInline = $state<Record<string, boolean>>({});
let isPullDialogOpen = $state(false);
let isConfirmPruneDialogOpen = $state(false);
- const totalImages = $derived(images?.length || 0);
const totalSize = $derived(images?.reduce((acc, img) => acc + (img.Size || 0), 0) || 0);
-
const enhancedImages = $derived(enhanceImagesWithMaturity(images, $maturityStore.maturityData));
- const filteredImages = $derived(
- enhancedImages.filter(
- (img) => (imageFilters.showUsed && img.InUse) || (imageFilters.showUnused && !img.InUse)
- ) as EnhancedImageInfo[]
- );
async function loadImages() {
try {
isLoadingImages = true;
- const response = await environmentAPI.getImages();
- images = response || [];
+ const response = await environmentAPI.getImages(
+ requestOptions.pagination,
+ requestOptions.sort,
+ requestOptions.search,
+ requestOptions.filters
+ );
+ images = Array.isArray(response) ? response : response.data || [];
error = null;
} catch (err) {
console.error('Failed to load images:', err);
@@ -90,23 +64,6 @@
}
}
- onMount(() => {
- loadImages();
- });
-
- $effect(() => {
- if (images && images.length > 0) {
- loadImagesMaturity();
- }
- });
-
- async function loadImagesMaturity() {
- if (!images || images.length === 0) return;
-
- const imageIds = images.map((img) => img.Id);
- await loadImageMaturityBatch(imageIds);
- }
-
async function refreshImages() {
isLoading.refreshing = true;
try {
@@ -119,55 +76,6 @@
}
}
- async function handleDeleteSelected() {
- if (selectedIds.length === 0) return;
-
- openConfirmDialog({
- title: `Remove ${selectedIds.length} Image${selectedIds.length > 1 ? 's' : ''}`,
- message: `Are you sure you want to remove the selected image${selectedIds.length > 1 ? 's' : ''}? This action cannot be undone.`,
- confirm: {
- label: 'Remove',
- destructive: true,
- action: async () => {
- isLoading.removing = true;
- let successCount = 0;
- let failureCount = 0;
-
- for (const id of selectedIds) {
- const result = await tryCatch(environmentAPI.deleteImage(id));
- handleApiResultWithCallbacks({
- result,
- message: `Failed to remove image`,
- setLoadingState: () => {},
- onSuccess: () => {
- successCount++;
- }
- });
-
- if (result.error) {
- failureCount++;
- }
- }
-
- isLoading.removing = false;
-
- if (successCount > 0) {
- toast.success(
- `Successfully removed ${successCount} image${successCount > 1 ? 's' : ''}`
- );
- await loadImages();
- }
-
- if (failureCount > 0) {
- toast.error(`Failed to remove ${failureCount} image${failureCount > 1 ? 's' : ''}`);
- }
-
- selectedIds = [];
- }
- }
- });
- }
-
async function handlePruneImages() {
isLoading.pruning = true;
handleApiResultWithCallbacks({
@@ -183,41 +91,44 @@
}
async function handleTriggerBulkMaturityCheck() {
- isLoading.checking = true;
- await triggerBulkMaturityCheck();
- isLoading.checking = false;
+ const result = await triggerBulkMaturityCheck(images.map((img) => img.Id));
+ if (result.success) {
+ toast.success(result.message);
+ } else {
+ toast.error(result.message);
+ }
}
- async function handleInlineImagePull(imageId: string, imageTag: string) {
- if (!imageTag) return;
-
- const imageIdentifier = imageId;
- isPullingInline = { ...isPullingInline, [imageIdentifier]: true };
-
- try {
- const result = await tryCatch(environmentAPI.pullImage(imageTag));
- handleApiResultWithCallbacks({
- result,
- message: `Failed to pull image ${imageTag}`,
- setLoadingState: () => {},
- onSuccess: async () => {
- toast.success(`Image ${imageTag} pulled successfully`);
- await loadImages();
- }
- });
- } finally {
- isPullingInline = { ...isPullingInline, [imageIdentifier]: false };
- }
+ async function onRefresh(options: SearchPaginationSortRequest) {
+ requestOptions = options;
+ await loadImages();
+ return {
+ data: enhancedImages,
+ pagination: {
+ totalPages: Math.ceil(enhancedImages.length / (requestOptions.pagination?.limit || 20)),
+ totalItems: enhancedImages.length,
+ currentPage: requestOptions.pagination?.page || 1,
+ itemsPerPage: requestOptions.pagination?.limit || 20
+ }
+ };
}
</script>
-<div class="space-y-6">
+<div class="space-y-6 pb-8">
<div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
<div>
- <h1 class="text-3xl font-bold tracking-tight">Container Images</h1>
+ <h1 class="text-2xl font-bold">Images</h1>
<p class="text-muted-foreground mt-1 text-sm">View and Manage your Container Images</p>
</div>
<div class="flex items-center gap-2">
+ <ArcaneButton
+ action="remove"
+ label="Prune Unused"
+ onClick={() => (isConfirmPruneDialogOpen = true)}
+ loading={isLoading.pruning}
+ loadingLabel="Pruning..."
+ disabled={isLoading.pruning}
+ />
<ArcaneButton
action="restart"
onClick={refreshImages}
@@ -237,20 +148,6 @@
{/if}
{#if isLoadingImages}
- <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
- {#each Array(2) as _}
- <Card.Root>
- <Card.Content class="flex items-center justify-between p-4">
- <div class="space-y-2">
- <div class="bg-muted h-4 w-24 animate-pulse rounded"></div>
- <div class="bg-muted h-8 w-12 animate-pulse rounded"></div>
- </div>
- <div class="bg-muted size-10 animate-pulse rounded-full"></div>
- </Card.Content>
- </Card.Root>
- {/each}
- </div>
-
<Card.Root class="border shadow-sm">
<Card.Header class="px-6">
<div class="flex items-center justify-between">
@@ -275,7 +172,7 @@
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
<StatCard
title="Total Images"
- value={totalImages}
+ value={images.length}
icon={HardDrive}
iconColor="text-blue-500"
class="border-l-4 border-l-blue-500"
@@ -289,199 +186,15 @@
/>
</div>
- {#if filteredImages.length > 0}
- <Card.Root class="border shadow-sm">
- <Card.Header class="px-6">
- <div class="flex items-center justify-between">
- <div>
- <Card.Title>Images List</Card.Title>
- </div>
- <div class="flex items-center gap-2">
- <DropdownMenu.Root>
- <DropdownMenu.Trigger>
- {#snippet child({ props })}
- <Button {...props} variant="outline" size="sm">
- <Funnel class="mr-2 size-4" />
- Filter
- <ChevronDown class="ml-2 size-4" />
- </Button>
- {/snippet}
- </DropdownMenu.Trigger>
- <DropdownMenu.Content>
- <DropdownMenu.Label>Image Usage</DropdownMenu.Label>
- <DropdownMenu.CheckboxItem
- checked={imageFilters.showUsed}
- onCheckedChange={(checked) => {
- imageFilters.showUsed = checked;
- }}
- >
- Show Used Images
- </DropdownMenu.CheckboxItem>
- <DropdownMenu.CheckboxItem
- checked={imageFilters.showUnused}
- onCheckedChange={(checked) => {
- imageFilters.showUnused = checked;
- }}
- >
- Show Unused Images
- </DropdownMenu.CheckboxItem>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- {#if selectedIds.length > 0}
- <ArcaneButton
- action="remove"
- onClick={() => handleDeleteSelected()}
- loading={isLoading.removing}
- disabled={isLoading.removing}
- />
- {/if}
- <ArcaneButton
- action="remove"
- label="Prune Unused"
- onClick={() => (isConfirmPruneDialogOpen = true)}
- loading={isLoading.pruning}
- loadingLabel="Pruning..."
- disabled={isLoading.pruning}
- />
- <ArcaneButton
- action="pull"
- label="Pull Image"
- onClick={() => (isPullDialogOpen = true)}
- loading={isLoading.pulling}
- loadingLabel="Pulling..."
- disabled={isLoading.pulling}
- />
- <ArcaneButton
- action="inspect"
- label="Recheck Maturities"
- onClick={() => handleTriggerBulkMaturityCheck()}
- loading={isLoading.checking}
- loadingLabel="Checking..."
- disabled={isLoading.checking}
- />
- </div>
- </div>
- </Card.Header>
- <Card.Content>
- <UniversalTable
- data={filteredImages}
- columns={[
- { accessorKey: 'RepoTags', header: 'Repository:Tag' },
- { accessorKey: 'Id', header: 'Image ID' },
- { accessorKey: 'Size', header: 'Size' },
- { accessorKey: 'Created', header: 'Created' },
- { accessorKey: 'InUse', header: 'Status' },
- { accessorKey: 'maturity', header: 'Maturity' },
- { accessorKey: 'actions', header: ' ', enableSorting: false }
- ]}
- pagination={{
- pageSize: tablePersistence.getPageSize('images')
- }}
- onPageSizeChange={(newSize) => {
- tablePersistence.setPageSize('images', newSize);
- }}
- sort={{
- defaultSort: { id: 'Created', desc: true }
- }}
- display={{
- filterPlaceholder: 'Search images...',
- noResultsMessage: 'No images found'
- }}
- bind:selectedIds
- >
- {#snippet rows({ item })}
- <Table.Cell>
- {#if item.RepoTags && item.RepoTags.length > 0 && item.RepoTags[0] !== '<none>:<none>'}
- {item.RepoTags[0]}
- {:else}
- <span class="text-muted-foreground italic">Untagged</span>
- {/if}
- </Table.Cell>
- <Table.Cell>
- <code class="bg-muted rounded px-2 py-1 text-xs"
- >{item.Id?.substring(7, 19) || 'N/A'}</code
- >
- </Table.Cell>
- <Table.Cell>{formatBytes(item.Size || 0)}</Table.Cell>
- <Table.Cell>{new Date((item.Created || 0) * 1000).toLocaleDateString()}</Table.Cell>
- <Table.Cell>
- {#if item.InUse}
- <StatusBadge text="In Use" variant="green" />
- {:else}
- <StatusBadge text="Unused" variant="amber" />
- {/if}
- </Table.Cell>
- <Table.Cell>
- {#if item.maturity}
- <MaturityItem maturity={item.maturity} imageId={item.Id} />
- {:else}
- <span class="text-muted-foreground text-sm">N/A</span>
- {/if}
- </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="size-4" />
- Inspect
- </DropdownMenu.Item>
- <DropdownMenu.Item
- onclick={() => handleInlineImagePull(item.Id, item.RepoTags?.[0] || '')}
- disabled={isPullingInline[item.Id] || !item.RepoTags?.[0]}
- >
- {#if isPullingInline[item.Id]}
- <Loader2 class="size-4 animate-spin" />
- Pulling...
- {:else}
- <Download class="size-4" />
- Pull
- {/if}
- </DropdownMenu.Item>
- <DropdownMenu.Separator />
- <DropdownMenu.Item
- class="focus:text-red-700! text-red-500"
- onclick={() => handleDeleteSelected()}
- disabled={isLoading.removing}
- >
- {#if isLoading.removing}
- <Loader2 class="size-4 animate-spin" />
- {:else}
- <Trash2 class="size-4" />
- {/if}
- Remove
- </DropdownMenu.Item>
- </DropdownMenu.Group>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- </Table.Cell>
- {/snippet}
- </UniversalTable>
- </Card.Content>
- </Card.Root>
- {:else if !error}
- <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
- <HardDrive class="text-muted-foreground mb-4 size-12 opacity-40" />
- <p class="text-lg font-medium">No images found</p>
- <p class="text-muted-foreground mt-1 max-w-md text-sm">
- Pull an image using the "Pull Image" button above
- </p>
- <div class="mt-4 flex gap-3">
- <Button variant="outline" onclick={() => (isPullDialogOpen = true)}>
- <Download class="size-4" />
- Pull Image
- </Button>
- </div>
- </div>
- {/if}
+ <ImageTable
+ images={enhancedImages}
+ bind:selectedIds
+ {requestOptions}
+ {onRefresh}
+ onImagesChanged={loadImages}
+ onPullDialogOpen={() => (isPullDialogOpen = true)}
+ onTriggerBulkMaturityCheck={handleTriggerBulkMaturityCheck}
+ />
<ImagePullSheet bind:open={isPullDialogOpen} onPullFinished={() => loadImages()} />
@@ -489,18 +202,20 @@
<Dialog.Content>
<Dialog.Header>
<Dialog.Title>Prune Unused Images</Dialog.Title>
- <Dialog.Description
- >Are you sure you want to remove all unused (dangling) Docker images? This will free up
+ <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
- >
+ affected.
+ </Dialog.Description>
</Dialog.Header>
<div class="flex justify-end gap-3 pt-6">
<Button
variant="outline"
onclick={() => (isConfirmPruneDialogOpen = false)}
- disabled={isLoading.pruning}>Cancel</Button
+ disabled={isLoading.pruning}
>
+ Cancel
+ </Button>
<Button variant="destructive" onclick={handlePruneImages} disabled={isLoading.pruning}>
{#if isLoading.pruning}
<Loader2 class="mr-2 size-4 animate-spin" /> Prune Images
@@ -515,6 +230,20 @@
</div>
<style>
+ :global(body) {
+ overflow-x: hidden;
+ }
+
+ :global([data-radix-popper-content-wrapper]) {
+ position: fixed !important;
+ z-index: 50;
+ }
+
+ :global([data-radix-dropdown-menu-content]) {
+ position: fixed !important;
+ z-index: 50;
+ }
+
:global(.tooltip-with-arrow) {
position: relative;
overflow: visible;
diff --git a/frontend/src/routes/images/+page.ts b/frontend/src/routes/images/+page.ts
new file mode 100644
index 000000000..5bcfff451
--- /dev/null
+++ b/frontend/src/routes/images/+page.ts
@@ -0,0 +1,25 @@
+import { environmentAPI } from '$lib/services/api';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async () => {
+ const imageRequestOptions: SearchPaginationSortRequest = {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'Created',
+ direction: 'desc' as const
+ }
+ };
+
+ const images = await environmentAPI.getImages(
+ imageRequestOptions.pagination,
+ imageRequestOptions.sort,
+ imageRequestOptions.search,
+ imageRequestOptions.filters
+ );
+
+ return { images, imageRequestOptions };
+};
\ No newline at end of file
diff --git a/frontend/src/routes/images/[imageId]/+page.svelte b/frontend/src/routes/images/[imageId]/+page.svelte
index a745fb2a9..9a4d625e2 100644
--- a/frontend/src/routes/images/[imageId]/+page.svelte
+++ b/frontend/src/routes/images/[imageId]/+page.svelte
@@ -69,7 +69,6 @@
</script>
<div class="space-y-6 pb-8">
- <!-- Breadcrumb Navigation -->
<div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
<div>
<Breadcrumb.Root>
diff --git a/frontend/src/routes/images/[imageId]/+page.ts b/frontend/src/routes/images/[imageId]/+page.ts
index c4f264c20..83ac1d03a 100644
--- a/frontend/src/routes/images/[imageId]/+page.ts
+++ b/frontend/src/routes/images/[imageId]/+page.ts
@@ -31,7 +31,7 @@ export const load = async ({ params }): Promise<ImageDetailData> => {
return {
image: {
- ...image,
+ ...image.data,
repo,
tag
}
diff --git a/frontend/src/routes/images/image-table.svelte b/frontend/src/routes/images/image-table.svelte
new file mode 100644
index 000000000..2583e936d
--- /dev/null
+++ b/frontend/src/routes/images/image-table.svelte
@@ -0,0 +1,335 @@
+<script lang="ts">
+ import type { EnhancedImageInfo } from '$lib/models/image.type';
+ import ArcaneTable from '$lib/components/arcane-table.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import {
+ Download,
+ HardDrive,
+ Trash2,
+ Loader2,
+ ChevronDown,
+ Ellipsis,
+ ScanSearch,
+ Funnel
+ } from '@lucide/svelte';
+ import * as Card from '$lib/components/ui/card/index.js';
+ import { goto } from '$app/navigation';
+ import { toast } from 'svelte-sonner';
+ import { formatBytes } from '$lib/utils/bytes.util';
+ 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 StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import ArcaneButton from '$lib/components/arcane-button.svelte';
+ import MaturityItem from '$lib/components/maturity-item.svelte';
+ import { environmentAPI } from '$lib/services/api';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+
+ interface ImageWithId extends EnhancedImageInfo {
+ id: string;
+ }
+
+ let {
+ images,
+ selectedIds = $bindable(),
+ requestOptions = $bindable(),
+ onRefresh,
+ onImagesChanged,
+ onPullDialogOpen,
+ onTriggerBulkMaturityCheck
+ }: {
+ images: EnhancedImageInfo[];
+ selectedIds: string[];
+ requestOptions: SearchPaginationSortRequest;
+ onRefresh: (options: SearchPaginationSortRequest) => Promise<any>;
+ onImagesChanged: () => Promise<void>;
+ onPullDialogOpen: () => void;
+ onTriggerBulkMaturityCheck: () => Promise<void>;
+ } = $props();
+
+ let imageFilters = $state({
+ showUsed: true,
+ showUnused: true
+ });
+
+ let isLoading = $state({
+ removing: false,
+ checking: false
+ });
+
+ let isPullingInline = $state<Record<string, boolean>>({});
+
+ const imagesWithId = $derived(
+ images.map((img) => ({
+ ...img,
+ id: img.Id
+ }))
+ );
+
+ const filteredImages = $derived(
+ imagesWithId.filter((img) => {
+ const showBecauseUsed = imageFilters.showUsed && img.InUse;
+ const showBecauseUnused = imageFilters.showUnused && !img.InUse;
+ return showBecauseUsed || showBecauseUnused;
+ })
+ );
+
+ const paginatedImages: Paginated<ImageWithId> = $derived({
+ data: filteredImages,
+ pagination: {
+ totalPages: Math.ceil(filteredImages.length / (requestOptions.pagination?.limit || 20)),
+ totalItems: filteredImages.length,
+ currentPage: requestOptions.pagination?.page || 1,
+ itemsPerPage: requestOptions.pagination?.limit || 20
+ }
+ });
+
+ async function handleDeleteSelected() {
+ if (selectedIds.length === 0) return;
+
+ openConfirmDialog({
+ title: `Remove ${selectedIds.length} Image${selectedIds.length > 1 ? 's' : ''}`,
+ message: `Are you sure you want to remove the selected image${selectedIds.length > 1 ? 's' : ''}? This action cannot be undone.`,
+ confirm: {
+ label: 'Remove',
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+ let successCount = 0;
+ let failureCount = 0;
+
+ for (const id of selectedIds) {
+ const result = await tryCatch(environmentAPI.deleteImage(id));
+ handleApiResultWithCallbacks({
+ result,
+ message: `Failed to remove image`,
+ setLoadingState: () => {},
+ onSuccess: () => {
+ successCount++;
+ }
+ });
+
+ if (result.error) {
+ failureCount++;
+ }
+ }
+
+ isLoading.removing = false;
+
+ if (successCount > 0) {
+ toast.success(
+ `Successfully removed ${successCount} image${successCount > 1 ? 's' : ''}`
+ );
+ await onImagesChanged();
+ }
+
+ if (failureCount > 0) {
+ toast.error(`Failed to remove ${failureCount} image${failureCount > 1 ? 's' : ''}`);
+ }
+
+ selectedIds = [];
+ }
+ }
+ });
+ }
+
+ async function handleInlineImagePull(imageId: string, repoTag: string) {
+ if (!repoTag || repoTag === '<none>:<none>') {
+ toast.error('Cannot pull image without repository tag');
+ return;
+ }
+
+ isPullingInline[imageId] = true;
+
+ const result = await tryCatch(environmentAPI.pullImage(repoTag));
+ handleApiResultWithCallbacks({
+ result,
+ message: 'Failed to Pull Image',
+ setLoadingState: () => {},
+ onSuccess: async () => {
+ toast.success(`Successfully pulled ${repoTag}`);
+ await onImagesChanged();
+ }
+ });
+
+ isPullingInline[imageId] = false;
+ }
+
+ async function handleTriggerBulkMaturityCheckInternal() {
+ isLoading.checking = true;
+ await onTriggerBulkMaturityCheck();
+ isLoading.checking = false;
+ }
+</script>
+
+{#if filteredImages.length > 0}
+ <Card.Root class="border shadow-sm">
+ <Card.Header class="px-6">
+ <div class="flex items-center justify-between">
+ <div>
+ <Card.Title>Images List</Card.Title>
+ </div>
+ <div class="flex items-center gap-2">
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button {...props} variant="outline" size="sm">
+ <Funnel class="mr-2 size-4" />
+ Filter
+ <ChevronDown class="ml-2 size-4" />
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content>
+ <DropdownMenu.Label>Image Usage</DropdownMenu.Label>
+ <DropdownMenu.CheckboxItem
+ checked={imageFilters.showUsed}
+ onCheckedChange={(checked) => {
+ imageFilters.showUsed = checked;
+ }}
+ >
+ Show Used Images
+ </DropdownMenu.CheckboxItem>
+ <DropdownMenu.CheckboxItem
+ checked={imageFilters.showUnused}
+ onCheckedChange={(checked) => {
+ imageFilters.showUnused = checked;
+ }}
+ >
+ Show Unused Images
+ </DropdownMenu.CheckboxItem>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ {#if selectedIds.length > 0}
+ <ArcaneButton
+ action="remove"
+ onClick={() => handleDeleteSelected()}
+ loading={isLoading.removing}
+ disabled={isLoading.removing}
+ />
+ {/if}
+ <ArcaneButton action="pull" label="Pull Image" onClick={onPullDialogOpen} />
+ <ArcaneButton
+ action="inspect"
+ label="Recheck Maturities"
+ onClick={handleTriggerBulkMaturityCheckInternal}
+ loading={isLoading.checking}
+ loadingLabel="Checking..."
+ disabled={isLoading.checking}
+ />
+ </div>
+ </div>
+ </Card.Header>
+ <Card.Content>
+ <ArcaneTable
+ items={paginatedImages}
+ bind:requestOptions
+ bind:selectedIds
+ {onRefresh}
+ columns={[
+ { label: 'Repository', sortColumn: 'RepoTags' },
+ { label: 'Image ID' },
+ { label: 'Size', sortColumn: 'Size' },
+ { label: 'Created', sortColumn: 'Created' },
+ { label: 'Status', sortColumn: 'InUse' },
+ { label: 'Maturity' },
+ { label: ' ' }
+ ]}
+ filterPlaceholder="Search images..."
+ noResultsMessage="No images found"
+ >
+ {#snippet rows({ item })}
+ <Table.Cell>
+ {#if item.RepoTags && item.RepoTags.length > 0 && item.RepoTags[0] !== '<none>:<none>'}
+ {item.RepoTags[0]}
+ {:else}
+ <span class="text-muted-foreground italic">Untagged</span>
+ {/if}
+ </Table.Cell>
+ <Table.Cell>
+ <code class="bg-muted rounded px-2 py-1 text-xs"
+ >{item.Id?.substring(7, 19) || 'N/A'}</code
+ >
+ </Table.Cell>
+ <Table.Cell>{formatBytes(item.Size || 0)}</Table.Cell>
+ <Table.Cell>{new Date((item.Created || 0) * 1000).toLocaleDateString()}</Table.Cell>
+ <Table.Cell>
+ {#if item.InUse}
+ <StatusBadge text="In Use" variant="green" />
+ {:else}
+ <StatusBadge text="Unused" variant="amber" />
+ {/if}
+ </Table.Cell>
+ <Table.Cell>
+ {#if item.maturity}
+ <MaturityItem maturity={item.maturity} imageId={item.Id} />
+ {:else}
+ <span class="text-muted-foreground text-sm">N/A</span>
+ {/if}
+ </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="size-4" />
+ Inspect
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ onclick={() => handleInlineImagePull(item.Id, item.RepoTags?.[0] || '')}
+ disabled={isPullingInline[item.Id] || !item.RepoTags?.[0]}
+ >
+ {#if isPullingInline[item.Id]}
+ <Loader2 class="size-4 animate-spin" />
+ Pulling...
+ {:else}
+ <Download class="size-4" />
+ Pull
+ {/if}
+ </DropdownMenu.Item>
+ <DropdownMenu.Separator />
+ <DropdownMenu.Item
+ class="focus:text-red-700! text-red-500"
+ onclick={() => handleDeleteSelected()}
+ disabled={isLoading.removing}
+ >
+ {#if isLoading.removing}
+ <Loader2 class="size-4 animate-spin" />
+ {:else}
+ <Trash2 class="size-4" />
+ {/if}
+ Remove
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </ArcaneTable>
+ </Card.Content>
+ </Card.Root>
+{:else}
+ <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
+ <HardDrive class="text-muted-foreground mb-4 size-12 opacity-40" />
+ <p class="text-lg font-medium">No images found</p>
+ <p class="text-muted-foreground mt-1 max-w-md text-sm">
+ Pull an image using the "Pull Image" button above
+ </p>
+ <div class="mt-4 flex gap-3">
+ <Button variant="outline" onclick={onPullDialogOpen}>
+ <Download class="size-4" />
+ Pull Image
+ </Button>
+ </div>
+ </div>
+{/if}
diff --git a/frontend/src/routes/networks/+page.svelte b/frontend/src/routes/networks/+page.svelte
index 99a92bea8..984e4c271 100644
--- a/frontend/src/routes/networks/+page.svelte
+++ b/frontend/src/routes/networks/+page.svelte
@@ -1,76 +1,102 @@
<script lang="ts">
- import {
- Trash2,
- Plus,
- Network,
- Ellipsis,
- ScanSearch,
- Loader2,
- EthernetPort
- } from '@lucide/svelte';
- import { Button } from '$lib/components/ui/button/index.js';
- import * as Card from '$lib/components/ui/card/index.js';
+ import { Network, EthernetPort } from '@lucide/svelte';
import * as Alert from '$lib/components/ui/alert/index.js';
- import * as Table from '$lib/components/ui/table';
- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
import { toast } from 'svelte-sonner';
- import { goto } from '$app/navigation';
- import { openConfirmDialog } from '$lib/components/confirm-dialog';
- import type { PageData } from './$types';
import type { NetworkCreateOptions, NetworkInspectInfo } from 'dockerode';
- import UniversalTable from '$lib/components/universal-table.svelte';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import CreateNetworkSheet from '$lib/components/sheets/create-network-sheet.svelte';
import { environmentAPI } from '$lib/services/api';
- import { DEFAULT_NETWORK_NAMES } from '$lib/constants';
import ArcaneButton from '$lib/components/arcane-button.svelte';
- import { tablePersistence } from '$lib/stores/table-store';
- import { onMount } from 'svelte';
import StatCard from '$lib/components/stat-card.svelte';
+ import NetworkTable from './network-table.svelte';
+ import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
+ import type { PageData } from './$types';
+
+ interface NetworkWithId extends NetworkInspectInfo {
+ id: string;
+ }
let { data }: { data: PageData } = $props();
- let networks = $state(<NetworkInspectInfo[]>[]);
- let selectedNetworks = $state(<string[]>[]);
+ let networks = $state<NetworkInspectInfo[]>([]);
+ let paginatedNetworks = $state<Paginated<NetworkWithId & { ID: string }> | null>(null);
+ let selectedIds = $state<string[]>([]);
let error = $state<string | null>(null);
- let isLoadingNetworks = $state(true);
let isCreateDialogOpen = $state(false);
+ let requestOptions = $state<SearchPaginationSortRequest>(data.networkRequestOptions);
let isLoading = $state({
create: false,
- remove: false,
refresh: false
});
+ $effect(() => {
+ if (data.networks) {
+ if (Array.isArray(data.networks)) {
+ networks = data.networks;
+ const paginatedData: Paginated<NetworkWithId & { ID: string }> = {
+ data: data.networks.map((n) => ({ ...n, id: n.Id, ID: n.Id })),
+ pagination: {
+ totalPages: 1,
+ totalItems: data.networks.length,
+ currentPage: 1,
+ itemsPerPage: data.networks.length
+ }
+ };
+ paginatedNetworks = paginatedData;
+ } else {
+ const paginatedData: Paginated<NetworkWithId & { ID: string }> = {
+ data: data.networks.data.map((n) => ({ ...n, id: n.Id, ID: n.Id })),
+ pagination: data.networks.pagination
+ };
+ paginatedNetworks = paginatedData;
+ networks = data.networks.data || [];
+ }
+ }
+ });
+
const totalNetworks = $derived(networks.length);
const bridgeNetworks = $derived(networks.filter((n) => n.Driver === 'bridge').length);
- const overlayNetworks = $derived(networks.filter((n) => n.Driver === 'overlay').length);
- async function loadNetworks() {
- try {
- isLoadingNetworks = true;
- const response = await environmentAPI.getNetworks();
- networks = Array.isArray(response) ? response : [];
- error = null;
- } catch (err) {
- console.error('Failed to load networks:', err);
- error = err instanceof Error ? err.message : 'Failed to load networks';
- networks = [];
- } finally {
- isLoadingNetworks = false;
+ async function onRefresh(
+ options: SearchPaginationSortRequest
+ ): Promise<Paginated<NetworkWithId & { ID: string }>> {
+ const response = await environmentAPI.getNetworks(
+ options.pagination,
+ options.sort,
+ options.search,
+ options.filters
+ );
+
+ if (Array.isArray(response)) {
+ networks = response;
+ const paginatedResponse: Paginated<NetworkWithId & { ID: string }> = {
+ data: response.map((n) => ({ ...n, id: n.Id, ID: n.Id })),
+ pagination: {
+ totalPages: 1,
+ totalItems: response.length,
+ currentPage: options.pagination?.page || 1,
+ itemsPerPage: response.length
+ }
+ };
+ paginatedNetworks = paginatedResponse;
+ return paginatedResponse;
+ } else {
+ const paginatedResponse: Paginated<NetworkWithId & { ID: string }> = {
+ data: response.data.map((n) => ({ ...n, id: n.Id, ID: n.Id })),
+ pagination: response.pagination
+ };
+ paginatedNetworks = paginatedResponse;
+ networks = response.data || [];
+ return paginatedResponse;
}
}
- onMount(() => {
- loadNetworks();
- });
-
async function refreshNetworks() {
isLoading.refresh = true;
try {
- const refreshedNetworks = await environmentAPI.getNetworks();
- networks = Array.isArray(refreshedNetworks) ? refreshedNetworks : [];
+ await onRefresh(requestOptions);
} catch (error) {
console.error('Failed to refresh networks:', error);
toast.error('Failed to refresh networks');
@@ -79,6 +105,10 @@
}
}
+ async function onNetworksChanged() {
+ await refreshNetworks();
+ }
+
async function handleCreateNetworkSubmit(options: NetworkCreateOptions) {
isLoading.create = true;
handleApiResultWithCallbacks({
@@ -87,88 +117,11 @@
setLoadingState: (value) => (isLoading.create = value),
onSuccess: async () => {
toast.success(`Network "${options.Name}" Created Successfully.`);
- await loadNetworks();
+ await refreshNetworks();
isCreateDialogOpen = false;
}
});
}
-
- async function handleDeleteNetwork(id: string, name: string) {
- if (DEFAULT_NETWORK_NAMES.has(name)) {
- toast.error(`Cannot delete default network: ${name}`);
- return;
- }
- openConfirmDialog({
- title: 'Delete Network',
- message: `Are you sure you want to delete network "${name}"? This action cannot be undone.`,
- confirm: {
- label: 'Delete',
- destructive: true,
- action: async () => {
- handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.deleteNetwork(id)),
- message: `Failed to Remove Network "${name}"`,
- setLoadingState: (value) => (isLoading.remove = value),
- onSuccess: async () => {
- toast.success(`Network "${name}" Removed Successfully.`);
- await loadNetworks();
- }
- });
- }
- }
- });
- }
-
- async function handleDeleteSelectedNetworks() {
- const selectedNetworkList = networks.filter((network) => selectedNetworks.includes(network.Id));
- const defaultNetworks = selectedNetworkList.filter((network) =>
- DEFAULT_NETWORK_NAMES.has(network.Name)
- );
-
- if (defaultNetworks.length > 0) {
- toast.error(
- `Cannot delete default networks: ${defaultNetworks.map((n) => n.Name).join(', ')}`
- );
- return;
- }
-
- openConfirmDialog({
- title: 'Delete Selected Networks',
- message: `Are you sure you want to delete ${selectedNetworks.length} selected network(s)? This action cannot be undone.`,
- confirm: {
- label: 'Delete',
- destructive: true,
- action: async () => {
- isLoading.remove = true;
-
- let successCount = 0;
- let failureCount = 0;
-
- for (const networkId of selectedNetworks) {
- const network = networks.find((n) => n.Id === networkId);
- if (!network) continue;
-
- const result = await tryCatch(environmentAPI.deleteNetwork(networkId));
- if (result.error) {
- failureCount++;
- toast.error(`Failed to delete network "${network.Name}": ${result.error.message}`);
- } else {
- successCount++;
- toast.success(`Network "${network.Name}" deleted successfully.`);
- }
- }
-
- isLoading.remove = false;
- if (successCount > 0) {
- setTimeout(async () => {
- await loadNetworks();
- }, 500);
- }
- selectedNetworks = [];
- }
- }
- });
- }
</script>
<div class="space-y-6">
@@ -195,164 +148,39 @@
</Alert.Root>
{/if}
- {#if isLoadingNetworks}
- <div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
- {#each Array(3) as _}
- <Card.Root>
- <Card.Content class="flex items-center justify-between p-4">
- <div class="space-y-2">
- <div class="bg-muted h-4 w-24 animate-pulse rounded"></div>
- <div class="bg-muted h-8 w-12 animate-pulse rounded"></div>
- </div>
- <div class="bg-muted size-10 animate-pulse rounded-full"></div>
- </Card.Content>
- </Card.Root>
- {/each}
- </div>
-
- <Card.Root class="border shadow-sm">
- <Card.Header class="px-6">
- <div class="flex items-center justify-between">
- <Card.Title>Network List</Card.Title>
- <div class="flex items-center gap-2">
- <div class="bg-muted h-9 w-28 animate-pulse rounded"></div>
- </div>
- </div>
- </Card.Header>
- <Card.Content>
- <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
- <Loader2 class="text-muted-foreground mb-4 size-8 animate-spin" />
- <p class="text-lg font-medium">Loading Networks...</p>
- <p class="text-muted-foreground mt-1 text-sm">Please wait while we fetch your networks</p>
- </div>
- </Card.Content>
- </Card.Root>
- {:else}
- <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
- <StatCard
- title="Total Networks"
- value={totalNetworks}
- icon={Network}
- iconColor="text-blue-500"
- class="border-l-4 border-l-blue-500"
- />
- <StatCard
- title="Bridge Networks"
- value={bridgeNetworks}
- icon={EthernetPort}
- iconColor="text-green-500"
- class="border-l-4 border-l-green-500"
- />
- </div>
-
- {#if networks && networks.length > 0}
- <Card.Root class="border shadow-sm">
- <Card.Header class="px-6">
- <div class="flex items-center justify-between">
- <Card.Title>Network List</Card.Title>
- <div class="flex items-center gap-2">
- {#if selectedNetworks.length > 0}
- <ArcaneButton
- action="remove"
- onClick={handleDeleteSelectedNetworks}
- loading={isLoading.remove}
- disabled={isLoading.remove}
- />
- {/if}
- <ArcaneButton
- action="create"
- label="Create Network"
- onClick={() => (isCreateDialogOpen = true)}
- loading={isLoading.create}
- disabled={isLoading.create}
- />
- </div>
- </div>
- </Card.Header>
+ <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
+ <StatCard
+ title="Total Networks"
+ value={totalNetworks}
+ icon={Network}
+ iconColor="text-blue-500"
+ class="border-l-4 border-l-blue-500"
+ />
+ <StatCard
+ title="Bridge Networks"
+ value={bridgeNetworks}
+ icon={EthernetPort}
+ iconColor="text-green-500"
+ class="border-l-4 border-l-green-500"
+ />
+ </div>
- <Card.Content>
- <UniversalTable
- data={networks}
- columns={[
- { accessorKey: 'Name', header: 'Name' },
- { accessorKey: 'Id', header: 'Network ID', enableSorting: false },
- { accessorKey: 'Driver', header: 'Driver' },
- { accessorKey: 'Scope', header: 'Scope' },
- { accessorKey: 'actions', header: ' ', enableSorting: false }
- ]}
- idKey="Id"
- display={{
- filterPlaceholder: 'Search networks...',
- noResultsMessage: 'No networks found'
- }}
- pagination={{
- pageSize: tablePersistence.getPageSize('networks')
- }}
- onPageSizeChange={(newSize) => {
- tablePersistence.setPageSize('networks', newSize);
- }}
- sort={{
- defaultSort: { id: 'Name', desc: false }
- }}
- bind:selectedIds={selectedNetworks}
- >
- {#snippet rows({ item })}
- <Table.Cell>
- <a class="font-medium hover:underline" href="/networks/{item.Id}/">{item.Name}</a>
- </Table.Cell>
- <Table.Cell class="truncate font-mono text-sm">{item.Id}</Table.Cell>
- <Table.Cell>{item.Driver}</Table.Cell>
- <Table.Cell>{item.Scope}</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}`)}>
- <ScanSearch class="size-4" />
- Inspect
- </DropdownMenu.Item>
- <DropdownMenu.Item
- class="focus:text-red-700! text-red-500"
- onclick={() => handleDeleteNetwork(item.Id, item.Name)}
- disabled={DEFAULT_NETWORK_NAMES.has(item.Name)}
- >
- <Trash2 class="size-4" />
- Remove
- </DropdownMenu.Item>
- </DropdownMenu.Group>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- </Table.Cell>
- {/snippet}
- </UniversalTable>
- </Card.Content>
- </Card.Root>
- {:else if !error}
- <div
- class="bg-card flex flex-col items-center justify-center rounded-lg border px-6 py-12 text-center"
- >
- <Network class="text-muted-foreground mb-4 size-12 opacity-40" />
- <p class="text-lg font-medium">No networks found</p>
- <p class="text-muted-foreground mt-1 max-w-md text-sm">
- Create a new network using the "Create Network" button above or use the Docker CLI
- </p>
- <div class="mt-4 flex gap-3">
- <Button variant="outline" size="sm" onclick={() => (isCreateDialogOpen = true)}>
- <Plus class="size-4" />
- Create Network
- </Button>
- </div>
- </div>
- {/if}
- {/if}
+ <NetworkTable
+ networks={paginatedNetworks || {
+ data: networks.map((n) => ({ ...n, id: n.Id, ID: n.Id })),
+ pagination: {
+ totalPages: 1,
+ totalItems: networks.length,
+ currentPage: 1,
+ itemsPerPage: networks.length
+ }
+ }}
+ bind:selectedIds
+ bind:requestOptions
+ {onRefresh}
+ {onNetworksChanged}
+ onCreateNetwork={() => (isCreateDialogOpen = true)}
+ />
<CreateNetworkSheet
bind:open={isCreateDialogOpen}
diff --git a/frontend/src/routes/networks/+page.ts b/frontend/src/routes/networks/+page.ts
new file mode 100644
index 000000000..1ce9938ef
--- /dev/null
+++ b/frontend/src/routes/networks/+page.ts
@@ -0,0 +1,25 @@
+import { environmentAPI } from '$lib/services/api';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async () => {
+ const networkRequestOptions: SearchPaginationSortRequest = {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'Name',
+ direction: 'asc' as const
+ }
+ };
+
+ const networks = await environmentAPI.getNetworks(
+ networkRequestOptions.pagination,
+ networkRequestOptions.sort,
+ networkRequestOptions.search,
+ networkRequestOptions.filters
+ );
+
+ return { networks, networkRequestOptions };
+};
\ No newline at end of file
diff --git a/frontend/src/routes/networks/[networkId]/+page.ts b/frontend/src/routes/networks/[networkId]/+page.ts
index 65d8f6330..5e18e5e69 100644
--- a/frontend/src/routes/networks/[networkId]/+page.ts
+++ b/frontend/src/routes/networks/[networkId]/+page.ts
@@ -13,7 +13,7 @@ export const load: PageLoad = async ({ params }) => {
}
return {
- network
+ network: network.data
};
} catch (err: any) {
console.error('Failed to load network:', err);
diff --git a/frontend/src/routes/networks/network-table.svelte b/frontend/src/routes/networks/network-table.svelte
new file mode 100644
index 000000000..cb39e2052
--- /dev/null
+++ b/frontend/src/routes/networks/network-table.svelte
@@ -0,0 +1,264 @@
+<script lang="ts">
+ import type { NetworkSummary } from '$lib/types/network.type';
+ import ArcaneTable from '$lib/components/arcane-table.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { ScanSearch, Trash2, Ellipsis, Network } from '@lucide/svelte';
+ import * as Card from '$lib/components/ui/card/index.js';
+ import { goto } from '$app/navigation';
+ import { toast } from 'svelte-sonner';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import ArcaneButton from '$lib/components/arcane-button.svelte';
+ import { environmentAPI } from '$lib/services/api';
+ import { DEFAULT_NETWORK_NAMES } from '$lib/constants';
+ import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
+ import * as Table from '$lib/components/ui/table';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { formatFriendlyDate } from '$lib/utils/date.utils';
+
+ interface NetworkWithId extends NetworkSummary {
+ id: string;
+ }
+
+ let {
+ networks,
+ selectedIds = $bindable(),
+ requestOptions = $bindable(),
+ onRefresh,
+ onNetworksChanged,
+ onCreateNetwork
+ }: {
+ networks: Paginated<NetworkSummary>;
+ selectedIds: string[];
+ requestOptions: SearchPaginationSortRequest;
+ onRefresh: (options: SearchPaginationSortRequest) => Promise<Paginated<NetworkSummary>>;
+ onNetworksChanged: () => Promise<void>;
+ onCreateNetwork: () => void;
+ } = $props();
+
+ let isLoading = $state({
+ remove: false
+ });
+
+ const transformedNetworks = $derived.by(() => {
+ const transformed: NetworkWithId[] = networks.data.map((network) => ({
+ ...network,
+ id: network.ID
+ }));
+
+ return {
+ data: transformed,
+ pagination: networks.pagination
+ };
+ });
+
+ async function handleRefresh(
+ options: SearchPaginationSortRequest
+ ): Promise<Paginated<NetworkWithId>> {
+ const result = await onRefresh(options);
+ const transformed: NetworkWithId[] = result.data.map((network) => ({
+ ...network,
+ id: network.ID
+ }));
+
+ return {
+ data: transformed,
+ pagination: result.pagination
+ };
+ }
+
+ async function handleDeleteNetwork(id: string, name: string) {
+ if (DEFAULT_NETWORK_NAMES.has(name)) {
+ toast.error(`Cannot delete default network: ${name}`);
+ return;
+ }
+ openConfirmDialog({
+ title: 'Delete Network',
+ message: `Are you sure you want to delete network "${name}"? This action cannot be undone.`,
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.deleteNetwork(id)),
+ message: `Failed to Remove Network "${name}"`,
+ setLoadingState: (value) => (isLoading.remove = value),
+ onSuccess: async () => {
+ toast.success(`Network "${name}" Removed Successfully.`);
+ await onNetworksChanged();
+ }
+ });
+ }
+ }
+ });
+ }
+
+ async function handleDeleteSelectedNetworks() {
+ const selectedNetworkList = networks.data.filter((network) => selectedIds.includes(network.ID));
+ const defaultNetworks = selectedNetworkList.filter((network) =>
+ DEFAULT_NETWORK_NAMES.has(network.Name)
+ );
+
+ if (defaultNetworks.length > 0) {
+ toast.error(
+ `Cannot delete default networks: ${defaultNetworks.map((n) => n.Name).join(', ')}`
+ );
+ return;
+ }
+
+ openConfirmDialog({
+ title: 'Delete Selected Networks',
+ message: `Are you sure you want to delete ${selectedIds.length} selected network(s)? This action cannot be undone.`,
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ isLoading.remove = true;
+
+ let successCount = 0;
+ let failureCount = 0;
+
+ for (const networkId of selectedIds) {
+ const network = networks.data.find((n) => n.ID === networkId);
+ if (!network) continue;
+
+ const result = await tryCatch(environmentAPI.deleteNetwork(networkId));
+ if (result.error) {
+ failureCount++;
+ toast.error(`Failed to delete network "${network.Name}": ${result.error.message}`);
+ } else {
+ successCount++;
+ toast.success(`Network "${network.Name}" deleted successfully.`);
+ }
+ }
+
+ isLoading.remove = false;
+ if (successCount > 0) {
+ setTimeout(async () => {
+ await onNetworksChanged();
+ }, 500);
+ }
+ selectedIds = [];
+ }
+ }
+ });
+ }
+
+ const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
+ const hasNetworks = $derived(networks?.data?.length > 0);
+
+ const getConnectedContainers = (network: NetworkWithId) => {
+ return network.Containers ? Object.keys(network.Containers).length : 0;
+ };
+</script>
+
+{#if hasNetworks}
+ <Card.Root class="border shadow-sm">
+ <Card.Header class="px-6">
+ <div class="flex items-center justify-between">
+ <div>
+ <Card.Title>Network List</Card.Title>
+ </div>
+ <div class="flex items-center gap-2">
+ {#if selectedIds.length > 0}
+ <ArcaneButton
+ action="remove"
+ onClick={handleDeleteSelectedNetworks}
+ loading={isLoading.remove}
+ disabled={isLoading.remove}
+ />
+ {/if}
+ <ArcaneButton action="create" label="Create Network" onClick={onCreateNetwork} />
+ </div>
+ </div>
+ </Card.Header>
+ <Card.Content>
+ <ArcaneTable
+ items={transformedNetworks}
+ bind:requestOptions
+ bind:selectedIds
+ onRefresh={handleRefresh}
+ columns={[
+ { label: 'Name', sortColumn: 'Name' },
+ { label: 'Network ID', sortColumn: 'ID' },
+ { label: 'Driver', sortColumn: 'Driver' },
+ { label: 'Scope', sortColumn: 'Scope' },
+ { label: 'Connected', sortColumn: 'connected' },
+ { label: 'Created', sortColumn: 'Created' },
+ { label: ' ' }
+ ]}
+ filterPlaceholder="Search networks..."
+ noResultsMessage="No networks found"
+ >
+ {#snippet rows({ item })}
+ <Table.Cell>
+ <a class="font-medium hover:underline" href="/networks/{item.ID}/">{item.Name}</a>
+ </Table.Cell>
+ <Table.Cell class="truncate font-mono text-sm">{item.ID}</Table.Cell>
+ <Table.Cell>
+ <StatusBadge
+ variant={item.Driver === 'bridge'
+ ? 'blue'
+ : item.Driver === 'overlay'
+ ? 'purple'
+ : 'gray'}
+ text={item.Driver}
+ />
+ </Table.Cell>
+ <Table.Cell>
+ <StatusBadge variant={item.Scope === 'local' ? 'green' : 'amber'} text={item.Scope} />
+ </Table.Cell>
+ <Table.Cell>
+ <span class="text-sm">{getConnectedContainers(item)} containers</span>
+ </Table.Cell>
+ <Table.Cell>
+ <span class="text-sm">
+ {item.Created ? formatFriendlyDate(item.Created) : 'N/A'}
+ </span>
+ </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="size-4" />
+ Inspect
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ class="focus:text-red-700! text-red-500"
+ onclick={() => handleDeleteNetwork(item.ID, item.Name)}
+ disabled={DEFAULT_NETWORK_NAMES.has(item.Name) || isAnyLoading}
+ >
+ <Trash2 class="size-4" />
+ Remove
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </ArcaneTable>
+ </Card.Content>
+ </Card.Root>
+{:else}
+ <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
+ <Network class="text-muted-foreground mb-4 size-12 opacity-40" />
+ <p class="text-lg font-medium">No networks found</p>
+ <p class="text-muted-foreground mt-1 text-sm">
+ Create a new network using the "Create Network" button above or use the Docker CLI
+ </p>
+ </div>
+{/if}
diff --git a/frontend/src/routes/settings/users/+page.svelte b/frontend/src/routes/settings/users/+page.svelte
index c50693770..a8b06c5c3 100644
--- a/frontend/src/routes/settings/users/+page.svelte
+++ b/frontend/src/routes/settings/users/+page.svelte
@@ -1,204 +1,234 @@
<script lang="ts">
- import * as Card from '$lib/components/ui/card/index.js';
- import { Button } from '$lib/components/ui/button/index.js';
+ import { Users, Shield, UserCheck } from '@lucide/svelte';
+ import * as Alert from '$lib/components/ui/alert/index.js';
import { toast } from 'svelte-sonner';
- import { UserPlus, UserCheck, Ellipsis, Pencil, UserX } from '@lucide/svelte';
- import type { PageData } from './$types';
- import UniversalTable from '$lib/components/universal-table.svelte';
- import type { User } from '$lib/types/user.type';
- import UserFormSheet from '$lib/components/sheets/user-form-sheet.svelte';
- import * as Table from '$lib/components/ui/table';
- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
+ import ArcaneButton from '$lib/components/arcane-button.svelte';
import { userAPI } from '$lib/services/api';
- import { invalidateAll } from '$app/navigation';
- import { openConfirmDialog } from '$lib/components/confirm-dialog';
- import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import StatCard from '$lib/components/stat-card.svelte';
+ import UserTable from './user-table.svelte';
+ import UserFormSheet from '$lib/components/sheets/user-form-sheet.svelte';
+ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import type { User } from '$lib/types/user.type';
+
+ let { data } = $props();
- let { data }: { data: PageData } = $props();
+ let users = $state<User[]>(Array.isArray(data.users) ? data.users : data.users?.data || []);
+ let error = $state<string | null>(null);
+ let selectedIds = $state<string[]>([]);
+ let requestOptions = $state<SearchPaginationSortRequest>(data.userRequestOptions);
- let userPageStates = $state({
- users: <User[]>data.users,
- isUserDialogOpen: false,
- userToEdit: <User | null>null
+ let isDialogOpen = $state({
+ create: false,
+ edit: false
});
+ let userToEdit = $state<User | null>(null);
+
let isLoading = $state({
- saving: false
+ creating: false,
+ editing: false,
+ refresh: false
});
- let userDialogRef: UserFormSheet | null = $state(null);
+ const totalUsers = $derived(users.length);
+ const adminUsers = $derived(users.filter((u) => u.Roles?.includes('admin')).length);
+ const regularUsers = $derived(users.filter((u) => !u.Roles?.includes('admin')).length);
- $effect(() => {
- userPageStates.users = data.users;
- });
+ async function loadUsers() {
+ try {
+ isLoading.refresh = true;
+ const response = await userAPI.getUsers(
+ requestOptions.pagination,
+ requestOptions.sort,
+ requestOptions.search,
+ requestOptions.filters
+ );
+ users = Array.isArray(response) ? response : response.data || [];
+ error = null;
+ } catch (err) {
+ console.error('Failed to load users:', err);
+ error = err instanceof Error ? err.message : 'Failed to load users';
+ users = [];
+ } finally {
+ isLoading.refresh = false;
+ }
+ }
- const roles = [
- { id: 'admin', name: 'Administrator' },
- { id: 'user', name: 'Standard User' },
- { id: 'viewer', name: 'Viewer (read-only)' }
- ];
+ async function onRefresh(options: SearchPaginationSortRequest) {
+ requestOptions = options;
+ await loadUsers();
+ return {
+ data: users,
+ pagination: {
+ totalPages: Math.ceil(users.length / (requestOptions.pagination?.limit || 20)),
+ totalItems: users.length,
+ currentPage: requestOptions.pagination?.page || 1,
+ itemsPerPage: requestOptions.pagination?.limit || 20
+ }
+ };
+ }
- function openCreateUserDialog() {
- userPageStates.userToEdit = null;
- userPageStates.isUserDialogOpen = true;
+ async function refreshUsers() {
+ isLoading.refresh = true;
+ try {
+ await loadUsers();
+ } catch (error) {
+ console.error('Failed to refresh users:', error);
+ toast.error('Failed to refresh users');
+ } finally {
+ isLoading.refresh = false;
+ }
}
- function openEditUserDialog(user: User) {
- userPageStates.userToEdit = user;
- userPageStates.isUserDialogOpen = true;
+ function openCreateDialog() {
+ userToEdit = null;
+ isDialogOpen.create = true;
}
- async function handleDialogSubmit({ user: userData, isEditMode, userId }: { user: Partial<User> & { password?: string }; isEditMode: boolean; userId?: string }) {
- isLoading.saving = true;
-
- handleApiResultWithCallbacks({
- result: await tryCatch(isEditMode ? userAPI.update(userId || '', userData as User) : userAPI.create(userData as User)),
- message: isEditMode ? 'Error Updating User' : 'Error Creating User',
- setLoadingState: (value) => (isLoading.saving = value),
- onSuccess: async () => {
- userPageStates.isUserDialogOpen = false;
- toast.success(isEditMode ? 'User Updated Successfully' : 'User Created Successfully');
- await invalidateAll();
- isLoading.saving = false;
- }
- });
+ function openEditDialog(user: User) {
+ userToEdit = user;
+ isDialogOpen.edit = true;
}
- async function handleRemoveUser(userId: string) {
- openConfirmDialog({
- title: 'Delete User',
- message: 'Are you sure you want to delete this user? This action cannot be undone.',
- confirm: {
- label: 'Delete',
- destructive: true,
- action: async () => {
- handleApiResultWithCallbacks({
- result: await tryCatch(userAPI.delete(userId)),
- message: 'Failed to Delete User',
- setLoadingState: (value) => (isLoading.saving = value),
- onSuccess: async () => {
- toast.success('User Deleted Successfully.');
- await invalidateAll();
- }
- });
+ async function handleUserSubmit({
+ user,
+ isEditMode,
+ userId
+ }: {
+ user: Partial<User> & { password?: string };
+ isEditMode: boolean;
+ userId?: string;
+ }) {
+ const loading = isEditMode ? 'editing' : 'creating';
+ isLoading[loading] = true;
+
+ try {
+ if (isEditMode && userId) {
+ const result = await tryCatch(userAPI.update(userId, user));
+ handleApiResultWithCallbacks({
+ result,
+ message: `Failed to update user "${user.Username}"`,
+ setLoadingState: (value) => (isLoading[loading] = value),
+ onSuccess: async () => {
+ toast.success(`User "${user.Username}" updated successfully.`);
+ await loadUsers();
+ isDialogOpen.edit = false;
+ userToEdit = null;
+ }
+ });
+ } else {
+ if (!user.Username) {
+ toast.error('Username is required');
+ isLoading[loading] = false;
+ return;
}
+
+ const createUser: Omit<User, 'ID' | 'CreatedAt' | 'UpdatedAt'> = {
+ Username: user.Username,
+ DisplayName: user.DisplayName,
+ Email: user.Email,
+ Roles: user.Roles || ['user'],
+ PasswordHash: user.password,
+ RequirePasswordChange: false
+ };
+
+ const result = await tryCatch(userAPI.create(createUser));
+ handleApiResultWithCallbacks({
+ result,
+ message: `Failed to create user "${user.Username}"`,
+ setLoadingState: (value) => (isLoading[loading] = value),
+ onSuccess: async () => {
+ toast.success(`User "${user.Username}" created successfully.`);
+ await loadUsers();
+ isDialogOpen.create = false;
+ }
+ });
}
- });
+ } catch (error) {
+ console.error('Failed to submit user:', error);
+ }
}
</script>
-<UserFormSheet bind:open={userPageStates.isUserDialogOpen} bind:userToEdit={userPageStates.userToEdit} {roles} onSubmit={handleDialogSubmit} bind:this={userDialogRef} isLoading={isLoading.saving} allowUsernameEdit={true} />
-
-<div class="space-y-6">
- <div>
- <h1 class="text-3xl font-bold tracking-tight">User Management</h1>
- <p class="text-muted-foreground mt-1 text-sm">Manage user accounts and permissions</p>
+<div class="space-y-6 pb-8">
+ <div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
+ <div>
+ <h1 class="text-3xl font-bold tracking-tight">Users</h1>
+ <p class="text-muted-foreground mt-1 text-sm">Manage system users and permissions</p>
+ </div>
+ <div class="flex items-center gap-2">
+ <ArcaneButton
+ action="create"
+ label="Create User"
+ onClick={openCreateDialog}
+ loading={isLoading.creating}
+ disabled={isLoading.creating}
+ />
+ <ArcaneButton
+ action="restart"
+ onClick={refreshUsers}
+ label="Refresh"
+ loading={isLoading.refresh}
+ disabled={isLoading.refresh}
+ />
+ </div>
</div>
- <div class="grid h-full grid-cols-1 gap-6">
- <!-- User List Card -->
- <Card.Root class="flex flex-col border shadow-sm">
- <Card.Header class="flex flex-row items-center justify-between space-y-0 pb-3">
- <div class="flex items-center gap-2">
- <div class="rounded-full bg-blue-500/10 p-2">
- <UserCheck class="size-5 text-blue-500" />
- </div>
- <div>
- <Card.Title>User Accounts</Card.Title>
- <Card.Description>Manage local user accounts</Card.Description>
- </div>
- </div>
- <Button class="arcane-button-save" onclick={openCreateUserDialog}>
- <UserPlus class="size-4" />
- Create User
- </Button>
- </Card.Header>
- <Card.Content class="flex flex-1 flex-col">
- {#if userPageStates.users.length > 0}
- <div class="flex h-full flex-1 flex-col">
- <UniversalTable
- data={data.users}
- columns={[
- { accessorKey: 'user', header: 'User' },
- { accessorKey: 'email', header: 'Email' },
- { accessorKey: 'roles', header: 'Roles' },
- { accessorKey: 'source', header: 'Source', enableSorting: false },
- { accessorKey: 'actions', header: ' ' }
- ]}
- idKey="id"
- 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">
- {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>
- <StatusBadge text={item.oidcSubjectId ? 'OIDC' : 'Local'} variant={item.oidcSubjectId ? 'blue' : 'purple'} />
- </Table.Cell>
- <Table.Cell>
- <DropdownMenu.Root>
- <DropdownMenu.Trigger>
- <Button variant="ghost" size="icon" class="size-8">
- <Ellipsis class="size-4" />
- <span class="sr-only">Open menu</span>
- </Button>
- </DropdownMenu.Trigger>
- <DropdownMenu.Content align="end">
- <DropdownMenu.Group>
- {#if !item.oidcSubjectId}
- <DropdownMenu.Item onclick={() => openEditUserDialog(item)}>
- <Pencil class="size-4" />
- Edit
- </DropdownMenu.Item>
- {/if}
- <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleRemoveUser(item.id)}>
- <UserX class="size-4" />
- Remove User
- </DropdownMenu.Item>
- </DropdownMenu.Group>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- </Table.Cell>
- {/snippet}
- </UniversalTable>
- </div>
- {:else}
- <div class="text-muted-foreground py-8 text-center italic">No local users found</div>
- {/if}
- </Card.Content>
- </Card.Root>
+ {#if error}
+ <Alert.Root variant="destructive">
+ <Alert.Title>Error Loading Users</Alert.Title>
+ <Alert.Description>{error}</Alert.Description>
+ </Alert.Root>
+ {/if}
+
+ <div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
+ <StatCard
+ title="Total Users"
+ value={totalUsers}
+ icon={Users}
+ iconColor="text-blue-500"
+ class="border-l-4 border-l-blue-500"
+ />
+ <StatCard
+ title="Administrators"
+ value={adminUsers}
+ icon={Shield}
+ iconColor="text-red-500"
+ class="border-l-4 border-l-red-500"
+ />
+ <StatCard
+ title="Regular Users"
+ value={regularUsers}
+ icon={UserCheck}
+ iconColor="text-green-500"
+ class="border-l-4 border-l-green-500"
+ />
</div>
+
+ <UserTable
+ {users}
+ bind:selectedIds
+ bind:requestOptions
+ {onRefresh}
+ onUsersChanged={loadUsers}
+ onEditUser={openEditDialog}
+ />
+
+ <UserFormSheet
+ bind:open={isDialogOpen.create}
+ userToEdit={null}
+ roles={[]}
+ onSubmit={handleUserSubmit}
+ isLoading={isLoading.creating}
+ />
+
+ <UserFormSheet
+ bind:open={isDialogOpen.edit}
+ {userToEdit}
+ roles={[]}
+ onSubmit={handleUserSubmit}
+ isLoading={isLoading.editing}
+ />
</div>
diff --git a/frontend/src/routes/settings/users/+page.ts b/frontend/src/routes/settings/users/+page.ts
index 3e0aed8ee..15c38c007 100644
--- a/frontend/src/routes/settings/users/+page.ts
+++ b/frontend/src/routes/settings/users/+page.ts
@@ -1,11 +1,31 @@
import { settingsAPI, userAPI } from '$lib/services/api';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+
export const load = async () => {
- const users = await userAPI.list();
const settings = await settingsAPI.getSettings();
+ const userRequestOptions: SearchPaginationSortRequest = {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'Username',
+ direction: 'asc' as const
+ }
+ };
+
+ const users = await userAPI.getUsers(
+ userRequestOptions.pagination,
+ userRequestOptions.sort,
+ userRequestOptions.search,
+ userRequestOptions.filters
+ );
+
return {
settings,
- users
+ users,
+ userRequestOptions
};
};
diff --git a/frontend/src/routes/settings/users/user-table.svelte b/frontend/src/routes/settings/users/user-table.svelte
new file mode 100644
index 000000000..6e38a4b41
--- /dev/null
+++ b/frontend/src/routes/settings/users/user-table.svelte
@@ -0,0 +1,226 @@
+<script lang="ts">
+ import ArcaneTable from '$lib/components/arcane-table.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { Trash2, Users, Ellipsis, Edit } from '@lucide/svelte';
+ import * as Card from '$lib/components/ui/card/index.js';
+ import { toast } from 'svelte-sonner';
+ 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 StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import ArcaneButton from '$lib/components/arcane-button.svelte';
+ import { formatFriendlyDate } from '$lib/utils/date.utils';
+ import { userAPI } from '$lib/services/api';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import type { User } from '$lib/types/user.type';
+
+ let {
+ users,
+ selectedIds = $bindable(),
+ requestOptions = $bindable(),
+ onRefresh,
+ onUsersChanged,
+ onEditUser
+ }: {
+ users: User[];
+ selectedIds: string[];
+ requestOptions: SearchPaginationSortRequest;
+ onRefresh: (options: SearchPaginationSortRequest) => Promise<any>;
+ onUsersChanged: () => Promise<void>;
+ onEditUser: (user: User) => void;
+ } = $props();
+
+ let isLoading = $state({
+ removing: false
+ });
+
+ type UserWithId = User & { id: string };
+
+ const usersWithId = $derived(
+ (users || []).map((user) => ({
+ ...user,
+ id: user.ID
+ }))
+ );
+
+ const paginatedUsers: Paginated<UserWithId> = $derived({
+ data: usersWithId as UserWithId[],
+ pagination: {
+ totalPages: Math.ceil(usersWithId.length / (requestOptions.pagination?.limit || 20)),
+ totalItems: usersWithId.length,
+ currentPage: requestOptions.pagination?.page || 1,
+ itemsPerPage: requestOptions.pagination?.limit || 20
+ }
+ });
+
+ async function handleDeleteSelected() {
+ if (selectedIds.length === 0) return;
+
+ openConfirmDialog({
+ title: `Delete ${selectedIds.length} User${selectedIds.length > 1 ? 's' : ''}`,
+ message: `Are you sure you want to delete the selected user${selectedIds.length > 1 ? 's' : ''}? This action cannot be undone.`,
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+ let successCount = 0;
+ let failureCount = 0;
+
+ for (const userId of selectedIds) {
+ const result = await tryCatch(userAPI.delete(userId));
+ handleApiResultWithCallbacks({
+ result,
+ message: `Failed to delete user ${userId}`,
+ setLoadingState: () => {},
+ onSuccess: () => {
+ successCount++;
+ }
+ });
+
+ if (result.error) {
+ failureCount++;
+ }
+ }
+
+ isLoading.removing = false;
+
+ if (successCount > 0) {
+ toast.success(
+ `Successfully deleted ${successCount} user${successCount > 1 ? 's' : ''}`
+ );
+ await onUsersChanged();
+ }
+
+ if (failureCount > 0) {
+ toast.error(`Failed to delete ${failureCount} user${failureCount > 1 ? 's' : ''}`);
+ }
+
+ selectedIds = [];
+ }
+ }
+ });
+ }
+
+ async function handleDeleteUser(userId: string, username: string) {
+ openConfirmDialog({
+ title: `Delete User "${username}"`,
+ message: `Are you sure you want to delete the user "${username}"? This action cannot be undone.`,
+ confirm: {
+ label: 'Delete',
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(userAPI.delete(userId)),
+ message: `Failed to delete user "${username}"`,
+ setLoadingState: (value) => (isLoading.removing = value),
+ onSuccess: async () => {
+ toast.success(`User "${username}" deleted successfully.`);
+ await onUsersChanged();
+ }
+ });
+ }
+ }
+ });
+ }
+
+ function getRoleBadgeVariant(roles: string[]) {
+ if (roles?.includes('admin')) return 'red';
+ if (roles?.includes('moderator')) return 'amber';
+ return 'green';
+ }
+
+ function getRoleText(roles: string[]) {
+ if (roles?.includes('admin')) return 'Admin';
+ if (roles?.includes('moderator')) return 'Moderator';
+ return 'User';
+ }
+</script>
+
+{#if usersWithId.length > 0}
+ <Card.Root class="border shadow-sm">
+ <Card.Header class="px-6">
+ <div class="flex items-center justify-between">
+ <Card.Title>Users List</Card.Title>
+ <div class="flex items-center gap-2">
+ {#if selectedIds.length > 0}
+ <ArcaneButton
+ action="remove"
+ onClick={handleDeleteSelected}
+ loading={isLoading.removing}
+ disabled={isLoading.removing}
+ />
+ {/if}
+ </div>
+ </div>
+ </Card.Header>
+ <Card.Content>
+ <ArcaneTable
+ items={paginatedUsers}
+ bind:requestOptions
+ bind:selectedIds
+ {onRefresh}
+ columns={[
+ { label: 'Username', sortColumn: 'Username' },
+ { label: 'Display Name', sortColumn: 'DisplayName' },
+ { label: 'Email', sortColumn: 'Email' },
+ { label: 'Role', sortColumn: 'Roles' },
+ { label: 'Created', sortColumn: 'CreatedAt' },
+ { label: ' ' }
+ ]}
+ filterPlaceholder="Search users..."
+ noResultsMessage="No users found"
+ >
+ {#snippet rows({ item })}
+ <Table.Cell>
+ <span class="font-medium">{item.Username}</span>
+ </Table.Cell>
+ <Table.Cell>{item.DisplayName || '-'}</Table.Cell>
+ <Table.Cell>{item.Email || '-'}</Table.Cell>
+ <Table.Cell>
+ <StatusBadge text={getRoleText(item.Roles)} variant={getRoleBadgeVariant(item.Roles)} />
+ </Table.Cell>
+ <Table.Cell>{formatFriendlyDate(item.CreatedAt)}</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={() => onEditUser(item)}>
+ <Edit class="size-4" />
+ Edit
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ class="focus:text-red-700! text-red-500"
+ onclick={() => handleDeleteUser(item.ID, item.Username)}
+ >
+ <Trash2 class="size-4" />
+ Delete
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </ArcaneTable>
+ </Card.Content>
+ </Card.Root>
+{:else}
+ <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
+ <Users class="text-muted-foreground mb-4 size-12 opacity-40" />
+ <p class="text-lg font-medium">No users found</p>
+ <p class="text-muted-foreground mt-1 max-w-md text-sm">
+ Create a new user using the "Create User" button above
+ </p>
+ </div>
+{/if}
diff --git a/frontend/src/routes/volumes/+page.svelte b/frontend/src/routes/volumes/+page.svelte
index 0e77b678c..2d16a7a24 100644
--- a/frontend/src/routes/volumes/+page.svelte
+++ b/frontend/src/routes/volumes/+page.svelte
@@ -1,76 +1,56 @@
<script lang="ts">
- import {
- Trash2,
- HardDrive,
- Ellipsis,
- ScanSearch,
- Loader2,
- ChevronDown,
- ArchiveRestore,
- ArchiveX
- } from '@lucide/svelte';
- import { Button } from '$lib/components/ui/button/index.js';
+ import { HardDrive, Loader2, ArchiveRestore, ArchiveX } from '@lucide/svelte';
import * as Card from '$lib/components/ui/card/index.js';
import * as Alert from '$lib/components/ui/alert/index.js';
- import * as Table from '$lib/components/ui/table';
- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
import { toast } from 'svelte-sonner';
- import { goto } from '$app/navigation';
- import { openConfirmDialog } from '$lib/components/confirm-dialog';
- import UniversalTable from '$lib/components/universal-table.svelte';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
- import { formatFriendlyDate } from '$lib/utils/date.utils';
import CreateVolumeSheet from '$lib/components/sheets/create-volume-sheet.svelte';
- import StatusBadge from '$lib/components/badges/status-badge.svelte';
import type { VolumeCreateOptions, VolumeInspectInfo } from 'dockerode';
import ArcaneButton from '$lib/components/arcane-button.svelte';
- import { tablePersistence } from '$lib/stores/table-store';
import { environmentAPI } from '$lib/services/api';
- import { onMount } from 'svelte';
import StatCard from '$lib/components/stat-card.svelte';
-
- let volumes = $state<EnhancedVolumeInfo[]>([]);
- let error = $state<string | null>(null);
- let selectedIds = $state<string[]>([]);
- let isLoadingVolumes = $state(true);
-
- let volumeFilters = $state({
- showUsed: true,
- showUnused: true
- });
+ import VolumeTable from './volume-table.svelte';
+ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
type EnhancedVolumeInfo = VolumeInspectInfo & {
- inUse: boolean;
+ InUse: boolean;
CreatedAt: string;
+ id: string;
};
- const filteredVolumes = $derived(
- volumes.filter(
- (vol) => (volumeFilters.showUsed && vol.inUse) || (volumeFilters.showUnused && !vol.inUse)
- )
+ let { data } = $props();
+
+ let volumes = $state<EnhancedVolumeInfo[]>(
+ Array.isArray(data.volumes) ? data.volumes : data.volumes.data || []
);
+ let error = $state<string | null>(null);
+ let selectedIds = $state<string[]>([]);
+ let requestOptions = $state<SearchPaginationSortRequest>(data.volumeRequestOptions);
let isDialogOpen = $state({
- create: false,
- remove: false
+ create: false
});
let isLoading = $state({
- remove: false,
creating: false,
refresh: false
});
const totalVolumes = $derived(volumes.length);
- const usedVolumes = $derived(volumes.filter((v) => v.inUse).length);
- const unusedVolumes = $derived(volumes.filter((v) => !v.inUse).length);
+ const usedVolumes = $derived(volumes.filter((v) => v.InUse).length);
+ const unusedVolumes = $derived(volumes.filter((v) => !v.InUse).length);
async function loadVolumes() {
try {
isLoading.refresh = true;
- const response = await environmentAPI.getVolumes();
- volumes = response || [];
+ const response = await environmentAPI.getVolumes(
+ requestOptions.pagination,
+ requestOptions.sort,
+ requestOptions.search,
+ requestOptions.filters
+ );
+ volumes = Array.isArray(response) ? response : response.data || [];
error = null;
} catch (err) {
console.error('Failed to load volumes:', err);
@@ -78,13 +58,22 @@
volumes = [];
} finally {
isLoading.refresh = false;
- isLoadingVolumes = false;
}
}
- onMount(() => {
- loadVolumes();
- });
+ async function onRefresh(options: SearchPaginationSortRequest) {
+ requestOptions = options;
+ await loadVolumes();
+ return {
+ data: volumes,
+ pagination: {
+ totalPages: Math.ceil(volumes.length / (requestOptions.pagination?.limit || 20)),
+ totalItems: volumes.length,
+ currentPage: requestOptions.pagination?.page || 1,
+ itemsPerPage: requestOptions.pagination?.limit || 20
+ }
+ };
+ }
async function handleCreateVolumeSubmit(options: VolumeCreateOptions) {
isLoading.creating = true;
@@ -100,83 +89,36 @@
});
}
- async function handleRemoveVolumeConfirm(name: string) {
- openConfirmDialog({
- title: `Remove Volume "${name}"`,
- message: `Are you sure you want to remove the volume "${name}"? This action cannot be undone and will permanently delete all data stored in this volume.`,
- confirm: {
- label: 'Remove',
- destructive: true,
- action: async () => {
- isLoading.remove = true;
- handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.deleteVolume(name)),
- message: `Failed to Remove Volume "${name}"`,
- setLoadingState: (value) => (isLoading.remove = value),
- onSuccess: async () => {
- toast.success(`Volume "${name}" Removed Successfully.`);
- await loadVolumes();
- }
- });
- }
- }
- });
- }
-
- async function handleDeleteSelected() {
- if (selectedIds.length === 0) return;
-
- openConfirmDialog({
- title: `Remove ${selectedIds.length} Volume${selectedIds.length > 1 ? 's' : ''}`,
- message: `Are you sure you want to remove the selected volume${selectedIds.length > 1 ? 's' : ''}? This action cannot be undone and will permanently delete all data.`,
- confirm: {
- label: 'Remove',
- destructive: true,
- action: async () => {
- isLoading.remove = true;
- let successCount = 0;
- let failureCount = 0;
-
- for (const volumeName of selectedIds) {
- const result = await tryCatch(environmentAPI.deleteVolume(volumeName));
- handleApiResultWithCallbacks({
- result,
- message: `Failed to remove volume ${volumeName}`,
- setLoadingState: () => {},
- onSuccess: () => {
- toast.success(`Volume "${volumeName}" deleted successfully.`);
- successCount++;
- }
- });
-
- if (result.error) {
- failureCount++;
- }
- }
- isLoading.remove = false;
-
- if (successCount > 0) {
- setTimeout(async () => {
- await loadVolumes();
- }, 500);
- }
- selectedIds = [];
- }
- }
- });
+ async function refreshVolumes() {
+ isLoading.refresh = true;
+ try {
+ await loadVolumes();
+ } catch (error) {
+ console.error('Failed to refresh volumes:', error);
+ toast.error('Failed to refresh volumes');
+ } finally {
+ isLoading.refresh = false;
+ }
}
</script>
-<div class="space-y-6">
+<div class="space-y-6 pb-8">
<div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
<div>
<h1 class="text-3xl font-bold tracking-tight">Volumes</h1>
<p class="text-muted-foreground mt-1 text-sm">Manage your Docker volumes</p>
</div>
<div class="flex items-center gap-2">
+ <ArcaneButton
+ action="create"
+ label="Create Volume"
+ onClick={() => (isDialogOpen.create = true)}
+ loading={isLoading.creating}
+ disabled={isLoading.creating}
+ />
<ArcaneButton
action="restart"
- onClick={loadVolumes}
+ onClick={refreshVolumes}
label="Refresh"
loading={isLoading.refresh}
disabled={isLoading.refresh}
@@ -191,205 +133,37 @@
</Alert.Root>
{/if}
- {#if isLoadingVolumes}
- <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
- {#each Array(2) as _}
- <Card.Root>
- <Card.Content class="flex items-center justify-between p-4">
- <div class="space-y-2">
- <div class="bg-muted h-4 w-24 animate-pulse rounded"></div>
- <div class="bg-muted h-8 w-12 animate-pulse rounded"></div>
- </div>
- <div class="bg-muted size-10 animate-pulse rounded-full"></div>
- </Card.Content>
- </Card.Root>
- {/each}
- </div>
-
- <Card.Root class="border shadow-sm">
- <Card.Header class="px-6">
- <div class="flex items-center justify-between">
- <div>
- <Card.Title>Volumes List</Card.Title>
- </div>
- <div class="flex items-center gap-2">
- <div class="bg-muted h-9 w-32 animate-pulse rounded"></div>
- <div class="bg-muted h-9 w-28 animate-pulse rounded"></div>
- </div>
- </div>
- </Card.Header>
- <Card.Content>
- <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
- <Loader2 class="text-muted-foreground mb-4 size-8 animate-spin" />
- <p class="text-lg font-medium">Loading Volumes...</p>
- <p class="text-muted-foreground mt-1 text-sm">Please wait while we fetch your volumes</p>
- </div>
- </Card.Content>
- </Card.Root>
- {:else}
- <div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
- <StatCard
- title="Total Volumes"
- value={totalVolumes}
- icon={HardDrive}
- iconColor="text-blue-500"
- class="border-l-4 border-l-blue-500"
- />
- <StatCard
- title="Used Volumes"
- value={usedVolumes}
- icon={ArchiveRestore}
- iconColor="text-green-500"
- class="border-l-4 border-l-green-500"
- />
- <StatCard
- title="Unused Volumes"
- value={unusedVolumes}
- icon={ArchiveX}
- iconColor="text-red-500"
- class="border-l-4 border-l-red-500"
- />
- </div>
- {/if}
+ <div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
+ <StatCard
+ title="Total Volumes"
+ value={totalVolumes}
+ icon={HardDrive}
+ iconColor="text-blue-500"
+ class="border-l-4 border-l-blue-500"
+ />
+ <StatCard
+ title="Used Volumes"
+ value={usedVolumes}
+ icon={ArchiveRestore}
+ iconColor="text-green-500"
+ class="border-l-4 border-l-green-500"
+ />
+ <StatCard
+ title="Unused Volumes"
+ value={unusedVolumes}
+ icon={ArchiveX}
+ iconColor="text-red-500"
+ class="border-l-4 border-l-red-500"
+ />
+ </div>
- {#if filteredVolumes.length > 0}
- <Card.Root class="border shadow-sm">
- <Card.Header class="px-6">
- <div class="flex items-center justify-between">
- <div>
- <Card.Title>Volumes List</Card.Title>
- </div>
- <div class="flex items-center gap-2">
- <DropdownMenu.Root>
- <DropdownMenu.Trigger>
- {#snippet child({ props })}
- <Button {...props} variant="outline" size="sm">
- Filter <ChevronDown class="ml-2 size-4" />
- </Button>
- {/snippet}
- </DropdownMenu.Trigger>
- <DropdownMenu.Content>
- <DropdownMenu.Label>Volume Usage</DropdownMenu.Label>
- <DropdownMenu.CheckboxItem
- checked={volumeFilters.showUsed}
- onCheckedChange={(checked) => {
- volumeFilters.showUsed = checked;
- }}
- >
- Show Used Volumes
- </DropdownMenu.CheckboxItem>
- <DropdownMenu.CheckboxItem
- checked={volumeFilters.showUnused}
- onCheckedChange={(checked) => {
- volumeFilters.showUnused = checked;
- }}
- >
- Show Unused Volumes
- </DropdownMenu.CheckboxItem>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- {#if selectedIds.length > 0}
- <ArcaneButton
- action="remove"
- onClick={handleDeleteSelected}
- loading={isLoading.remove}
- disabled={isLoading.remove}
- />
- {/if}
- <ArcaneButton
- action="create"
- label="Create Volume"
- onClick={() => (isDialogOpen.create = true)}
- loading={isLoading.creating}
- disabled={isLoading.creating}
- />
- </div>
- </div>
- </Card.Header>
- <Card.Content>
- <UniversalTable
- data={filteredVolumes}
- columns={[
- { accessorKey: 'Name', header: 'Name' },
- { accessorKey: 'inUse', header: 'Status' },
- { accessorKey: 'Driver', header: 'Driver' },
- { accessorKey: 'CreatedAt', header: 'Created' },
- { accessorKey: 'actions', header: ' ', enableSorting: false }
- ]}
- pagination={{
- pageSize: tablePersistence.getPageSize('volumes')
- }}
- onPageSizeChange={(newSize) => {
- tablePersistence.setPageSize('volumes', newSize);
- }}
- sort={{
- defaultSort: { id: 'Name', desc: false }
- }}
- bind:selectedIds
- >
- {#snippet rows({ item })}
- <Table.Cell>
- <a class="font-medium hover:underline" href="/volumes/{item.Name}/">{item.Name}</a>
- </Table.Cell>
- <Table.Cell>
- {#if item.inUse}
- <StatusBadge text="In Use" variant="green" />
- {:else}
- <StatusBadge text="Unused" variant="amber" />
- {/if}
- </Table.Cell>
- <Table.Cell>{item.Driver}</Table.Cell>
- <Table.Cell>{formatFriendlyDate(item.CreatedAt)}</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/${item.Name}`)}>
- <ScanSearch class="size-4" />
- Inspect
- </DropdownMenu.Item>
- <DropdownMenu.Item
- class="focus:text-red-700! text-red-500"
- onclick={() => handleRemoveVolumeConfirm(item.Name)}
- >
- <Trash2 class="size-4" />
- Remove
- </DropdownMenu.Item>
- </DropdownMenu.Group>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- </Table.Cell>
- {/snippet}
- </UniversalTable>
- </Card.Content>
- </Card.Root>
- {:else if !error}
- <div
- class="bg-card flex flex-col items-center justify-center rounded-lg border px-6 py-12 text-center"
- >
- <HardDrive class="text-muted-foreground mb-4 size-12 opacity-40" />
- <p class="text-lg font-medium">No volumes found</p>
- <p class="text-muted-foreground mt-1 max-w-md text-sm">
- Create a new volume using the "Create Volume" button above
- </p>
- <div class="mt-4 flex gap-3">
- <ArcaneButton
- action="create"
- label="Create Volume"
- onClick={() => (isDialogOpen.create = true)}
- size="sm"
- />
- </div>
- </div>
- {/if}
+ <VolumeTable
+ {volumes}
+ bind:selectedIds
+ bind:requestOptions
+ {onRefresh}
+ onVolumesChanged={loadVolumes}
+ />
<CreateVolumeSheet
bind:open={isDialogOpen.create}
diff --git a/frontend/src/routes/volumes/+page.ts b/frontend/src/routes/volumes/+page.ts
new file mode 100644
index 000000000..d73e0b67a
--- /dev/null
+++ b/frontend/src/routes/volumes/+page.ts
@@ -0,0 +1,25 @@
+import { environmentAPI } from '$lib/services/api';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async () => {
+ const volumeRequestOptions: SearchPaginationSortRequest = {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'Name',
+ direction: 'asc' as const
+ }
+ };
+
+ const volumes = await environmentAPI.getVolumes(
+ volumeRequestOptions.pagination,
+ volumeRequestOptions.sort,
+ volumeRequestOptions.search,
+ volumeRequestOptions.filters
+ );
+
+ return { volumes, volumeRequestOptions };
+};
\ No newline at end of file
diff --git a/frontend/src/routes/volumes/[volumeName]/+page.ts b/frontend/src/routes/volumes/[volumeName]/+page.ts
index 38f3416c3..fb8bf19c4 100644
--- a/frontend/src/routes/volumes/[volumeName]/+page.ts
+++ b/frontend/src/routes/volumes/[volumeName]/+page.ts
@@ -14,7 +14,7 @@ export const load: PageLoad = async ({ params }) => {
const inUseResponse = await environmentAPI.getVolumeUsage(volumeName);
return {
- volume,
+ volume: volume.data,
inUse: inUseResponse.data ? inUseResponse.data.inUse : false
};
} catch (err: any) {
diff --git a/frontend/src/routes/volumes/volume-table.svelte b/frontend/src/routes/volumes/volume-table.svelte
new file mode 100644
index 000000000..d41933ea2
--- /dev/null
+++ b/frontend/src/routes/volumes/volume-table.svelte
@@ -0,0 +1,262 @@
+<script lang="ts">
+ import type { VolumeInspectInfo } from 'dockerode';
+ import ArcaneTable from '$lib/components/arcane-table.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { Trash2, HardDrive, Ellipsis, ScanSearch, ChevronDown, Funnel } from '@lucide/svelte';
+ import * as Card from '$lib/components/ui/card/index.js';
+ import { goto } from '$app/navigation';
+ import { toast } from 'svelte-sonner';
+ 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 StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import ArcaneButton from '$lib/components/arcane-button.svelte';
+ import { formatFriendlyDate } from '$lib/utils/date.utils';
+ import { environmentAPI } from '$lib/services/api';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+
+ type EnhancedVolumeInfo = VolumeInspectInfo & {
+ InUse: boolean;
+ CreatedAt: string;
+ id: string;
+ };
+
+ let {
+ volumes,
+ selectedIds = $bindable(),
+ requestOptions = $bindable(),
+ onRefresh,
+ onVolumesChanged
+ }: {
+ volumes: EnhancedVolumeInfo[];
+ selectedIds: string[];
+ requestOptions: SearchPaginationSortRequest;
+ onRefresh: (options: SearchPaginationSortRequest) => Promise<any>;
+ onVolumesChanged: () => Promise<void>;
+ } = $props();
+
+ let volumeFilters = $state({
+ showUsed: true,
+ showUnused: true
+ });
+
+ let isLoading = $state({
+ removing: false
+ });
+
+ const volumesWithId = $derived(
+ volumes.map((vol) => ({
+ ...vol,
+ id: vol.Name
+ }))
+ );
+
+ const filteredVolumes = $derived(
+ volumesWithId.filter((vol) => {
+ const showBecauseUsed = volumeFilters.showUsed && vol.InUse;
+ const showBecauseUnused = volumeFilters.showUnused && !vol.InUse;
+ return showBecauseUsed || showBecauseUnused;
+ })
+ );
+
+ const paginatedVolumes: Paginated<EnhancedVolumeInfo> = $derived({
+ data: filteredVolumes,
+ pagination: {
+ totalPages: Math.ceil(filteredVolumes.length / (requestOptions.pagination?.limit || 20)),
+ totalItems: filteredVolumes.length,
+ currentPage: requestOptions.pagination?.page || 1,
+ itemsPerPage: requestOptions.pagination?.limit || 20
+ }
+ });
+
+ async function handleDeleteSelected() {
+ if (selectedIds.length === 0) return;
+
+ openConfirmDialog({
+ title: `Remove ${selectedIds.length} Volume${selectedIds.length > 1 ? 's' : ''}`,
+ message: `Are you sure you want to remove the selected volume${selectedIds.length > 1 ? 's' : ''}? This action cannot be undone and will permanently delete all data.`,
+ confirm: {
+ label: 'Remove',
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+ let successCount = 0;
+ let failureCount = 0;
+
+ for (const volumeName of selectedIds) {
+ const result = await tryCatch(environmentAPI.deleteVolume(volumeName));
+ handleApiResultWithCallbacks({
+ result,
+ message: `Failed to remove volume ${volumeName}`,
+ setLoadingState: () => {},
+ onSuccess: () => {
+ successCount++;
+ }
+ });
+
+ if (result.error) {
+ failureCount++;
+ }
+ }
+
+ isLoading.removing = false;
+
+ if (successCount > 0) {
+ toast.success(
+ `Successfully removed ${successCount} volume${successCount > 1 ? 's' : ''}`
+ );
+ await onVolumesChanged();
+ }
+
+ if (failureCount > 0) {
+ toast.error(`Failed to remove ${failureCount} volume${failureCount > 1 ? 's' : ''}`);
+ }
+
+ selectedIds = [];
+ }
+ }
+ });
+ }
+
+ async function handleRemoveVolumeConfirm(name: string) {
+ openConfirmDialog({
+ title: `Remove Volume "${name}"`,
+ message: `Are you sure you want to remove the volume "${name}"? This action cannot be undone and will permanently delete all data stored in this volume.`,
+ confirm: {
+ label: 'Remove',
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.deleteVolume(name)),
+ message: `Failed to Remove Volume "${name}"`,
+ setLoadingState: (value) => (isLoading.removing = value),
+ onSuccess: async () => {
+ toast.success(`Volume "${name}" Removed Successfully.`);
+ await onVolumesChanged();
+ }
+ });
+ }
+ }
+ });
+ }
+</script>
+
+{#if filteredVolumes.length > 0}
+ <Card.Root class="border shadow-sm">
+ <Card.Header class="px-6">
+ <div class="flex items-center justify-between">
+ <Card.Title>Volumes List</Card.Title>
+ <div class="flex items-center gap-2">
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button {...props} variant="outline" size="sm">
+ <Funnel class="mr-2 size-4" />
+ Filter
+ <ChevronDown class="ml-2 size-4" />
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content>
+ <DropdownMenu.Label>Volume Usage</DropdownMenu.Label>
+ <DropdownMenu.CheckboxItem
+ checked={volumeFilters.showUsed}
+ onCheckedChange={(checked) => {
+ volumeFilters.showUsed = checked;
+ }}
+ >
+ Show Used Volumes
+ </DropdownMenu.CheckboxItem>
+ <DropdownMenu.CheckboxItem
+ checked={volumeFilters.showUnused}
+ onCheckedChange={(checked) => {
+ volumeFilters.showUnused = checked;
+ }}
+ >
+ Show Unused Volumes
+ </DropdownMenu.CheckboxItem>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ {#if selectedIds.length > 0}
+ <ArcaneButton
+ action="remove"
+ onClick={handleDeleteSelected}
+ loading={isLoading.removing}
+ disabled={isLoading.removing}
+ />
+ {/if}
+ </div>
+ </div>
+ </Card.Header>
+ <Card.Content>
+ <ArcaneTable
+ items={paginatedVolumes}
+ bind:requestOptions
+ bind:selectedIds
+ {onRefresh}
+ columns={[
+ { label: 'Name', sortColumn: 'Name' },
+ { label: 'Status', sortColumn: 'InUse' },
+ { label: 'Driver', sortColumn: 'Driver' },
+ { label: 'Created', sortColumn: 'CreatedAt' },
+ { label: ' ' }
+ ]}
+ filterPlaceholder="Search volumes..."
+ noResultsMessage="No volumes found"
+ >
+ {#snippet rows({ item })}
+ <Table.Cell>
+ <a class="font-medium hover:underline" href="/volumes/{item.Name}/">{item.Name}</a>
+ </Table.Cell>
+ <Table.Cell>
+ {#if item.InUse}
+ <StatusBadge text="In Use" variant="green" />
+ {:else}
+ <StatusBadge text="Unused" variant="amber" />
+ {/if}
+ </Table.Cell>
+ <Table.Cell>{item.Driver}</Table.Cell>
+ <Table.Cell>{formatFriendlyDate(item.CreatedAt)}</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/${item.Name}`)}>
+ <ScanSearch class="size-4" />
+ Inspect
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ class="focus:text-red-700! text-red-500"
+ onclick={() => handleRemoveVolumeConfirm(item.Name)}
+ >
+ <Trash2 class="size-4" />
+ Remove
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </ArcaneTable>
+ </Card.Content>
+ </Card.Root>
+{:else}
+ <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
+ <HardDrive class="text-muted-foreground mb-4 size-12 opacity-40" />
+ <p class="text-lg font-medium">No volumes found</p>
+ <p class="text-muted-foreground mt-1 max-w-md text-sm">
+ Create a new volume using the "Create Volume" button above
+ </p>
+ </div>
+{/if}