Skip to content

Modern Docker Management, Designed for Everyone

fix: pagination round one fixes (containers, images, and projects)

Kyle Mendell8349d1b84a85
diff --git a/backend/internal/dto/container_dto.go b/backend/internal/dto/container_dto.go
index 1dca90d36..a507d675a 100644
--- a/backend/internal/dto/container_dto.go
+++ b/backend/internal/dto/container_dto.go
@@ -1,5 +1,10 @@
package dto
+import (
+ "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/api/types/network"
+)
+
type CreateContainerDto struct {
Name string `json:"name" binding:"required"`
Image string `json:"image" binding:"required"`
@@ -25,3 +30,149 @@ type ContainerActionResult struct {
Success bool `json:"success"`
Errors []string `json:"errors,omitempty"`
}
+
+type PortDto struct {
+ IP string `json:"ip,omitempty"`
+ PrivatePort int `json:"privatePort"`
+ PublicPort int `json:"publicPort,omitempty"`
+ Type string `json:"type"`
+}
+
+type MountDto struct {
+ Type string `json:"type"`
+ Name string `json:"name,omitempty"`
+ Source string `json:"source,omitempty"`
+ Destination string `json:"destination"`
+ Driver string `json:"driver,omitempty"`
+ Mode string `json:"mode,omitempty"`
+ RW bool `json:"rw,omitempty"`
+ Propagation string `json:"propagation,omitempty"`
+}
+
+type NetworkDto struct {
+ IPAMConfig any `json:"ipamConfig"`
+ Links []string `json:"links"`
+ Aliases []string `json:"aliases"`
+ MacAddress string `json:"macAddress"`
+ DriverOpts map[string]string `json:"driverOpts"`
+ GwPriority int `json:"gwPriority"`
+ NetworkID string `json:"networkId"`
+ EndpointID string `json:"endpointId"`
+ Gateway string `json:"gateway"`
+ IPAddress string `json:"ipAddress"`
+ IPPrefixLen int `json:"ipPrefixLen"`
+ IPv6Gateway string `json:"ipv6Gateway"`
+ GlobalIPv6Address string `json:"globalIPv6Address"`
+ GlobalIPv6PrefixLen int `json:"globalIPv6PrefixLen"`
+ DNSNames []string `json:"dnsNames"`
+}
+
+type HostConfigDto struct {
+ NetworkMode string `json:"networkMode"`
+}
+
+type NetworkSettingsDto struct {
+ Networks map[string]NetworkDto `json:"networks"`
+}
+
+type ContainerSummaryDto struct {
+ ID string `json:"id"`
+ Names []string `json:"names"`
+ Image string `json:"image"`
+ ImageID string `json:"imageId"`
+ Command string `json:"command"`
+ Created int64 `json:"created"`
+ Ports []PortDto `json:"ports"`
+ Labels map[string]string `json:"labels"`
+ State string `json:"state"`
+ Status string `json:"status"`
+ HostConfig HostConfigDto `json:"hostConfig"`
+ NetworkSettings NetworkSettingsDto `json:"networkSettings"`
+ Mounts []MountDto `json:"mounts"`
+}
+
+// Mapper from Docker's container.Summary to DTO
+func NewContainerSummaryDto(c container.Summary) ContainerSummaryDto {
+ // Ports
+ ports := make([]PortDto, 0, len(c.Ports))
+ for _, p := range c.Ports {
+ ports = append(ports, PortDto{
+ IP: p.IP,
+ PrivatePort: int(p.PrivatePort),
+ PublicPort: int(p.PublicPort),
+ Type: p.Type,
+ })
+ }
+
+ // Mounts
+ mounts := make([]MountDto, 0, len(c.Mounts))
+ for _, m := range c.Mounts {
+ mounts = append(mounts, MountDto{
+ Type: string(m.Type),
+ Name: m.Name,
+ Source: m.Source,
+ Destination: m.Destination,
+ Driver: m.Driver,
+ Mode: m.Mode,
+ RW: m.RW,
+ Propagation: string(m.Propagation),
+ })
+ }
+
+ // Networks
+ networks := map[string]NetworkDto{}
+ if c.NetworkSettings != nil && c.NetworkSettings.Networks != nil {
+ for name, n := range c.NetworkSettings.Networks {
+ networks[name] = mapEndpointSettings(n)
+ }
+ }
+
+ return ContainerSummaryDto{
+ ID: c.ID,
+ Names: c.Names,
+ Image: c.Image,
+ ImageID: c.ImageID,
+ Command: c.Command,
+ Created: c.Created,
+ Ports: ports,
+ Labels: c.Labels,
+ State: c.State,
+ Status: c.Status,
+ HostConfig: HostConfigDto{
+ NetworkMode: c.HostConfig.NetworkMode,
+ },
+ NetworkSettings: NetworkSettingsDto{
+ Networks: networks,
+ },
+ Mounts: mounts,
+ }
+}
+
+func mapEndpointSettings(n *network.EndpointSettings) NetworkDto {
+ if n == nil {
+ return NetworkDto{}
+ }
+ // DriverOpts can be nil in Docker types; ensure non-nil map for JSON stability if needed
+ var driverOpts map[string]string
+ if n.DriverOpts != nil {
+ driverOpts = n.DriverOpts
+ }
+
+ return NetworkDto{
+ IPAMConfig: n.IPAMConfig,
+ Links: n.Links,
+ Aliases: n.Aliases,
+ MacAddress: n.MacAddress,
+ DriverOpts: driverOpts,
+ GwPriority: n.GwPriority,
+ NetworkID: n.NetworkID,
+ EndpointID: n.EndpointID,
+ Gateway: n.Gateway,
+ IPAddress: n.IPAddress,
+ IPPrefixLen: n.IPPrefixLen,
+ IPv6Gateway: n.IPv6Gateway,
+ GlobalIPv6Address: n.GlobalIPv6Address,
+ GlobalIPv6PrefixLen: n.GlobalIPv6PrefixLen,
+ DNSNames: n.DNSNames,
+ }
+}
diff --git a/backend/internal/dto/image_dto.go b/backend/internal/dto/image_dto.go
index 05d47a7c1..734772fcc 100644
--- a/backend/internal/dto/image_dto.go
+++ b/backend/internal/dto/image_dto.go
@@ -1,5 +1,80 @@
package dto
+import (
+ "time"
+
+ "github.com/ofkm/arcane-backend/internal/models"
+)
+
type ImagePullDto struct {
ImageName string `json:"imageName" binding:"required"`
}
+
+type ImageUpdateInfoDto struct {
+ HasUpdate bool `json:"hasUpdate"`
+ UpdateType string `json:"updateType"`
+ CurrentVersion string `json:"currentVersion"`
+ LatestVersion string `json:"latestVersion"`
+ CurrentDigest string `json:"currentDigest"`
+ LatestDigest string `json:"latestDigest"`
+ CheckTime time.Time `json:"checkTime"`
+ ResponseTimeMs int `json:"responseTimeMs"`
+ Error string `json:"error"`
+}
+
+type ImageSummaryDto struct {
+ ID string `json:"id" sortable:"true"`
+ RepoTags []string `json:"repoTags"`
+ RepoDigests []string `json:"repoDigests"`
+ Created int64 `json:"created" sortable:"true"`
+ Size int64 `json:"size" sortable:"true"`
+ VirtualSize int64 `json:"virtualSize"`
+ Labels map[string]interface{} `json:"labels"`
+ InUse bool `json:"inUse" sortable:"true"`
+ Repo string `json:"repo" sortable:"true"`
+ Tag string `json:"tag" sortable:"true"`
+ UpdateInfo *ImageUpdateInfoDto `json:"updateInfo,omitempty"`
+}
+
+func NewImageSummaryDto(m *models.Image) ImageSummaryDto {
+ var labels map[string]interface{}
+ if m.Labels != nil {
+ labels = map[string]interface{}(m.Labels)
+ }
+
+ var update *ImageUpdateInfoDto
+ if m.UpdateRecord != nil {
+ sp := func(p *string) string {
+ if p == nil {
+ return ""
+ }
+ return *p
+ }
+
+ update = &ImageUpdateInfoDto{
+ HasUpdate: m.UpdateRecord.HasUpdate,
+ UpdateType: m.UpdateRecord.UpdateType,
+ CurrentVersion: m.UpdateRecord.CurrentVersion,
+ LatestVersion: sp(m.UpdateRecord.LatestVersion),
+ CurrentDigest: sp(m.UpdateRecord.CurrentDigest),
+ LatestDigest: sp(m.UpdateRecord.LatestDigest),
+ CheckTime: m.UpdateRecord.CheckTime,
+ ResponseTimeMs: m.UpdateRecord.ResponseTimeMs,
+ Error: sp(m.UpdateRecord.LastError),
+ }
+ }
+
+ return ImageSummaryDto{
+ ID: m.ID,
+ RepoTags: []string(m.RepoTags),
+ RepoDigests: []string(m.RepoDigests),
+ Created: m.Created.Unix(),
+ Size: m.Size,
+ VirtualSize: m.VirtualSize,
+ Labels: labels,
+ InUse: m.InUse,
+ Repo: m.Repo,
+ Tag: m.Tag,
+ UpdateInfo: update,
+ }
+}
diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.go
index 884d9485a..17b8f7531 100644
--- a/backend/internal/services/container_service.go
+++ b/backend/internal/services/container_service.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
+ "sort"
"strings"
"github.com/docker/docker/api/types/container"
@@ -14,6 +15,7 @@ import (
"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/dto"
"github.com/ofkm/arcane-backend/internal/models"
"github.com/ofkm/arcane-backend/internal/utils"
)
@@ -447,60 +449,38 @@ func (s *ContainerService) readAllLogs(logs io.ReadCloser, logsChan chan<- strin
}
//nolint:gocognit
-func (s *ContainerService) ListContainersPaginated(ctx context.Context, req utils.SortedPaginationRequest, includeAll bool) ([]map[string]interface{}, utils.PaginationResponse, error) {
+func (s *ContainerService) ListContainersPaginated(ctx context.Context, req utils.SortedPaginationRequest, includeAll bool) ([]dto.ContainerSummaryDto, 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)
+ // Map to DTOs
+ result := make([]dto.ContainerSummaryDto, 0, len(dockerContainers))
+ for _, dc := range dockerContainers {
+ result = append(result, dto.NewContainerSummaryDto(dc))
}
+ // Search filter
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
- }
+ filtered := make([]dto.ContainerSummaryDto, 0, len(result))
+ for _, c := range result {
+ matched := false
+ for _, name := range c.Names {
+ if strings.Contains(strings.ToLower(name), searchLower) {
+ matched = true
+ break
}
}
- if image, ok := container["Image"].(string); ok {
- if strings.Contains(strings.ToLower(image), searchLower) {
- filtered = append(filtered, container)
- continue
- }
+ if !matched && strings.Contains(strings.ToLower(c.Image), searchLower) {
+ matched = true
}
- if state, ok := container["State"].(string); ok {
- if strings.Contains(strings.ToLower(state), searchLower) {
- filtered = append(filtered, container)
- continue
- }
+ if !matched && strings.Contains(strings.ToLower(c.State), searchLower) {
+ matched = true
+ }
+ if matched {
+ filtered = append(filtered, c)
}
}
result = filtered
@@ -508,24 +488,23 @@ func (s *ContainerService) ListContainersPaginated(ctx context.Context, req util
totalItems := len(result)
+ // Sort
if req.Sort.Column != "" {
- utils.SortSliceByField(result, req.Sort.Column, req.Sort.Direction)
+ sortContainers(result, req.Sort.Column, req.Sort.Direction)
}
+ // Pagination window
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)
}
-
+ pageItems := []dto.ContainerSummaryDto{}
if startIdx < endIdx {
- result = result[startIdx:endIdx]
- } else {
- result = []map[string]interface{}{}
+ pageItems = result[startIdx:endIdx]
}
totalPages := (totalItems + req.Pagination.Limit - 1) / req.Pagination.Limit
@@ -536,5 +515,50 @@ func (s *ContainerService) ListContainersPaginated(ctx context.Context, req util
ItemsPerPage: req.Pagination.Limit,
}
- return result, pagination, nil
+ return pageItems, pagination, nil
+}
+
+func sortContainers(items []dto.ContainerSummaryDto, field, direction string) {
+ dir := utils.NormalizeSortDirection(direction)
+ f := strings.ToLower(strings.TrimSpace(field))
+
+ desc := dir == "desc"
+ lessStr := func(a, b string) bool {
+ if desc {
+ return a > b
+ }
+ return a < b
+ }
+ lessInt := func(a, b int64) bool {
+ if desc {
+ return a > b
+ }
+ return a < b
+ }
+
+ sort.Slice(items, func(i, j int) bool {
+ a, b := items[i], items[j]
+ switch f {
+ case "name", "names":
+ var n1, n2 string
+ if len(a.Names) > 0 {
+ n1 = a.Names[0]
+ }
+ if len(b.Names) > 0 {
+ n2 = b.Names[0]
+ }
+ return lessStr(n1, n2)
+ case "image":
+ return lessStr(a.Image, b.Image)
+ case "state":
+ return lessStr(a.State, b.State)
+ case "status":
+ return lessStr(a.Status, b.Status)
+ case "created":
+ return lessInt(a.Created, b.Created)
+ default:
+ // no-op sort keeps original order
+ return false
+ }
+ })
}
diff --git a/backend/internal/services/image_service.go b/backend/internal/services/image_service.go
index 9c0a78f37..002fc64aa 100644
--- a/backend/internal/services/image_service.go
+++ b/backend/internal/services/image_service.go
@@ -18,6 +18,7 @@ import (
"github.com/docker/docker/api/types/registry"
"github.com/docker/docker/client"
"github.com/ofkm/arcane-backend/internal/database"
+ "github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/models"
"github.com/ofkm/arcane-backend/internal/utils"
"gorm.io/gorm/clause"
@@ -488,50 +489,57 @@ func (s *ImageService) DeleteImageByDockerID(ctx context.Context, dockerImageID
return nil
}
-func (s *ImageService) ListImagesWithUpdatesPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]map[string]interface{}, utils.PaginationResponse, error) {
+// func (s *ImageService) ListImagesWithUpdatesPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]dto.ImageSummaryDto, 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("UpdateRecord")
+
+// if req.Sort.Column != "" {
+// dir := utils.NormalizeSortDirection(req.Sort.Direction)
+// col := utils.CamelCaseToSnakeCase(req.Sort.Column)
+// query = query.Order(col + " " + dir)
+// }
+
+// pagination, err := utils.PaginateAndSort(req, query, &images)
+// if err != nil {
+// return nil, utils.PaginationResponse{}, fmt.Errorf("failed to paginate images: %w", err)
+// }
+
+// result := make([]dto.ImageSummaryDto, 0, len(images))
+// for _, img := range images {
+// result = append(result, dto.NewImageSummaryDto(&img))
+// }
+
+// return result, pagination, nil
+// }
+
+func (s *ImageService) ListImagesWithUpdatesPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]dto.ImageSummaryDto, 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
+ var images []models.Image
query := s.db.WithContext(ctx).Model(&models.Image{}).Preload("UpdateRecord")
+ if req.Sort.Column != "" {
+ dir := utils.NormalizeSortDirection(req.Sort.Direction)
+ col := utils.CamelCaseToSnakeCase(req.Sort.Column)
+ query = query.Order(col + " " + dir)
+ }
+
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.UpdateRecord != nil {
- imageData["updateInfo"] = map[string]interface{}{
- "hasUpdate": img.UpdateRecord.HasUpdate,
- "updateType": img.UpdateRecord.UpdateType,
- "currentVersion": img.UpdateRecord.CurrentVersion,
- "latestVersion": img.UpdateRecord.LatestVersion,
- "currentDigest": img.UpdateRecord.CurrentDigest,
- "latestDigest": img.UpdateRecord.LatestDigest,
- "checkTime": img.UpdateRecord.CheckTime,
- "responseTimeMs": img.UpdateRecord.ResponseTimeMs,
- "error": img.UpdateRecord.LastError,
- }
- }
-
- result = append(result, imageData)
+ result := make([]dto.ImageSummaryDto, 0, len(images))
+ for i := range images {
+ result = append(result, dto.NewImageSummaryDto(&images[i]))
}
return result, pagination, nil
diff --git a/backend/internal/utils/page_util.go b/backend/internal/utils/page_util.go
index 3076c0c19..7fecbbcbb 100644
--- a/backend/internal/utils/page_util.go
+++ b/backend/internal/utils/page_util.go
@@ -50,35 +50,12 @@ func PaginateAndSort(sortedPaginationRequest SortedPaginationRequest, query *gor
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 := reflect.TypeOf(result).Elem().Elem().FieldByName(capitalizedSortColumn)
+ isSortable, _ := strconv.ParseBool(sortField.Tag.Get("sortable"))
- 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"
- }
+ sort.Direction = NormalizeSortDirection(sort.Direction)
if sortFieldFound && isSortable {
columnName := CamelCaseToSnakeCase(sort.Column)
@@ -92,30 +69,12 @@ func PaginateAndSort(sortedPaginationRequest SortedPaginationRequest, query *gor
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"},
- },
- })
- }
+func NormalizeSortDirection(direction string) string {
+ d := strings.ToLower(strings.TrimSpace(direction))
+ if d != "asc" && d != "desc" {
+ return "asc"
}
-
- return Paginate(page, pageSize, query, result)
+ return d
}
func Paginate(page int, pageSize int, query *gorm.DB, result interface{}) (PaginationResponse, error) {
@@ -153,80 +112,6 @@ func Paginate(page int, pageSize int, query *gorm.DB, result interface{}) (Pagin
}, 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)
-}
-
//nolint:gocognit
func SortSliceByField(data []map[string]interface{}, field, direction string) {
if field == "" {
diff --git a/backend/internal/utils/string_util.go b/backend/internal/utils/string_util.go
new file mode 100644
index 000000000..2b6d18d52
--- /dev/null
+++ b/backend/internal/utils/string_util.go
@@ -0,0 +1,21 @@
+package utils
+
+import "strings"
+
+func CapitalizeFirstLetter(str string) string {
+ if len(str) == 0 {
+ return str
+ }
+ return strings.ToUpper(str[:1]) + str[1:]
+}
+
+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())
+}
diff --git a/frontend/src/lib/components/image-update-item.svelte b/frontend/src/lib/components/image-update-item.svelte
index 0a99b0a72..86c2e196e 100644
--- a/frontend/src/lib/components/image-update-item.svelte
+++ b/frontend/src/lib/components/image-update-item.svelte
@@ -5,7 +5,10 @@
CircleFadingArrowUp,
CircleArrowUp,
Loader2,
- AlertTriangle
+ AlertTriangle,
+ RefreshCw,
+ ArrowRight,
+ Package
} from '@lucide/svelte';
import { imageUpdateAPI } from '$lib/services/api';
import { toast } from 'svelte-sonner';
@@ -63,7 +66,7 @@
const result = await imageUpdateAPI.checkImageUpdateByID(imageId);
if (result && !result.error) {
localUpdateInfo = result;
- onUpdated?.(result); // optional: lets a parent sync if desired
+ onUpdated?.(result);
toast.success('Update check completed');
} else {
toast.error(result?.error || 'Update check failed');
@@ -120,18 +123,152 @@
>
<div class="overflow-hidden rounded-xl">
{#if !localUpdateInfo.hasUpdate}
- <div class="p-3 text-xs">Running {displayCurrentVersion()}</div>
+ <!-- Success State -->
+ <div
+ class="bg-gradient-to-br from-emerald-50 to-green-50/30 p-4 dark:from-emerald-950/20 dark:to-green-950/10"
+ >
+ <div class="flex items-center gap-3">
+ <div
+ class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-emerald-500 to-green-500 shadow-lg shadow-emerald-500/25"
+ >
+ <CircleCheck class="size-5 text-white" />
+ </div>
+ <div>
+ <div class="text-sm font-semibold text-emerald-900 dark:text-emerald-100">
+ Up to Date
+ </div>
+ <div class="text-xs text-emerald-700/80 dark:text-emerald-300/80">
+ No updates available
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="bg-white/90 p-4 dark:bg-gray-950/90">
+ <div class="text-center">
+ <div class="mb-2 text-xs text-gray-600 dark:text-gray-400">
+ Running <span
+ class="rounded bg-gray-100 px-1.5 py-0.5 font-mono text-xs font-medium dark:bg-gray-800"
+ >{displayCurrentVersion()}</span
+ >
+ </div>
+ <div class="text-xs leading-relaxed text-gray-500 dark:text-gray-400">
+ This image is running the latest available version.
+ </div>
+ </div>
+ </div>
{:else if localUpdateInfo.updateType === 'digest'}
- <div class="p-3 text-xs">
- <div>Current: {displayCurrentVersion()}</div>
- {#if displayLatestVersion()}<div>Latest digest: {displayLatestVersion()}</div>{/if}
- <div class="mt-1 text-blue-600 dark:text-blue-300">{priority.description}</div>
+ <!-- Digest Update State -->
+ <div
+ class="bg-gradient-to-br from-blue-50 to-cyan-50/30 p-4 dark:from-blue-950/20 dark:to-cyan-950/10"
+ >
+ <div class="flex items-center gap-3">
+ <div
+ class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-blue-500 to-cyan-500 shadow-lg shadow-blue-500/25"
+ >
+ <CircleArrowUp class="size-5 text-white" />
+ </div>
+ <div>
+ <div class="text-sm font-semibold text-blue-900 dark:text-blue-100">
+ Digest Update
+ </div>
+ <div class="text-xs text-blue-700/80 dark:text-blue-300/80">
+ Security or bug fixes available
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="bg-white/90 p-4 dark:bg-gray-950/90">
+ <div class="space-y-3">
+ <div class="space-y-2 text-xs">
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-1.5 text-gray-500 dark:text-gray-400">
+ <Package class="size-3" />
+ <span>Current</span>
+ </div>
+ <span
+ class="rounded bg-gray-100 px-1.5 py-0.5 font-mono font-medium dark:bg-gray-800"
+ >{displayCurrentVersion()}</span
+ >
+ </div>
+ {#if displayLatestVersion()}
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-1.5 text-gray-500 dark:text-gray-400">
+ <ArrowRight class="size-3" />
+ <span>Latest Digest</span>
+ </div>
+ <span
+ class="rounded bg-blue-100 px-1.5 py-0.5 font-mono font-medium text-blue-700 dark:bg-blue-900/30 dark:text-blue-300"
+ >
+ {displayLatestVersion()}
+ </span>
+ </div>
+ {/if}
+ </div>
+ <div class="rounded-lg bg-blue-50 p-3 dark:bg-blue-950/30">
+ <div
+ class="text-xs text-center leading-relaxed text-blue-700 dark:text-blue-300 font-medium"
+ >
+ {priority.description}
+ </div>
+ </div>
+ </div>
</div>
{:else}
- <div class="p-3 text-xs">
- <div>Current: {displayCurrentVersion()}</div>
- {#if displayLatestVersion()}<div>Latest: {displayLatestVersion()}</div>{/if}
- <div class="mt-1 text-amber-600 dark:text-amber-300">{priority.description}</div>
+ <!-- Version Update State -->
+ <div
+ class="bg-gradient-to-br from-amber-50 to-yellow-50/30 p-4 dark:from-amber-950/20 dark:to-yellow-950/10"
+ >
+ <div class="flex items-center gap-3">
+ <div
+ class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-amber-500 to-yellow-500 shadow-lg shadow-amber-500/25"
+ >
+ <CircleFadingArrowUp class="size-5 text-white" />
+ </div>
+ <div>
+ <div class="text-sm font-semibold text-amber-900 dark:text-amber-100">
+ Version Update
+ </div>
+ <div class="text-xs text-amber-700/80 dark:text-amber-300/80">
+ New version available
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="bg-white/90 p-4 dark:bg-gray-950/90">
+ <div class="space-y-3">
+ <div class="space-y-2 text-xs">
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-1.5 text-gray-500 dark:text-gray-400">
+ <Package class="size-3" />
+ <span>Current</span>
+ </div>
+ <span
+ class="rounded bg-gray-100 px-1.5 py-0.5 font-mono font-medium dark:bg-gray-800"
+ >{displayCurrentVersion()}</span
+ >
+ </div>
+ {#if displayLatestVersion()}
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-1.5 text-gray-500 dark:text-gray-400">
+ <ArrowRight class="size-3" />
+ <span>Latest</span>
+ </div>
+ <span
+ class="rounded bg-amber-100 px-1.5 py-0.5 font-mono font-medium text-amber-700 dark:bg-amber-900/30 dark:text-amber-300"
+ >
+ {displayLatestVersion()}
+ </span>
+ </div>
+ {/if}
+ </div>
+ <div class="rounded-lg bg-amber-50 p-3 dark:bg-amber-950/30">
+ <div
+ class="text-xs text-center leading-relaxed text-amber-700 dark:text-amber-300 font-medium"
+ >
+ {priority.description}
+ </div>
+ </div>
+ </div>
</div>
{/if}
@@ -148,6 +285,7 @@
<Loader2 class="size-3 animate-spin" />
Checking...
{:else}
+ <RefreshCw class="size-3 transition-transform group-hover:rotate-45" />
Re-check Updates
{/if}
</button>
@@ -165,6 +303,33 @@
<Loader2 class="size-4 animate-spin text-blue-400" />
</span>
</Tooltip.Trigger>
+ <Tooltip.Content
+ side="right"
+ class="tooltip-with-arrow relative max-w-[220px] rounded-xl border border-gray-200/50 bg-white/95 p-0 shadow-2xl shadow-black/10 backdrop-blur-sm dark:border-gray-800/50 dark:bg-gray-950/95 dark:shadow-black/30"
+ align="center"
+ >
+ <div class="overflow-hidden rounded-xl">
+ <div
+ class="bg-gradient-to-br from-blue-50 to-cyan-50/30 p-4 dark:from-blue-950/20 dark:to-cyan-950/10"
+ >
+ <div class="flex items-center gap-3">
+ <div
+ class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-blue-500 to-cyan-500 shadow-lg shadow-blue-500/25"
+ >
+ <Loader2 class="size-5 animate-spin text-white" />
+ </div>
+ <div>
+ <div class="text-sm font-semibold text-blue-900 dark:text-blue-100">
+ Checking Updates
+ </div>
+ <div class="text-xs text-blue-700/80 dark:text-blue-300/80">
+ Querying registry for latest version...
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </Tooltip.Content>
</Tooltip.Root>
</Tooltip.Provider>
{:else}
@@ -201,9 +366,28 @@
align="center"
>
<div class="overflow-hidden rounded-xl">
- <div class="p-3 text-xs flex items-center gap-2">
- <AlertTriangle class="size-4" />
- Status unknown. Click to check for updates.
+ <div
+ class="bg-gradient-to-br from-gray-50 to-slate-50/30 p-4 dark:from-gray-900/20 dark:to-slate-900/10"
+ >
+ <div class="flex items-center gap-3">
+ <div
+ class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-gray-400 to-slate-500 shadow-lg shadow-gray-400/25"
+ >
+ <AlertTriangle class="size-5 text-white" />
+ </div>
+ <div>
+ <div class="text-sm font-semibold text-gray-900 dark:text-gray-100">
+ Status Unknown
+ </div>
+ <div class="text-xs text-gray-700/80 dark:text-gray-300/80">
+ {#if canCheckUpdate}
+ Click to check for updates from registry.
+ {:else}
+ Unable to check updates for images without proper tags.
+ {/if}
+ </div>
+ </div>
+ </div>
</div>
</div>
</Tooltip.Content>
diff --git a/frontend/src/lib/models/container-info.ts b/frontend/src/lib/models/container-info.ts
deleted file mode 100644
index 6126533e0..000000000
--- a/frontend/src/lib/models/container-info.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-export type ContainerInfo = {
- Id: string;
- Names: string[];
- Image: string;
- ImageID: string;
- Command: string;
- Created: number;
- Ports: Array<{
- IP?: string;
- PrivatePort: number;
- PublicPort?: number;
- Type: string;
- }>;
- Labels: Record<string, string> | null;
- State: string;
- Status: string;
- HostConfig: {
- NetworkMode?: string;
- [key: string]: any;
- };
- NetworkSettings: {
- Networks?: Record<string, any>;
- [key: string]: any;
- };
- Mounts: Array<{
- Type: string;
- Source: string;
- Destination: string;
- Mode: string;
- [key: string]: any;
- }>;
- // Add common fields that might be missing
- SizeRw?: number;
- SizeRootFs?: number;
-};
-
-export type EnhancedContainerInfo = ContainerInfo & {
- displayName: string;
- statusSortValue: number;
-};
diff --git a/frontend/src/lib/models/image.type.ts b/frontend/src/lib/models/image.type.ts
deleted file mode 100644
index 63ac2c43b..000000000
--- a/frontend/src/lib/models/image.type.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import type Docker from 'dockerode';
-
-export type ServiceImage = Docker.ImageInfo & {
- repo: string;
- tag: string;
- Architecture?: string;
- Os?: string;
- Config?: {
- User?: string;
- ExposedPorts?: Record<string, any>;
- Env?: string[];
- Entrypoint?: string[];
- WorkingDir?: string;
- Labels?: Record<string, string>;
- };
- GraphDriver?: {
- Data: any;
- Name: string;
- };
- RootFS?: {
- Type: string;
- Layers: string[];
- };
- Metadata?: {
- LastTagTime?: string;
- };
- Descriptor?: {
- mediaType: string;
- digest: string;
- size: number;
- };
-};
-
-export interface ImageUpdateInfo {
- hasUpdate: boolean;
- updateType: string;
- currentVersion: string;
- latestVersion?: string;
- currentDigest?: string;
- latestDigest?: string;
- checkTime: string;
- responseTimeMs: number;
- error?: string;
-}
-
-export type EnhancedImageInfo = ServiceImage & {
- InUse: boolean;
- updateInfo?: ImageUpdateInfo;
-};
diff --git a/frontend/src/lib/services/api/environment-api-service.ts b/frontend/src/lib/services/api/environment-api-service.ts
index e5518e821..4f76fb0ce 100644
--- a/frontend/src/lib/services/api/environment-api-service.ts
+++ b/frontend/src/lib/services/api/environment-api-service.ts
@@ -7,15 +7,17 @@ import type {
VolumeCreateOptions,
ContainerStats
} from 'dockerode';
-import type { Project, ProjectService } from '$lib/types/project.type';
+import type { Project } from '$lib/types/project.type';
import type {
PaginationRequest,
SortRequest,
- PaginatedApiResponse
+ PaginatedApiResponse,
+ SearchPaginationSortRequest,
+ Paginated
} 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';
+import type { ContainerSummaryDto } from '$lib/types/container.type';
+import type { ImageSummaryDto } from '$lib/types/image.type';
export class EnvironmentAPIService extends BaseAPIService {
private async getCurrentEnvironmentId(): Promise<string> {
@@ -30,45 +32,12 @@ export class EnvironmentAPIService extends BaseAPIService {
}
async getContainers(
- pagination?: PaginationRequest,
- sort?: SortRequest,
- search?: string,
- filters?: Record<string, string>
- ): Promise<any[] | PaginatedApiResponse<any>> {
+ options?: SearchPaginationSortRequest
+ ): Promise<Paginated<ContainerSummaryDto>> {
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 }));
+ const res = await this.api.get(`/environments/${envId}/containers`, { params: options });
+ return res.data;
}
async getContainer(containerId: string): Promise<any> {
@@ -120,44 +89,11 @@ export class EnvironmentAPIService extends BaseAPIService {
);
}
- async getImages(
- pagination?: PaginationRequest,
- sort?: SortRequest,
- search?: string,
- filters?: Record<string, string>
- ): Promise<any[] | PaginatedApiResponse<any>> {
+ async getImages(options?: SearchPaginationSortRequest): Promise<Paginated<ImageSummaryDto>> {
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 }));
+ const res = await this.api.get(`/environments/${envId}/images`, { params: options });
+ return res.data;
}
async getTotalImageSize(): Promise<number> {
@@ -376,44 +312,11 @@ export class EnvironmentAPIService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/execute`, { command, args }));
}
- async getProjects(
- pagination?: PaginationRequest,
- sort?: SortRequest,
- search?: string,
- filters?: Record<string, string>
- ): Promise<any[] | PaginatedApiResponse<any>> {
+ async getProjects(options?: SearchPaginationSortRequest): Promise<Paginated<Project>> {
const envId = await this.getCurrentEnvironmentId();
- if (!pagination) {
- const response = await this.handleResponse<{ stacks?: Project[] }>(
- 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 }));
+ const res = await this.api.get(`/environments/${envId}/stacks`, { params: options });
+ return res.data;
}
async getProject(projectName: string): Promise<Project> {
diff --git a/frontend/src/lib/types/container.type.ts b/frontend/src/lib/types/container.type.ts
new file mode 100644
index 000000000..b4f6d7b1c
--- /dev/null
+++ b/frontend/src/lib/types/container.type.ts
@@ -0,0 +1,88 @@
+export interface BaseContainer {
+ id: string;
+ names: string[];
+ image: string;
+ imageId: string;
+ command: string;
+ created: number;
+ labels: Record<string, string>;
+ state: string;
+ status: string;
+}
+
+export interface PortDto {
+ ip?: string;
+ privatePort: number;
+ publicPort?: number;
+ type: string;
+}
+
+export interface MountDto {
+ type: string;
+ name?: string;
+ source?: string;
+ destination: string;
+ driver?: string;
+ mode?: string;
+ rw?: boolean;
+ propagation?: string;
+}
+
+export interface NetworkDto {
+ ipamConfig: any | null;
+ links: string[] | null;
+ aliases: string[] | null;
+ macAddress: string;
+ driverOpts: Record<string, string> | null;
+ gwPriority: number;
+ networkId: string;
+ endpointId: string;
+ gateway: string;
+ ipAddress: string;
+ ipPrefixLen: number;
+ ipv6Gateway: string;
+ globalIPv6Address: string;
+ globalIPv6PrefixLen: number;
+ dnsNames: string[] | null;
+}
+
+export interface HostConfigDto {
+ networkMode: string;
+}
+
+export interface NetworkSettingsDto {
+ networks: Record<string, NetworkDto>;
+}
+
+export interface ContainerSummaryDto extends BaseContainer {
+ ports: PortDto[];
+ hostConfig: HostConfigDto;
+ networkSettings: NetworkSettingsDto;
+ mounts: MountDto[];
+}
+
+export interface CreateContainerDto {
+ name: string;
+ image: string;
+ command?: string[];
+ entrypoint?: string[];
+ workingDir?: string;
+ user?: string;
+ environment?: string[];
+ ports?: Record<string, string>;
+ volumes?: string[];
+ networks?: string[];
+ restartPolicy?: string;
+ privileged?: boolean;
+ autoRemove?: boolean;
+ memory?: number;
+ cpus?: number;
+}
+
+export interface ContainerActionResult {
+ started?: string[];
+ stopped?: string[];
+ failed?: string[];
+ success: boolean;
+ errors?: string[];
+}
diff --git a/frontend/src/lib/types/image.type.ts b/frontend/src/lib/types/image.type.ts
new file mode 100644
index 000000000..383e37b26
--- /dev/null
+++ b/frontend/src/lib/types/image.type.ts
@@ -0,0 +1,25 @@
+export interface ImageUpdateInfoDto {
+ hasUpdate: boolean;
+ updateType: string;
+ currentVersion: string;
+ latestVersion: string;
+ currentDigest: string;
+ latestDigest: string;
+ checkTime: string; // ISO string from backend
+ responseTimeMs: number;
+ error: string;
+}
+
+export interface ImageSummaryDto {
+ id: string;
+ repoTags: string[];
+ repoDigests: string[];
+ created: number;
+ size: number;
+ virtualSize: number;
+ labels: Record<string, unknown> | null;
+ inUse: boolean;
+ repo: string;
+ tag: string;
+ updateInfo?: ImageUpdateInfoDto;
+}
diff --git a/frontend/src/lib/types/project.type.ts b/frontend/src/lib/types/project.type.ts
index 865117b08..4a023f247 100644
--- a/frontend/src/lib/types/project.type.ts
+++ b/frontend/src/lib/types/project.type.ts
@@ -43,27 +43,35 @@ export interface ProjectService {
export interface Project {
id: string;
name: string;
+ path: string;
+ runningCount: string;
+ serviceCount: string;
+ status: string;
+ updatedAt: string;
+ createdAt: string;
+ autoUpdate?: boolean;
services?: ProjectService[];
- serviceCount?: number;
- runningCount?: number;
- status: 'running' | 'stopped' | 'partially running' | 'unknown';
- isExternal?: boolean;
- createdAt?: string;
- updatedAt?: string;
composeContent?: string;
envContent?: string;
- isLegacy?: boolean;
- agentId?: string;
- agentHostname?: string;
- isRemote?: boolean;
- dirName?: string;
- lastPolled?: string;
- path?: string;
}
-export interface ProjectUpdate {
- name?: string;
- composeContent?: string;
- envContent?: string;
- autoUpdate?: boolean;
-}
+// export interface Project {
+// id: string;
+// name: string;
+// services?: ProjectService[];
+// serviceCount?: number;
+// runningCount?: number;
+// status: 'running' | 'stopped' | 'partially running' | 'unknown';
+// isExternal?: boolean;
+// createdAt?: string;
+// updatedAt?: string;
+// composeContent?: string;
+// envContent?: string;
+// isLegacy?: boolean;
+// agentId?: string;
+// agentHostname?: string;
+// isRemote?: boolean;
+// dirName?: string;
+// lastPolled?: string;
+// path?: string;
+// }
diff --git a/frontend/src/routes/compose/+page.svelte b/frontend/src/routes/compose/+page.svelte
index 45fb0672c..97e12fac9 100644
--- a/frontend/src/routes/compose/+page.svelte
+++ b/frontend/src/routes/compose/+page.svelte
@@ -1,6 +1,4 @@
<script lang="ts">
- import type { PageData } from './$types';
- import type { Project } from '$lib/types/project.type';
import { AlertCircle, FileStack, Loader2, PlayCircle, StopCircle } from '@lucide/svelte';
import * as Alert from '$lib/components/ui/alert/index.js';
import * as Card from '$lib/components/ui/card/index.js';
@@ -9,68 +7,26 @@
import { tryCatch } from '$lib/utils/try-catch';
import ArcaneButton from '$lib/components/arcane-button.svelte';
import { autoUpdateAPI, environmentAPI } from '$lib/services/api';
- import { onMount } from 'svelte';
import StatCard from '$lib/components/stat-card.svelte';
- import StackTable from './compose-table.svelte';
- import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import ProjectsTable from './compose-table.svelte';
import { goto } from '$app/navigation';
- let { data }: { data: PageData } = $props();
+ let { data } = $props();
- let Compose = $state<Project[]>(
- Array.isArray(data.projects) ? data.projects : data.projects.data || []
- );
+ let projects = $state(data.projects);
+ let projectRequestOptions = $state(data.projectRequestOptions);
let error = $state<string | null>(null);
let selectedIds = $state<string[]>([]);
let isLoadingCompose = $state(false);
- let requestOptions = $state<SearchPaginationSortRequest>(data.projectRequestOptions);
let isLoading = $state({
updating: false,
refreshing: false
});
- const totalCompose = $derived(Compose.length);
- const runningCompose = $derived(Compose.filter((s) => s.status === 'running').length);
- const stoppedCompose = $derived(Compose.filter((s) => s.status === 'stopped').length);
-
- async function loadCompose() {
- try {
- isLoadingCompose = true;
- const response = await environmentAPI.getProjects(
- requestOptions.pagination,
- requestOptions.sort,
- requestOptions.search,
- requestOptions.filters
- );
- Compose = Array.isArray(response) ? response : response.data || [];
- error = null;
- } catch (err) {
- console.error('Failed to load compose page:', err);
- error = err instanceof Error ? err.message : 'Failed to load Docker Compose Compose';
- Compose = [];
- } finally {
- isLoadingCompose = false;
- }
- }
-
- onMount(() => {
- if (Compose.length === 0) {
- loadCompose();
- }
- });
-
- async function refreshCompose() {
- isLoading.refreshing = true;
- try {
- await loadCompose();
- } catch (error) {
- console.error('Failed to refresh Compose:', error);
- toast.error('Failed to refresh Compose');
- } finally {
- isLoading.refreshing = false;
- }
- }
+ const totalCompose = $derived(projects.pagination.totalItems);
+ const runningCompose = $derived(projects.data.filter((s) => s.status === 'running').length);
+ const stoppedCompose = $derived(projects.data.filter((s) => s.status === 'stopped').length);
async function handleCheckForUpdates() {
isLoading.updating = true;
@@ -80,24 +36,10 @@
setLoadingState: (value) => (isLoading.updating = value),
async onSuccess() {
toast.success('Compose Projects Updated Successfully.');
- await loadCompose();
+ projects = await environmentAPI.getProjects(projectRequestOptions);
}
});
}
-
- async function onRefresh(options: SearchPaginationSortRequest) {
- requestOptions = options;
- await loadCompose();
- return {
- data: Compose,
- pagination: {
- totalPages: Math.ceil(Compose.length / (requestOptions.pagination?.limit || 20)),
- totalItems: Compose.length,
- currentPage: requestOptions.pagination?.page || 1,
- itemsPerPage: requestOptions.pagination?.limit || 20
- }
- };
- }
</script>
<div class="space-y-6">
@@ -107,13 +49,13 @@
<p class="text-muted-foreground mt-1 text-sm">View and Manage Compose Projects</p>
</div>
<div class="flex items-center gap-2">
- <ArcaneButton
+ <!-- <ArcaneButton
action="restart"
onClick={refreshCompose}
label="Refresh"
loading={isLoading.refreshing}
disabled={isLoading.refreshing}
- />
+ /> -->
<ArcaneButton
action="create"
customLabel="Create Project"
@@ -190,12 +132,10 @@
/>
</div>
- <StackTable
- {Compose}
+ <ProjectsTable
+ bind:projects
bind:selectedIds
- {requestOptions}
- {onRefresh}
- onComposeChanged={loadCompose}
+ requestOptions={projectRequestOptions}
onCheckForUpdates={handleCheckForUpdates}
/>
{/if}
diff --git a/frontend/src/routes/compose/+page.ts b/frontend/src/routes/compose/+page.ts
index 4f3342ad5..b09c574d3 100644
--- a/frontend/src/routes/compose/+page.ts
+++ b/frontend/src/routes/compose/+page.ts
@@ -6,7 +6,7 @@ export const load: PageLoad = async () => {
const projectRequestOptions: SearchPaginationSortRequest = {
pagination: {
page: 1,
- limit: 20
+ limit: 10
},
sort: {
column: 'name',
@@ -14,12 +14,7 @@ export const load: PageLoad = async () => {
}
};
- const projects = await environmentAPI.getProjects(
- projectRequestOptions.pagination,
- projectRequestOptions.sort,
- projectRequestOptions.search,
- projectRequestOptions.filters
- );
+ const projects = await environmentAPI.getProjects(projectRequestOptions);
return { projects, projectRequestOptions };
};
diff --git a/frontend/src/routes/compose/[projectId]/+page.svelte b/frontend/src/routes/compose/[projectId]/+page.svelte
index 9f2b832c2..9c6365257 100644
--- a/frontend/src/routes/compose/[projectId]/+page.svelte
+++ b/frontend/src/routes/compose/[projectId]/+page.svelte
@@ -31,7 +31,6 @@
import ArcaneButton from '$lib/components/arcane-button.svelte';
import LogViewer from '$lib/components/LogViewer.svelte';
import { browser } from '$app/environment';
- import FormInput from '$lib/components/form/form-input.svelte';
let { data }: { data: PageData } = $props();
let { project, editorState, servicePorts, settings } = $derived(data);
diff --git a/frontend/src/routes/compose/compose-table.svelte b/frontend/src/routes/compose/compose-table.svelte
index 53d7c588a..fde7c2222 100644
--- a/frontend/src/routes/compose/compose-table.svelte
+++ b/frontend/src/routes/compose/compose-table.svelte
@@ -28,23 +28,15 @@
import { capitalizeFirstLetter } from '$lib/utils/string.utils';
import { formatFriendlyDate } from '$lib/utils/date.utils';
- interface StackWithId extends Project {
- id: string;
- }
-
let {
- Compose,
+ projects = $bindable(),
selectedIds = $bindable(),
requestOptions = $bindable(),
- onRefresh,
- onComposeChanged,
onCheckForUpdates
}: {
- Compose: Project[];
+ projects: Paginated<Project>;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
- onRefresh: (options: SearchPaginationSortRequest) => Promise<any>;
- onComposeChanged: () => Promise<void>;
onCheckForUpdates: () => Promise<void>;
} = $props();
@@ -58,23 +50,6 @@
updating: false
});
- const ComposeWithId = $derived(
- Compose.map((stack) => ({
- ...stack,
- id: stack.id || stack.name
- }))
- );
-
- const paginatedCompose: Paginated<StackWithId> = $derived({
- data: ComposeWithId,
- pagination: {
- totalPages: Math.ceil(ComposeWithId.length / (requestOptions.pagination?.limit || 20)),
- totalItems: ComposeWithId.length,
- currentPage: requestOptions.pagination?.page || 1,
- itemsPerPage: requestOptions.pagination?.limit || 20
- }
- });
-
async function performProjectAction(action: string, id: string) {
isLoading[action as keyof typeof isLoading] = true;
@@ -86,7 +61,7 @@
setLoadingState: (value) => (isLoading.start = value),
onSuccess: async () => {
toast.success('Project Started Successfully.');
- await onComposeChanged();
+ projects = await environmentAPI.getProjects(requestOptions);
}
});
} else if (action === 'stop') {
@@ -96,7 +71,7 @@
setLoadingState: (value) => (isLoading.stop = value),
onSuccess: async () => {
toast.success('Project Stopped Successfully.');
- await onComposeChanged();
+ projects = await environmentAPI.getProjects(requestOptions);
}
});
} else if (action === 'restart') {
@@ -106,7 +81,7 @@
setLoadingState: (value) => (isLoading.restart = value),
onSuccess: async () => {
toast.success('Project Restarted Successfully.');
- await onComposeChanged();
+ projects = await environmentAPI.getProjects(requestOptions);
}
});
} else if (action === 'pull') {
@@ -116,7 +91,7 @@
setLoadingState: (value) => (isLoading.pull = value),
onSuccess: async () => {
toast.success('Project Pulled successfully.');
- await onComposeChanged();
+ projects = await environmentAPI.getProjects(requestOptions);
}
});
} else if (action === 'destroy') {
@@ -133,7 +108,7 @@
setLoadingState: (value) => (isLoading.destroy = value),
onSuccess: async () => {
toast.success('Project Removed Successfully');
- await onComposeChanged();
+ projects = await environmentAPI.getProjects(requestOptions);
}
});
}
@@ -150,7 +125,7 @@
const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
</script>
-{#if ComposeWithId.length > 0}
+{#if projects.data.length > 0}
<Card.Root class="border shadow-sm">
<Card.Header class="px-6">
<div class="flex items-center justify-between">
@@ -171,10 +146,9 @@
</Card.Header>
<Card.Content>
<ArcaneTable
- items={paginatedCompose}
+ items={projects}
bind:requestOptions
bind:selectedIds
- {onRefresh}
columns={[
{ label: 'Name', sortColumn: 'name' },
{ label: 'Services', sortColumn: 'service_count' },
@@ -184,6 +158,7 @@
]}
filterPlaceholder="Search projects..."
noResultsMessage="No projects found"
+ onRefresh={async (options) => (projects = await environmentAPI.getProjects(options))}
>
{#snippet rows({ item })}
{@const stateVariant = item.status ? statusVariantMap[item.status.toLowerCase()] : 'gray'}
diff --git a/frontend/src/routes/containers/+page.svelte b/frontend/src/routes/containers/+page.svelte
index e4d470d97..01c058fce 100644
--- a/frontend/src/routes/containers/+page.svelte
+++ b/frontend/src/routes/containers/+page.svelte
@@ -4,22 +4,15 @@
import { toast } from 'svelte-sonner';
import { tryCatch } from '$lib/utils/try-catch';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
- import type { PageData } from './$types';
import StatCard from '$lib/components/stat-card.svelte';
- import type { ContainerInfo } from '$lib/models/container-info';
import { autoUpdateAPI, environmentAPI } from '$lib/services/api';
- import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
import ContainerTable from './container-table.svelte';
import ArcaneButton from '$lib/components/arcane-button.svelte';
- interface ContainerWithId extends ContainerInfo {
- id: string;
- }
-
- let { data }: { data: PageData } = $props();
+ let { data } = $props();
- let containers = $state<ContainerInfo[]>([]);
- let paginatedContainers = $state<Paginated<ContainerWithId> | null>(null);
+ let containers = $state(data.containers);
+ let requestOptions = $state(data.containerRequestOptions);
let selectedIds = $state([]);
let isCreateDialogOpen = $state(false);
@@ -29,79 +22,6 @@
refreshing: false
});
- 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 || [];
- }
- }
- });
-
- 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;
- }
- }
-
- async function refreshContainers() {
- isLoading.refreshing = true;
- try {
- await onRefresh(requestOptions);
- } catch (error) {
- console.error('Failed to refresh containers:', error);
- toast.error('Failed to refresh containers');
- } finally {
- isLoading.refreshing = false;
- }
- }
-
async function handleCheckForUpdates() {
isLoading.checking = true;
handleApiResultWithCallbacks({
@@ -110,13 +30,24 @@
setLoadingState: (value) => (isLoading.checking = value),
async onSuccess() {
toast.success('Containers Updated Successfully.');
- await refreshContainers();
+ containers = await environmentAPI.getContainers(requestOptions);
}
});
}
- async function onContainersChanged() {
- await refreshContainers();
+ const runningContainers = $derived(containers.data.filter((s) => s.state === 'running').length);
+ const stoppedContainers = $derived(containers.data.filter((s) => s.state != 'running').length);
+
+ async function refreshContainers() {
+ isLoading.refreshing = true;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.getContainers(requestOptions)),
+ message: 'Failed to Refresh Containers for Updates',
+ setLoadingState: (value) => (isLoading.refreshing = value),
+ async onSuccess(newContainers) {
+ containers = newContainers;
+ }
+ });
}
</script>
@@ -147,13 +78,13 @@
<div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
<StatCard
title="Total"
- value={data.dockerInfo.containers}
+ value={containers.pagination.totalItems}
icon={Box}
class="border-l-primary border-l-4 transition-shadow hover:shadow-lg"
/>
<StatCard
title="Running"
- value={data.dockerInfo.containersRunning}
+ value={runningContainers}
icon={Box}
iconColor="text-green-500"
bgColor="bg-green-500/10"
@@ -161,7 +92,7 @@
/>
<StatCard
title="Stopped"
- value={data.dockerInfo.containersStopped}
+ value={stoppedContainers}
icon={Box}
iconColor="text-amber-500"
class="border-l-4 border-l-amber-500"
@@ -169,19 +100,9 @@
</div>
<ContainerTable
- containers={paginatedContainers || {
- data: containers.map((c) => ({ ...c, id: c.Id })),
- pagination: {
- totalPages: 1,
- totalItems: containers.length,
- currentPage: 1,
- itemsPerPage: containers.length
- }
- }}
+ bind:containers
bind:selectedIds
bind:requestOptions
- {onRefresh}
- {onContainersChanged}
onCheckForUpdates={handleCheckForUpdates}
/>
@@ -199,7 +120,7 @@
setLoadingState: (value) => (isLoading.create = value),
onSuccess: async () => {
toast.success('Container Created Successfully.');
- await refreshContainers();
+ containers = await environmentAPI.getContainers(requestOptions);
isCreateDialogOpen = false;
}
});
diff --git a/frontend/src/routes/containers/+page.ts b/frontend/src/routes/containers/+page.ts
index d85cb08ca..86e071bca 100644
--- a/frontend/src/routes/containers/+page.ts
+++ b/frontend/src/routes/containers/+page.ts
@@ -1,4 +1,4 @@
-import { environmentAPI, systemAPI } from '$lib/services/api';
+import { environmentAPI } from '$lib/services/api';
import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
import type { PageLoad } from './$types';
@@ -14,14 +14,7 @@ export const load: PageLoad = async () => {
}
};
- const dockerInfo = await systemAPI.getDockerInfo();
+ const containers = await environmentAPI.getContainers(containerRequestOptions);
- const containers = await environmentAPI.getContainers(
- containerRequestOptions.pagination,
- containerRequestOptions.sort,
- containerRequestOptions.search,
- containerRequestOptions.filters
- );
-
- return { dockerInfo, containers, containerRequestOptions };
+ return { containers, containerRequestOptions };
};
diff --git a/frontend/src/routes/containers/[containerId]/+page.svelte b/frontend/src/routes/containers/[containerId]/+page.svelte
index f33905b97..788895c52 100644
--- a/frontend/src/routes/containers/[containerId]/+page.svelte
+++ b/frontend/src/routes/containers/[containerId]/+page.svelte
@@ -61,10 +61,8 @@
let statsEventSource: EventSource | null = $state(null);
let showFloatingHeader = $state(false);
- // Helper function to clean container name
const cleanContainerName = (name: string | undefined): string => {
if (!name) return 'Container Details';
- // Remove leading slash and any extra slashes
return name.replace(/^\/+/, '');
};
@@ -191,7 +189,6 @@
}, 500);
}
- // LogViewer callback functions
function handleLogStart() {
isStreaming = true;
}
diff --git a/frontend/src/routes/containers/container-table.svelte b/frontend/src/routes/containers/container-table.svelte
index 5f8639c1f..3bad7e167 100644
--- a/frontend/src/routes/containers/container-table.svelte
+++ b/frontend/src/routes/containers/container-table.svelte
@@ -1,5 +1,4 @@
<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 {
@@ -26,24 +25,17 @@
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import { formatFriendlyDate } from '$lib/utils/date.utils';
import { capitalizeFirstLetter } from '$lib/utils/string.utils';
-
- interface ContainerWithId extends ContainerInfo {
- id: string;
- }
+ import type { ContainerSummaryDto } from '$lib/types/container.type';
let {
- containers,
+ containers = $bindable(),
selectedIds = $bindable(),
requestOptions = $bindable(),
- onRefresh,
- onContainersChanged,
onCheckForUpdates
}: {
- containers: Paginated<ContainerWithId>;
+ containers: Paginated<ContainerSummaryDto>;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
- onRefresh: (options: SearchPaginationSortRequest) => Promise<Paginated<ContainerWithId>>;
- onContainersChanged: () => Promise<void>;
onCheckForUpdates: () => Promise<void>;
} = $props();
@@ -66,7 +58,7 @@
setLoadingState: (value) => (isLoading.start = value),
async onSuccess() {
toast.success('Container Started Successfully.');
- await onContainersChanged();
+ containers = await environmentAPI.getContainers(requestOptions);
}
});
} else if (action === 'stop') {
@@ -76,7 +68,7 @@
setLoadingState: (value) => (isLoading.stop = value),
async onSuccess() {
toast.success('Container Stopped Successfully.');
- await onContainersChanged();
+ containers = await environmentAPI.getContainers(requestOptions);
}
});
} else if (action === 'restart') {
@@ -86,7 +78,7 @@
setLoadingState: (value) => (isLoading.restart = value),
async onSuccess() {
toast.success('Container Restarted Successfully.');
- await onContainersChanged();
+ containers = await environmentAPI.getContainers(requestOptions);
}
});
}
@@ -111,7 +103,7 @@
setLoadingState: (value) => (isLoading.remove = value),
async onSuccess() {
toast.success('Container Removed Successfully.');
- await onContainersChanged();
+ containers = await environmentAPI.getContainers(requestOptions);
}
});
}
@@ -147,7 +139,7 @@
items={containers}
bind:requestOptions
bind:selectedIds
- {onRefresh}
+ onRefresh={async (options) => (containers = await environmentAPI.getContainers(options))}
columns={[
{ label: 'Name', sortColumn: 'names' },
{ label: 'ID' },
@@ -162,36 +154,36 @@
>
{#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]}
+ <a class="font-medium hover:underline" href="/containers/{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)}
+ {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>
+ <span class="font-mono text-sm">{item.id.substring(0, 12)}</span>
</Table.Cell>
<Table.Cell>
- <span class="text-sm">{item.Image}</span>
+ <span class="text-sm">{item.image}</span>
</Table.Cell>
<Table.Cell>
<StatusBadge
- variant={item.State === 'running'
+ variant={item.state === 'running'
? 'green'
- : item.State === 'exited'
+ : item.state === 'exited'
? 'red'
: 'amber'}
- text={capitalizeFirstLetter(item.State)}
+ text={capitalizeFirstLetter(item.state)}
/>
</Table.Cell>
<Table.Cell>
- <span class="text-sm">{item.Status}</span>
+ <span class="text-sm">{item.status}</span>
</Table.Cell>
<Table.Cell>
<span class="text-sm">
- {item.Created ? formatFriendlyDate(new Date(item.Created * 1000).toISOString()) : ''}
+ {item.created ? formatFriendlyDate(new Date(item.created * 1000).toISOString()) : ''}
</span>
</Table.Cell>
<Table.Cell>
@@ -207,16 +199,16 @@
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
<DropdownMenu.Item
- onclick={() => goto(`/containers/${item.Id || item.id}`)}
+ onclick={() => goto(`/containers/${item.id}`)}
disabled={isAnyLoading}
>
<ScanSearch class="size-4" />
Inspect
</DropdownMenu.Item>
- {#if item.State !== 'running'}
+ {#if item.state !== 'running'}
<DropdownMenu.Item
- onclick={() => performContainerAction('start', item.Id || item.id)}
+ onclick={() => performContainerAction('start', item.id)}
disabled={isLoading.start || isAnyLoading}
>
{#if isLoading.start}
@@ -228,7 +220,7 @@
</DropdownMenu.Item>
{:else}
<DropdownMenu.Item
- onclick={() => performContainerAction('restart', item.Id || item.id)}
+ onclick={() => performContainerAction('restart', item.id)}
disabled={isLoading.restart || isAnyLoading}
>
{#if isLoading.restart}
@@ -240,7 +232,7 @@
</DropdownMenu.Item>
<DropdownMenu.Item
- onclick={() => performContainerAction('stop', item.Id || item.id)}
+ onclick={() => performContainerAction('stop', item.id)}
disabled={isLoading.stop || isAnyLoading}
>
{#if isLoading.stop}
@@ -256,7 +248,7 @@
<DropdownMenu.Item
variant="destructive"
- onclick={() => handleRemoveContainer(item.Id || item.id)}
+ onclick={() => handleRemoveContainer(item.id)}
disabled={isLoading.remove || isAnyLoading}
>
{#if isLoading.remove}
@@ -279,7 +271,7 @@
<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
+ Create a new container using the "Create Container" button above
</p>
</div>
{/if}
diff --git a/frontend/src/routes/dashboard/+page.svelte b/frontend/src/routes/dashboard/+page.svelte
index 2e6b3f6d1..67ecb3f2f 100644
--- a/frontend/src/routes/dashboard/+page.svelte
+++ b/frontend/src/routes/dashboard/+page.svelte
@@ -1,5 +1,4 @@
<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 {
@@ -18,7 +17,6 @@
} from '@lucide/svelte';
import * as Alert from '$lib/components/ui/alert/index.js';
import { capitalizeFirstLetter } from '$lib/utils/string.utils';
- // Size display removed on dashboard
import { toast } from 'svelte-sonner';
import PruneConfirmationDialog from '$lib/components/dialogs/prune-confirmation-dialog.svelte';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
@@ -31,20 +29,19 @@
import MeterMetric from '$lib/components/meter-metric.svelte';
import DockerIcon from '$lib/icons/docker-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';
+ import type { ContainerSummaryDto } from '$lib/types/container.type';
- let { data }: { data: PageData } = $props();
+ let { data } = $props();
+ let containers = $state(data.containers);
+ let images = $state(data.images);
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
});
@@ -54,7 +51,6 @@
refreshing: false,
pruning: false,
loadingStats: true,
- loadingContainers: false,
loadingDockerInfo: false,
loadingImages: false
});
@@ -70,25 +66,11 @@
containers: [] as Array<{ date: Date; value: number }>
});
- const dockerInfoRef = $derived(dashboardStates.dockerInfo);
- const totalContainers = $derived(
- dockerInfoRef?.containers ?? dashboardStates.containers?.length ?? 0
- );
- const runningContainers = $derived(
- dockerInfoRef?.containersRunning ??
- (dashboardStates.containers
- ? dashboardStates.containers.filter((c: ContainerInfo) => c.State === 'running').length
- : 0)
- );
- const stoppedContainers = $derived(
- dockerInfoRef?.containersStopped ??
- (dashboardStates.containers
- ? dashboardStates.containers.filter((c: ContainerInfo) => c.State !== 'running').length
- : 0)
- );
- const totalImages = $derived(dockerInfoRef?.images ?? dashboardStates.images?.length ?? 0);
+ const runningContainers = $derived(containers.data.filter((s) => s.state === 'running').length);
+ const stoppedContainers = $derived(containers.data.filter((s) => s.state != 'running').length);
+ const totalContainers = $derived(containers.pagination.totalItems);
+ const totalImages = $derived(images.pagination.totalItems);
const currentStats = $derived(dashboardStates.systemStats || liveSystemStats);
- // Size totals removed; only show image count on dashboard
function addToHistoricalData(stats: SystemStats) {
const now = new Date();
@@ -123,70 +105,70 @@
}
}
- 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];
+ function getContainerDisplayName(container: ContainerSummaryDto): 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';
+ 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 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) {
@@ -229,30 +211,12 @@
// Set all loading states to true at start
isLoading.loadingDockerInfo = true;
- isLoading.loadingContainers = true;
isLoading.loadingImages = 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())
- ]);
+ const [dockerInfoResult, settingsResult] = await Promise.allSettled([
+ tryCatch(systemAPI.getDockerInfo()),
+ tryCatch(settingsAPI.getSettings())
+ ]);
// Handle results and clear individual loading states
if (dockerInfoResult.status === 'fulfilled' && !dockerInfoResult.value.error) {
@@ -260,20 +224,6 @@
}
isLoading.loadingDockerInfo = false;
- if (containersResult.status === 'fulfilled' && !containersResult.value.error) {
- const containerData = containersResult.value.data;
- dashboardStates.containers = Array.isArray(containerData)
- ? containerData
- : containerData?.data || [];
- }
- isLoading.loadingContainers = false;
-
- if (imagesResult.status === 'fulfilled' && !imagesResult.value.error) {
- const imageData = imagesResult.value.data;
- dashboardStates.images = Array.isArray(imageData) ? imageData : imageData?.data || [];
- }
- isLoading.loadingImages = false;
-
if (settingsResult.status === 'fulfilled' && !settingsResult.value.error) {
dashboardStates.settings = settingsResult.value.data;
}
@@ -395,17 +345,6 @@
</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}
-
<!-- Quick Actions -->
<section>
<h2 class="mb-3 text-lg font-semibold tracking-tight">Quick Actions</h2>
@@ -511,12 +450,12 @@
title="Running Containers"
icon={Container}
description="Active containers"
- currentValue={isLoading.loadingContainers ? undefined : runningContainers}
+ currentValue={isLoading.loadingStats ? undefined : runningContainers}
formatValue={(v) => v.toString()}
maxValue={Math.max(totalContainers, 1)}
footerText={`${runningContainers} of ${totalContainers} running`}
unit="containers"
- loading={isLoading.loadingContainers}
+ loading={isLoading.loadingStats}
/>
<MeterMetric
@@ -596,14 +535,14 @@
<Card.Content class="p-4">
<div class="flex items-center gap-3">
<div class="rounded-lg bg-green-500/10 p-2">
- {#if isLoading.loadingContainers}
+ {#if isLoading.loadingStats}
<Loader2 class="size-5 text-green-500 animate-spin" />
{:else}
<Box class="size-5 text-green-500" />
{/if}
</div>
<div class="flex-1 min-w-0">
- {#if isLoading.loadingContainers}
+ {#if isLoading.loadingStats}
<div class="space-y-2">
<div class="h-4 w-28 bg-muted animate-pulse rounded"></div>
<div class="h-3 w-20 bg-muted animate-pulse rounded"></div>
@@ -638,7 +577,7 @@
{:else}
<p class="text-sm font-medium">Docker Images</p>
<p class="text-xs text-muted-foreground">
- {dashboardStates.dockerInfo?.images || 0} images
+ {images.pagination.totalItems} images
</p>
{/if}
</div>
@@ -652,19 +591,8 @@
<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}
- total={totalContainers}
- />
- <DashboardImageTable
- images={dashboardStates.images}
- isLoading={isLoading.loadingImages}
- onRefresh={onImageRefresh}
- total={totalImages}
- />
+ <DashboardContainerTable bind:containers isLoading={isLoading.loadingStats} />
+ <DashboardImageTable bind:images isLoading={isLoading.loadingImages} />
</div>
</section>
diff --git a/frontend/src/routes/dashboard/+page.ts b/frontend/src/routes/dashboard/+page.ts
index 109be49fb..669a9eb33 100644
--- a/frontend/src/routes/dashboard/+page.ts
+++ b/frontend/src/routes/dashboard/+page.ts
@@ -19,53 +19,28 @@ export const load: PageLoad = async () => {
limit: 5
},
sort: {
- column: 'Created',
+ column: 'size',
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 containers = await environmentAPI.getContainers(containerRequestOptions);
+ const images = await environmentAPI.getImages(imageRequestOptions);
- 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;
+ const [dockerInfoResult, settingsResult] = await Promise.allSettled([
+ systemAPI.getDockerInfo(),
+ settingsAPI.getSettings()
+ ]);
- 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)
- };
- }
+ const dockerInfo = dockerInfoResult.status === 'fulfilled' ? dockerInfoResult.value : null;
+ const settings = settingsResult.status === 'fulfilled' ? settingsResult.value : null;
+
+ return {
+ dockerInfo,
+ containers,
+ images,
+ settings,
+ containerRequestOptions,
+ imageRequestOptions
+ };
};
diff --git a/frontend/src/routes/dashboard/dash-container-table.svelte b/frontend/src/routes/dashboard/dash-container-table.svelte
index 51ee2eabe..95f927526 100644
--- a/frontend/src/routes/dashboard/dash-container-table.svelte
+++ b/frontend/src/routes/dashboard/dash-container-table.svelte
@@ -1,5 +1,4 @@
<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';
@@ -9,41 +8,23 @@
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;
- }
+ import type { ContainerSummaryDto } from '$lib/types/container.type';
+ import { environmentAPI } from '$lib/services/api';
let {
- containers,
- isLoading,
- onRefresh,
- getContainerDisplayName,
- total = containers.length
+ containers = $bindable(),
+ isLoading
}: {
- containers: ContainerInfo[];
+ containers: Paginated<ContainerSummaryDto>;
isLoading: boolean;
- onRefresh: (options: SearchPaginationSortRequest) => Promise<Paginated<ContainerWithId>>;
- getContainerDisplayName: (container: ContainerInfo) => string;
- total?: number;
} = $props();
+ let selectedIds = $state<string[]>([]);
+
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 rounded-lg border shadow-sm">
@@ -62,19 +43,13 @@
</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}
+ {#if containers.data.length > 0}
<div class="flex h-full flex-col">
<ArcaneTable
- items={paginatedContainers}
+ items={containers}
bind:requestOptions
bind:selectedIds
- {onRefresh}
+ onRefresh={async (options) => (containers = await environmentAPI.getContainers(options))}
withoutSearch={true}
withoutPagination={true}
selectionDisabled={true}
@@ -89,23 +64,27 @@
>
{#snippet rows({ item })}
<Table.Cell class="py-3 md:py-3.5">
- <a class="font-medium hover:underline" href="/containers/{item.Id}/">
- {getContainerDisplayName(item)}
+ <a class="font-medium hover:underline" href="/containers/{item.id}/">
+ {#if item.names && item.names.length > 0}
+ {item.names[0].startsWith('/') ? item.names[0].substring(1) : item.names[0]}
+ {:else}
+ {item.id.substring(0, 12)}
+ {/if}
</a>
</Table.Cell>
- <Table.Cell class="py-3 md:py-3.5" title={item.Image}>
- {truncateString(item.Image, 40)}
+ <Table.Cell>
+ <span class="text-sm">{item.image}</span>
</Table.Cell>
<Table.Cell class="py-3 md:py-3.5">
- {@const stateVariant = statusVariantMap[item.State?.toLowerCase()] || 'red'}
- <StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.State)} />
+ {@const stateVariant = statusVariantMap[item.state.toLowerCase()] || 'grey'}
+ <StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.state)} />
</Table.Cell>
- <Table.Cell class="py-3 md:py-3.5">{item.Status}</Table.Cell>
+ <Table.Cell class="py-3 md:py-3.5">{item.status}</Table.Cell>
{/snippet}
</ArcaneTable>
- {#if containers.length > 5}
+ {#if containers.data.length > 5}
<div class="bg-muted/40 text-muted-foreground border-t px-6 py-2 text-xs">
- Showing 5 of {total} containers
+ Showing 5 of {containers.pagination.totalItems} containers
</div>
{/if}
</div>
diff --git a/frontend/src/routes/dashboard/dash-image-table.svelte b/frontend/src/routes/dashboard/dash-image-table.svelte
index 25c3cc0d7..d9d974d5f 100644
--- a/frontend/src/routes/dashboard/dash-image-table.svelte
+++ b/frontend/src/routes/dashboard/dash-image-table.svelte
@@ -1,5 +1,4 @@
<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';
@@ -7,49 +6,25 @@
import * as Table from '$lib/components/ui/table';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
-
- interface ImageWithId extends EnhancedImageInfo {
- id: string;
- }
+ import type { ImageSummaryDto } from '$lib/types/image.type';
+ import { environmentAPI } from '$lib/services/api';
+ import { formatBytes } from '$lib/utils/bytes.util';
let {
- images,
- isLoading,
- onRefresh,
- total = images.length,
- totalBytes
+ images = $bindable(),
+ isLoading
}: {
- images: EnhancedImageInfo[];
+ images: Paginated<ImageSummaryDto>;
isLoading: boolean;
- onRefresh: (options: SearchPaginationSortRequest) => Promise<Paginated<ImageWithId>>;
- total?: number;
- totalBytes?: number;
} = $props();
let requestOptions = $state<SearchPaginationSortRequest>({
pagination: { page: 1, limit: 5 },
- sort: { column: 'Size', direction: 'desc' }
+ 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
- }
- });
-
// Size display removed on dashboard; keep sorting by size to show largest but do not render sizes
</script>
@@ -71,26 +46,21 @@
</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}
+ {#if images.data.length > 0}
<div class="flex h-full flex-col">
<ArcaneTable
- items={paginatedImages}
+ items={images}
bind:requestOptions
bind:selectedIds
- {onRefresh}
+ onRefresh={async (options) => (images = await environmentAPI.getImages(options))}
withoutSearch={true}
selectionDisabled={true}
withoutPagination={true}
columns={[
- { label: 'Name', sortColumn: 'RepoTags' },
- { label: 'Status', sortColumn: 'InUse' },
- { label: 'Tag', sortColumn: 'tag' }
+ { label: 'Name', sortColumn: 'repoTags' },
+ { label: 'Status', sortColumn: 'inUse' },
+ { label: 'Tag', sortColumn: 'tag' },
+ { label: 'Size', sortColumn: 'size' }
]}
filterPlaceholder="Search images..."
noResultsMessage="No images found"
@@ -99,9 +69,9 @@
<Table.Cell class="py-3 md:py-3.5">
<div class="flex items-center gap-2">
<div class="flex flex-1 items-center">
- <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]}
+ <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}
@@ -110,25 +80,25 @@
</div>
</Table.Cell>
<Table.Cell class="py-3 md:py-3.5">
- {#if item.InUse}
+ {#if item.inUse}
<StatusBadge text="In Use" variant="green" />
{:else}
<StatusBadge text="Unused" variant="amber" />
{/if}
</Table.Cell>
<Table.Cell class="py-3 md:py-3.5">
- {#if item.RepoTags && item.RepoTags.length > 0 && item.RepoTags[0] !== '<none>:<none>'}
- {item.RepoTags[0].split(':')[1] || 'latest'}
+ {#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>
- <!-- Size column removed on dashboard -->
+ <Table.Cell class="py-3 md:py-3.5">{formatBytes(item.size)}</Table.Cell>
{/snippet}
</ArcaneTable>
- {#if images.length > 5}
+ {#if images.data.length > 5}
<div class="bg-muted/40 text-muted-foreground border-t px-6 py-2 text-xs">
- Showing 5 of {total} images
+ Showing 5 of {images.pagination.totalItems} images
</div>
{/if}
</div>
diff --git a/frontend/src/routes/images/+page.svelte b/frontend/src/routes/images/+page.svelte
index 5b63c2027..42dc9ed54 100644
--- a/frontend/src/routes/images/+page.svelte
+++ b/frontend/src/routes/images/+page.svelte
@@ -1,6 +1,4 @@
<script lang="ts">
- import type { PageData } from './$types';
- import type { EnhancedImageInfo } from '$lib/models/image.type';
import { Button } from '$lib/components/ui/button/index.js';
import { AlertCircle, HardDrive, Loader2, Package } from '@lucide/svelte';
import * as Alert from '$lib/components/ui/alert/index.js';
@@ -15,17 +13,15 @@
import { environmentAPI, imageUpdateAPI } from '$lib/services/api';
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 { data } = $props();
+
+ let images = $state(data.images);
+ let requestOptions = $state(data.imageRequestOptions);
- 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(false);
- let requestOptions = $state<SearchPaginationSortRequest>(data.imageRequestOptions);
let isLoading = $state({
pulling: false,
@@ -37,38 +33,6 @@
let isPullDialogOpen = $state(false);
let isConfirmPruneDialogOpen = $state(false);
- async function loadImages() {
- try {
- isLoadingImages = true;
- 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);
- error = err instanceof Error ? err.message : 'Failed to load images';
- images = [];
- } finally {
- isLoadingImages = false;
- }
- }
-
- async function refreshImages() {
- isLoading.refreshing = true;
- try {
- await loadImages();
- } catch (error) {
- console.error('Failed to refresh images:', error);
- toast.error('Failed to refresh images');
- } finally {
- isLoading.refreshing = false;
- }
- }
-
async function handlePruneImages() {
isLoading.pruning = true;
handleApiResultWithCallbacks({
@@ -77,7 +41,7 @@
setLoadingState: (value) => (isLoading.pruning = value),
onSuccess: async () => {
toast.success('Images Pruned Successfully');
- await loadImages();
+ images = await environmentAPI.getImages(requestOptions);
isConfirmPruneDialogOpen = false;
}
});
@@ -86,10 +50,10 @@
async function handleTriggerBulkUpdateCheck() {
isLoading.checking = true;
try {
- const imageRefs = images.map((img) => img.RepoTags?.[0] || `image:${img.Id}`);
+ const imageRefs = images.data.map((img) => img.repoTags?.[0] || `image:${img.id}`);
await imageUpdateAPI.checkMultipleImages(imageRefs);
toast.success('Update check completed');
- await loadImages();
+ images = await environmentAPI.getImages(requestOptions);
} catch (error) {
console.error('Failed to check for updates:', error);
toast.error('Failed to check for updates');
@@ -98,18 +62,16 @@
}
}
- async function onRefresh(options: SearchPaginationSortRequest) {
- requestOptions = options;
- await loadImages();
- return {
- data: images,
- pagination: {
- totalPages: Math.ceil(images.length / (requestOptions.pagination?.limit || 20)),
- totalItems: images.length,
- currentPage: requestOptions.pagination?.page || 1,
- itemsPerPage: requestOptions.pagination?.limit || 20
+ async function refreshImages() {
+ isLoading.refreshing = true;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.getImages(requestOptions)),
+ message: 'Failed to Refresh Containers for Updates',
+ setLoadingState: (value) => (isLoading.refreshing = value),
+ async onSuccess(newImages) {
+ images = newImages;
}
- };
+ });
}
</script>
@@ -171,7 +133,7 @@
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
<StatCard
title="Total Images"
- value={data.dockerInfo.images}
+ value={images.pagination.totalItems}
icon={HardDrive}
iconColor="text-blue-500"
class="border-l-4 border-l-blue-500"
@@ -186,16 +148,17 @@
</div>
<ImageTable
- {images}
+ bind:images
bind:selectedIds
- {requestOptions}
- {onRefresh}
- onImagesChanged={loadImages}
+ bind:requestOptions
onPullDialogOpen={() => (isPullDialogOpen = true)}
onTriggerBulkUpdateCheck={handleTriggerBulkUpdateCheck}
/>
- <ImagePullSheet bind:open={isPullDialogOpen} onPullFinished={() => loadImages()} />
+ <ImagePullSheet
+ bind:open={isPullDialogOpen}
+ onPullFinished={async () => (images = await environmentAPI.getImages(requestOptions))}
+ />
<Dialog.Root bind:open={isConfirmPruneDialogOpen}>
<Dialog.Content>
diff --git a/frontend/src/routes/images/+page.ts b/frontend/src/routes/images/+page.ts
index 171443896..6ff21581b 100644
--- a/frontend/src/routes/images/+page.ts
+++ b/frontend/src/routes/images/+page.ts
@@ -9,20 +9,13 @@ export const load: PageLoad = async () => {
limit: 20
},
sort: {
- column: 'Created',
+ column: 'created',
direction: 'desc' as const
}
};
- const dockerInfo = await systemAPI.getDockerInfo();
const totalSize = await environmentAPI.getTotalImageSize();
+ const images = await environmentAPI.getImages(imageRequestOptions);
- const images = await environmentAPI.getImages(
- imageRequestOptions.pagination,
- imageRequestOptions.sort,
- imageRequestOptions.search,
- imageRequestOptions.filters
- );
-
- return { dockerInfo, totalSize, images, imageRequestOptions };
+ return { totalSize, images, imageRequestOptions };
};
diff --git a/frontend/src/routes/images/image-table.svelte b/frontend/src/routes/images/image-table.svelte
index 84da2a9df..c919f0ea0 100644
--- a/frontend/src/routes/images/image-table.svelte
+++ b/frontend/src/routes/images/image-table.svelte
@@ -1,5 +1,4 @@
<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, Ellipsis, ScanSearch } from '@lucide/svelte';
@@ -18,25 +17,18 @@
import { environmentAPI } from '$lib/services/api';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
import FilterDropdown from '$lib/components/dropdowns/filter-dropdown.svelte';
-
- interface ImageWithId extends EnhancedImageInfo {
- id: string;
- }
+ import type { ImageSummaryDto } from '$lib/types/image.type';
let {
- images,
+ images = $bindable(),
selectedIds = $bindable(),
requestOptions = $bindable(),
- onRefresh,
- onImagesChanged,
onPullDialogOpen,
onTriggerBulkUpdateCheck
}: {
- images: EnhancedImageInfo[];
+ images: Paginated<ImageSummaryDto>;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
- onRefresh: (options: SearchPaginationSortRequest) => Promise<any>;
- onImagesChanged: () => Promise<void>;
onPullDialogOpen: () => void;
onTriggerBulkUpdateCheck: () => Promise<void>;
} = $props();
@@ -55,18 +47,12 @@
let isPullingInline = $state<Record<string, boolean>>({});
- const imagesWithId = $derived(
- images.map((img) => ({
- ...img,
- id: img.Id
- }))
- );
-
- const filteredImages = $derived(
- imagesWithId.filter((img) => {
+ const filteredImages: Paginated<ImageSummaryDto> = $derived({
+ ...images,
+ data: images.data.filter((img) => {
// Usage filtering
- const showBecauseUsed = imageFilters.showUsed && img.InUse;
- const showBecauseUnused = imageFilters.showUnused && !img.InUse;
+ const showBecauseUsed = imageFilters.showUsed && img.inUse;
+ const showBecauseUnused = imageFilters.showUnused && !img.inUse;
const usageMatch = showBecauseUsed || showBecauseUnused;
// Update status filtering
@@ -77,7 +63,7 @@
return usageMatch && updateMatch;
})
- );
+ });
function getImageUpdateStatus(updateInfo: any): 'has-updates' | 'no-updates' {
if (!updateInfo) return 'no-updates';
@@ -87,16 +73,6 @@
return updateInfo.hasUpdate === true ? 'has-updates' : 'no-updates';
}
- 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 deleteImage(id: string) {
openConfirmDialog({
title: 'Remove Image',
@@ -114,7 +90,7 @@
setLoadingState: () => {},
onSuccess: async () => {
toast.success('Image removed successfully');
- await onImagesChanged();
+ images = await environmentAPI.getImages(requestOptions);
}
});
@@ -160,7 +136,7 @@
toast.success(
`Successfully removed ${successCount} image${successCount > 1 ? 's' : ''}`
);
- await onImagesChanged();
+ images = await environmentAPI.getImages(requestOptions);
}
if (failureCount > 0) {
@@ -188,7 +164,7 @@
setLoadingState: () => {},
onSuccess: async () => {
toast.success(`Successfully pulled ${repoTag}`);
- await onImagesChanged();
+ images = await environmentAPI.getImages(requestOptions);
}
});
@@ -220,7 +196,7 @@
}
</script>
-{#if images.length > 0}
+{#if images.data.length > 0}
<Card.Root class="border shadow-sm">
<Card.Header class="px-6">
<div class="flex items-center justify-between">
@@ -289,18 +265,18 @@
</div>
</Card.Header>
<Card.Content>
- {#if filteredImages.length > 0}
+ {#if filteredImages.data.length > 0}
<ArcaneTable
- items={paginatedImages}
+ items={filteredImages}
bind:requestOptions
bind:selectedIds
- {onRefresh}
+ onRefresh={async (options) => (images = await environmentAPI.getImages(options))}
columns={[
- { label: 'Repository', sortColumn: 'RepoTags' },
+ { label: 'Repository', sortColumn: 'repoTags' },
{ label: 'Image ID' },
- { label: 'Size', sortColumn: 'Size' },
- { label: 'Created', sortColumn: 'Created' },
- { label: 'Status', sortColumn: 'InUse' },
+ { label: 'Size', sortColumn: 'size' },
+ { label: 'Created', sortColumn: 'created' },
+ { label: 'Status', sortColumn: 'inUse' },
{ label: 'Updates' },
{ label: ' ' }
]}
@@ -308,11 +284,11 @@
noResultsMessage="No images found"
>
{#snippet rows({ item })}
- {@const { repo, tag } = extractRepoAndTag(item.RepoTags)}
+ {@const { repo, tag } = extractRepoAndTag(item.repoTags)}
<Table.Cell>
- {#if item.RepoTags && item.RepoTags.length > 0 && item.RepoTags[0] !== '<none>:<none>'}
- <a class="font-medium hover:underline" href="/images/{item.Id}/"
- >{item.RepoTags[0]}</a
+ {#if item.repoTags && item.repoTags.length > 0 && item.repoTags[0] !== '<none>:<none>'}
+ <a class="font-medium hover:underline" href="/images/{item.id}/"
+ >{item.repoTags[0]}</a
>
{:else}
<span class="text-muted-foreground italic">Untagged</span>
@@ -320,22 +296,20 @@
</Table.Cell>
<Table.Cell>
<code class="bg-muted rounded px-2 py-1 text-xs"
- >{item.Id?.substring(7, 19) || 'N/A'}</code
+ >{item.id?.substring(7, 19) || 'N/A'}</code
>
</Table.Cell>
- <Table.Cell class="py-3 md:py-3.5"
- >{formatBytes(item.Size ?? item.VirtualSize ?? 0)}</Table.Cell
- >
- <Table.Cell>{new Date((item.Created || 0) * 1000).toLocaleDateString()}</Table.Cell>
+ <Table.Cell class="py-3 md:py-3.5">{formatBytes(item.size)}</Table.Cell>
+ <Table.Cell>{new Date((item.created || 0) * 1000).toLocaleDateString()}</Table.Cell>
<Table.Cell>
- {#if item.InUse}
+ {#if item.inUse}
<StatusBadge text="In Use" variant="green" />
{:else}
<StatusBadge text="Unused" variant="amber" />
{/if}
</Table.Cell>
<Table.Cell>
- <ImageUpdateItem updateInfo={item.updateInfo} imageId={item.Id} {repo} {tag} />
+ <ImageUpdateItem updateInfo={item.updateInfo} imageId={item.id} {repo} {tag} />
</Table.Cell>
<Table.Cell>
<DropdownMenu.Root>
@@ -349,15 +323,15 @@
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
- <DropdownMenu.Item onclick={() => goto(`/images/${item.Id}`)}>
+ <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]}
+ onclick={() => handleInlineImagePull(item.id, item.repoTags?.[0] || '')}
+ disabled={isPullingInline[item.id] || !item.repoTags?.[0]}
>
- {#if isPullingInline[item.Id]}
+ {#if isPullingInline[item.id]}
<Loader2 class="size-4 animate-spin" />
Pulling...
{:else}
@@ -368,7 +342,7 @@
<DropdownMenu.Separator />
<DropdownMenu.Item
variant="destructive"
- onclick={() => deleteImage(item.Id)}
+ onclick={() => deleteImage(item.id)}
disabled={isLoading.removing}
>
{#if isLoading.removing}