Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: dashboard overview card arrangement (#215)
Kyle Mendellda87f3b7eb8e
diff --git a/src/lib/components/dropdown-card.svelte b/src/lib/components/dropdown-card.sveltenew file mode 100644index 000000000..17cb973b4--- /dev/null+++ b/src/lib/components/dropdown-card.svelte@@ -0,0 +1,77 @@+<script lang="ts">+ import { cn } from '$lib/utils';+ import { LucideChevronDown, type Icon as IconType } from '@lucide/svelte';+ import { onMount, type Snippet } from 'svelte';+ import { slide } from 'svelte/transition';+ import { Button } from './ui/button';+ import * as Card from './ui/card';++ let {+ id,+ title,+ description,+ defaultExpanded = false,+ icon,+ children+ }: {+ id: string;+ title: string;+ description?: string;+ defaultExpanded?: boolean;+ icon?: typeof IconType;+ children: Snippet;+ } = $props();++ let expanded = $state(defaultExpanded);++ function loadExpandedState() {+ const state = JSON.parse(localStorage.getItem('collapsible-cards-expanded') || '{}');+ expanded = state[id] || false;+ }++ function saveExpandedState() {+ const state = JSON.parse(localStorage.getItem('collapsible-cards-expanded') || '{}');+ state[id] = expanded;+ localStorage.setItem('collapsible-cards-expanded', JSON.stringify(state));+ }++ function toggleExpanded() {+ expanded = !expanded;+ saveExpandedState();+ }++ onMount(() => {+ if (defaultExpanded) {+ saveExpandedState();+ }+ loadExpandedState();+ });+</script>++<Card.Root>+ <Card.Header class="cursor-pointer p-5" onclick={toggleExpanded}>+ <div class="flex items-center justify-between">+ <div>+ <Card.Title class="flex items-center gap-2 text-xl font-semibold mb-2">+ {#if icon}{@const Icon = icon}+ <Icon class="text-primary/80 h-5 w-5" />+ {/if}+ {title}+ </Card.Title>+ {#if description}+ <Card.Description class="mt-1">{description}</Card.Description>+ {/if}+ </div>+ <Button class="ml-10 h-8 p-3" variant="ghost" aria-label="Expand Card">+ <LucideChevronDown class={cn('h-5 w-5 transition-transform duration-200', expanded && 'rotate-180 transform')} />+ </Button>+ </div>+ </Card.Header>+ {#if expanded}+ <div transition:slide={{ duration: 200 }}>+ <Card.Content class="bg-muted/20 pt-5">+ {@render children()}+ </Card.Content>+ </div>+ {/if}+</Card.Root>diff --git a/src/lib/components/navbar.svelte b/src/lib/components/navbar.svelteindex d41007e77..4b6f4afe5 100644--- a/src/lib/components/navbar.svelte+++ b/src/lib/components/navbar.svelte@@ -1,7 +1,7 @@<script lang="ts">- import { Home, Box, Image, Network, HardDrive, Settings, Menu, X, ChevronRight, ChevronLeft, FileStack, ExternalLink, LogOut, Sun, Moon, type Icon as IconType } from '@lucide/svelte';+ import { Home, Box, Image, Network, HardDrive, Settings, Menu, X, ChevronRight, ChevronLeft, FileStack, ExternalLink, LogOut, Sun, Moon, ChevronDown, UserIcon, Shield, Bell, Palette, Database, type Icon as IconType, ShieldCheck } from '@lucide/svelte';import { page } from '$app/state';- import { fly } from 'svelte/transition';+ import { fly, slide } from 'svelte/transition';import { Button } from '$lib/components/ui/button/index.js';import { Separator } from '$lib/components/ui/separator/index.js';import { cn } from '$lib/utils';@@ -10,6 +10,19 @@import type { AppVersionInformation } from '$lib/types/application-configuration';import type { User } from '$lib/types/user.type';+ type SubMenuItem = {+ href: string;+ label: string;+ icon: typeof IconType;+ };++ type MenuItem = {+ href?: string;+ label: string;+ icon: typeof IconType;+ children?: SubMenuItem[];+ };+let {items = [{ href: '/', label: 'Dashboard', icon: Home },@@ -18,7 +31,19 @@{ href: '/images', label: 'Images', icon: Image },{ href: '/networks', label: 'Networks', icon: Network },{ href: '/volumes', label: 'Volumes', icon: HardDrive },- { href: '/settings', label: 'Settings', icon: Settings }+ {+ label: 'Settings',+ icon: Settings,+ children: [+ { href: '/settings/general', label: 'General', icon: Settings },+ { href: '/settings/docker', label: 'Docker', icon: Database },+ { href: '/settings/users', label: 'Users', icon: UserIcon },+ // { href: '/settings/rbac', label: 'RBAC', icon: ShieldCheck },+ { href: '/settings/security', label: 'Security', icon: Shield }+ // { href: '/settings/notifications', label: 'Notifications', icon: Bell },+ // { href: '/settings/appearance', label: 'Appearance', icon: Palette }+ ]+ }] as MenuItem[],versionInformation,user@@ -28,18 +53,22 @@user?: User | null;}>();- type MenuItem = {- href: string;- label: string;- icon: typeof IconType;- };-let isOpen = $state(false);let isCollapsed = $state(false);+ let expandedSections = $state<Set<string>>(new Set());if (browser) {const savedState = localStorage.getItem('sidebarCollapsed');isCollapsed = savedState === 'true';++ const savedExpanded = localStorage.getItem('expandedSections');+ if (savedExpanded) {+ try {+ expandedSections = new Set(JSON.parse(savedExpanded));+ } catch (e) {+ expandedSections = new Set();+ }+ }}function toggleCollapse() {@@ -49,161 +78,278 @@}}+ function toggleSection(label: string) {+ if (expandedSections.has(label)) {+ expandedSections.delete(label);+ } else {+ expandedSections.add(label);+ }+ expandedSections = new Set(expandedSections);++ if (browser) {+ localStorage.setItem('expandedSections', JSON.stringify([...expandedSections]));+ }+ }++ function isActiveItem(href: string): boolean {+ return page.url.pathname === href || (page.url.pathname.startsWith(href) && href !== '/');+ }++ function isActiveSection(children: SubMenuItem[]): boolean {+ return children.some((child) => isActiveItem(child.href));+ }+const updateAvailable = $derived(versionInformation?.updateAvailable);</script>-<!-- Mobile menu button - Enhanced with better positioning and shadow -->-<Button variant="ghost" size="icon" class="md:hidden fixed top-4 right-4 z-50 shadow-md bg-background/95 backdrop-blur-sm border" onclick={() => (isOpen = !isOpen)} aria-label={isOpen ? 'Close menu' : 'Open menu'}>+<!-- Mobile menu button - Modern floating design -->+<Button variant="ghost" size="icon" class="md:hidden fixed top-4 right-4 z-50 h-11 w-11 rounded-xl shadow-lg bg-background/80 backdrop-blur-xl border border-border/50 hover:shadow-xl hover:scale-105 transition-all duration-200" onclick={() => (isOpen = !isOpen)} aria-label={isOpen ? 'Close menu' : 'Open menu'}>{#if isOpen}- <X size={18} />+ <X size={20} class="transition-transform duration-200" />{:else}- <Menu size={18} />+ <Menu size={20} class="transition-transform duration-200" />{/if}</Button>-<!-- Main sidebar container - Enhanced with smoother transitions and better shadows -->-<div class={cn('fixed md:sticky top-0 left-0 h-screen md:h-dvh transition-all duration-300 ease-in-out', 'bg-card border-r shadow-md z-40', 'flex flex-col', isCollapsed ? 'w-[70px]' : 'w-64', isOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0')}>- <!-- Logo header - Enhanced spacing and alignment -->- <div class={cn('flex items-center h-16 transition-all duration-300', isCollapsed ? 'justify-center px-2' : 'gap-3 px-5')}>- <div class="shrink-0 flex items-center justify-center">- <img src="/img/arcane.svg" alt="Arcane" class={cn('transition-all duration-300', isCollapsed ? 'size-15' : 'size-15')} width={isCollapsed ? '24' : '28'} height={isCollapsed ? '24' : '28'} />+<!-- Main sidebar container - Modern glassmorphism design -->+<div class={cn('fixed md:sticky top-0 left-0 h-screen md:h-dvh transition-all duration-300 ease-out', 'bg-gradient-to-b from-card/95 to-background/90 backdrop-blur-xl border-r border-border/40 shadow-2xl z-40 flex flex-col', isCollapsed ? 'w-[70px]' : 'w-64', isOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0')}>+ <!-- Logo header - Enhanced with subtle glow effect -->+ <div class={cn('flex items-center h-16 transition-all duration-300 border-b border-border/30', isCollapsed ? 'justify-center px-2' : 'gap-3 px-6')}>+ <div class="shrink-0 flex items-center justify-center relative">+ <img src="/img/arcane.svg" alt="Arcane" class="size-8 transition-all duration-300 drop-shadow-sm" width="32" height="32" />+ <div class="absolute inset-0 bg-primary/10 rounded-full blur-xl opacity-60"></div></div>{#if !isCollapsed}- <div class="flex flex-col justify-center">- <span class="text-lg font-bold tracking-tight leading-none">Arcane</span>- <span class="text-xs text-muted-foreground">v{versionInformation?.currentVersion}</span>+ <div class="flex flex-col justify-center min-w-0">+ <span class="text-lg font-bold tracking-tight leading-none bg-gradient-to-r from-foreground to-foreground/80 bg-clip-text"> Arcane </span>+ <span class="text-xs text-muted-foreground/80 font-medium">+ v{versionInformation?.currentVersion}+ </span></div>{/if}</div>- <Separator />+ <Separator class="opacity-30" />- <!-- Collapse toggle button - Enhanced positioning and animation -->- <div class="hidden md:flex justify-end px-2 -mt-[9px] mb-1.5 relative">- <Button variant="outline" size="icon" class="rounded-full bg-background/95 backdrop-blur-sm absolute right-0 translate-x-1/2 size-[22px] shadow-sm border transition-transform duration-300 hover:scale-110" onclick={toggleCollapse} aria-label={isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'}>+ <!-- Collapse toggle button - Modern floating design -->+ <div class="hidden md:flex justify-end px-3 -mt-[11px] mb-2 relative">+ <Button variant="outline" size="icon" class="rounded-full bg-background/90 backdrop-blur-sm absolute right-0 translate-x-1/2 h-6 w-6 shadow-md border border-border/50 transition-all duration-200 hover:scale-110 hover:shadow-lg" onclick={toggleCollapse} aria-label={isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'}>{#if isCollapsed}- <ChevronRight size={12} />+ <ChevronRight size={14} class="transition-transform duration-200" />{:else}- <ChevronLeft size={12} />+ <ChevronLeft size={14} class="transition-transform duration-200" />{/if}</Button></div>- <!-- Navigation menu - Enhanced with better spacing and transitions -->- <nav class={cn('p-2 flex-1 overflow-y-auto overflow-x-hidden custom-scrollbar', isCollapsed && 'py-2 px-1')}>- {#each items as item (item.href)}- {@const isActive = page.url.pathname === item.href || (page.url.pathname.startsWith(item.href) && item.href !== '/')}- {@const Icon = item.icon}-- <a- href={item.href}- class={cn('flex items-center justify-between rounded-lg text-sm font-medium', isCollapsed ? 'px-2 py-3 my-1 flex-col gap-1' : 'px-3 py-2.5 my-0.5', 'transition-all duration-200 group', isActive ? 'bg-primary/12 text-primary shadow-sm' : 'text-muted-foreground hover:bg-muted/70 hover:text-foreground')}- aria-current={isActive ? 'page' : undefined}- title={isCollapsed ? item.label : undefined}- >- <div class={cn('flex items-center', isCollapsed ? 'justify-center' : 'gap-3')}>- <div class={cn('p-1.5 rounded-md transition-colors duration-200', isActive ? 'bg-primary/15' : 'bg-transparent group-hover:bg-muted-foreground/10')}>- <Icon size={16} class={cn('transition-colors duration-200', isActive ? 'text-primary' : 'text-muted-foreground group-hover:text-foreground')} />- </div>- {#if !isCollapsed}- <span class="truncate">{item.label}</span>+ <!-- Navigation menu - Enhanced with modern card-like styling -->+ <nav class={cn('flex-1 overflow-y-auto overflow-x-hidden modern-scrollbar', isCollapsed ? 'py-4 px-2' : 'py-4 px-4')}>+ {#each items as item (item.label)}+ {#if item.children}+ <!-- Dropdown section -->+ {@const isExpanded = expandedSections.has(item.label)}+ {@const hasActiveChild = isActiveSection(item.children)}+ {@const Icon = item.icon}++ <div class="mb-1">+ {#if isCollapsed}+ <!-- Collapsed state - show tooltip with children -->+ <button+ class={cn(+ 'flex items-center justify-center rounded-xl p-3 text-sm font-medium transition-all duration-200 group w-full',+ 'hover:shadow-md hover:scale-[1.02] active:scale-[0.98]',+ hasActiveChild ? 'bg-gradient-to-br from-primary/15 to-primary/10 text-primary shadow-sm ring-1 ring-primary/20' : 'text-muted-foreground hover:bg-gradient-to-br hover:from-muted/80 hover:to-muted/60 hover:text-foreground'+ )}+ title={`${item.label} (${item.children.length} items)`}+ onclick={() => toggleSection(item.label)}+ >+ <div class={cn('p-1.5 rounded-lg transition-all duration-200', hasActiveChild ? 'bg-primary/20 shadow-sm' : 'bg-transparent group-hover:bg-muted-foreground/10')}>+ <Icon size={16} class={cn('transition-colors duration-200', hasActiveChild ? 'text-primary' : 'text-muted-foreground group-hover:text-foreground')} />+ </div>+ </button>+ {:else}+ <!-- Expanded state - full dropdown -->+ <button+ class={cn(+ 'flex items-center justify-between rounded-xl px-3 py-2.5 text-sm font-medium transition-all duration-200 group w-full',+ 'hover:shadow-md hover:scale-[1.02] active:scale-[0.98]',+ hasActiveChild || isExpanded ? 'bg-gradient-to-br from-primary/15 to-primary/10 text-primary shadow-sm ring-1 ring-primary/20' : 'text-muted-foreground hover:bg-gradient-to-br hover:from-muted/80 hover:to-muted/60 hover:text-foreground'+ )}+ onclick={() => toggleSection(item.label)}+ >+ <div class="flex items-center gap-3">+ <div class={cn('p-1.5 rounded-lg transition-all duration-200', hasActiveChild || isExpanded ? 'bg-primary/20 shadow-sm' : 'bg-transparent group-hover:bg-muted-foreground/10')}>+ <Icon size={16} class={cn('transition-colors duration-200', hasActiveChild || isExpanded ? 'text-primary' : 'text-muted-foreground group-hover:text-foreground')} />+ </div>+ <span class="truncate font-medium">{item.label}</span>+ </div>+ <ChevronDown size={14} class={cn('transition-transform duration-200', isExpanded ? 'rotate-180' : '', hasActiveChild || isExpanded ? 'text-primary/70' : 'text-muted-foreground/70')} />+ </button>++ <!-- Dropdown content -->+ {#if isExpanded}+ <div class="mt-1 ml-3 border-l-2 border-border/30 pl-3 space-y-1" transition:slide={{ duration: 200 }}>+ {#each item.children as child (child.href)}+ {@const isActive = isActiveItem(child.href)}+ {@const ChildIcon = child.icon}++ <a+ href={child.href}+ class={cn('flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200', 'hover:scale-[1.01] active:scale-[0.99]', isActive ? 'bg-gradient-to-r from-primary/20 to-primary/10 text-primary shadow-sm border border-primary/20' : 'text-muted-foreground hover:bg-gradient-to-r hover:from-muted/60 hover:to-muted/40 hover:text-foreground')}+ aria-current={isActive ? 'page' : undefined}+ >+ <div class={cn('p-1 rounded-md transition-all duration-200', isActive ? 'bg-primary/30' : 'bg-transparent')}>+ <ChildIcon size={14} class="transition-colors duration-200" />+ </div>+ <span class="truncate">{child.label}</span>+ {#if isActive}+ <div class="ml-auto w-1.5 h-1.5 rounded-full bg-primary"></div>+ {/if}+ </a>+ {/each}+ </div>+ {/if}{/if}</div>+ {:else}+ <!-- Regular menu item -->+ {@const isActive = item.href ? isActiveItem(item.href) : false}+ {@const Icon = item.icon}- {#if !isCollapsed && isActive}- <ChevronRight size={14} class="text-primary opacity-70" />- {/if}- </a>+ <a+ href={item.href}+ class={cn(+ 'flex items-center justify-between rounded-xl text-sm font-medium mb-1 transition-all duration-200 group',+ 'hover:shadow-md hover:scale-[1.02] active:scale-[0.98]',+ isCollapsed ? 'px-2 py-3 flex-col gap-1' : 'px-3 py-2.5',+ isActive ? 'bg-gradient-to-br from-primary/15 to-primary/10 text-primary shadow-sm ring-1 ring-primary/20' : 'text-muted-foreground hover:bg-gradient-to-br hover:from-muted/80 hover:to-muted/60 hover:text-foreground'+ )}+ aria-current={isActive ? 'page' : undefined}+ title={isCollapsed ? item.label : undefined}+ >+ <div class={cn('flex items-center', isCollapsed ? 'justify-center' : 'gap-3')}>+ <div class={cn('p-1.5 rounded-lg transition-all duration-200', isActive ? 'bg-primary/20 shadow-sm' : 'bg-transparent group-hover:bg-muted-foreground/10')}>+ <Icon size={16} class={cn('transition-colors duration-200', isActive ? 'text-primary' : 'text-muted-foreground group-hover:text-foreground')} />+ </div>+ {#if !isCollapsed}+ <span class="truncate font-medium">{item.label}</span>+ {/if}+ </div>++ {#if !isCollapsed && isActive}+ <ChevronRight size={14} class="text-primary/70 transition-transform duration-200" />+ {/if}+ </a>+ {/if}{/each}</nav>- <!-- Update notification - Enhanced with better visibility -->+ <!-- Update notification - Modern card design with enhanced styling -->{#if updateAvailable}- <Separator />+ <div class="px-4 pb-2">+ <Separator class="mb-3 opacity-30" />- <div class={cn('transition-all px-3 py-3', isCollapsed ? 'text-center' : '', 'bg-blue-500/10 dark:bg-blue-500/5 my-1 mx-2 rounded-md')}>- {#if !isCollapsed}- <a href={versionInformation.releaseUrl} target="_blank" rel="noopener noreferrer" class="flex items-center justify-between text-blue-600 dark:text-blue-400 hover:underline text-sm font-medium">- <span>Update available</span>- <span class="flex items-center">- v{versionInformation.newestVersion}- <ExternalLink class="ml-1 size-3.5" />- </span>- </a>- {:else}- <a href={versionInformation.releaseUrl} target="_blank" rel="noopener noreferrer" title="Update available: v{versionInformation.newestVersion}" class="flex justify-center text-blue-600 dark:text-blue-400">- <ExternalLink class="size-4" />- </a>- {/if}+ <div class={cn('transition-all rounded-xl p-3 bg-gradient-to-br from-blue-500/10 to-blue-600/5 border border-blue-500/20', 'hover:shadow-md hover:scale-[1.02] hover:from-blue-500/15 hover:to-blue-600/10', isCollapsed ? 'text-center' : '')}>+ {#if !isCollapsed}+ <a href={versionInformation?.releaseUrl} target="_blank" rel="noopener noreferrer" class="flex items-center justify-between text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 transition-colors duration-200 group">+ <div class="flex flex-col gap-1">+ <span class="text-sm font-semibold">Update available</span>+ <span class="text-xs text-blue-500/80">v{versionInformation?.newestVersion}</span>+ </div>+ <ExternalLink size={16} class="transition-transform duration-200 group-hover:scale-110" />+ </a>+ {:else}+ <a href={versionInformation?.releaseUrl} target="_blank" rel="noopener noreferrer" title="Update available: v{versionInformation?.newestVersion}" class="flex justify-center text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 transition-all duration-200 hover:scale-110">+ <ExternalLink size={18} />+ </a>+ {/if}+ </div></div>{/if}- <!-- User controls section - Enhanced with better spacing and hover effects -->- <div class="mt-auto p-2">- <Separator class="mb-2" />-+ <!-- User controls section - Modern design with enhanced spacing -->+ <div class="mt-auto p-4 border-t border-border/30">{#if user && user.displayName && !isCollapsed}- <div class="px-3 py-2.5 text-sm font-medium text-muted-foreground truncate flex items-center gap-2" title={user.displayName}>- <div class="size-6 rounded-full bg-primary/15 text-primary flex items-center justify-center">+ <div class="px-3 py-2.5 mb-3 text-sm font-medium text-foreground truncate flex items-center gap-3 rounded-xl bg-gradient-to-br from-muted/50 to-muted/30 transition-all duration-200" title={user.displayName}>+ <div class="h-8 w-8 rounded-full bg-gradient-to-br from-primary/20 to-primary/10 text-primary flex items-center justify-center text-sm font-semibold border border-primary/20">{user.displayName.charAt(0).toUpperCase()}</div>- <span class="truncate">{user.displayName}</span>+ <span class="truncate font-medium">{user.displayName}</span></div>{/if}- <!-- Theme toggle button - Enhanced with better hover effects -->- <Button variant="ghost" class={cn('w-full flex items-center text-sm font-medium transition-colors text-muted-foreground hover:bg-muted hover:text-foreground rounded-lg', isCollapsed ? 'justify-center px-2 py-3' : 'justify-start gap-3 px-3 py-2.5')} title={isCollapsed ? 'Toggle theme' : 'Toggle theme'} onclick={toggleMode}>- <div class={cn('p-1 rounded-md transition-colors', 'bg-transparent group-hover:bg-muted-foreground/10')}>+ <!-- Theme toggle button - Enhanced with modern styling -->+ <Button+ variant="ghost"+ class={cn('w-full flex items-center text-sm font-medium transition-all duration-200 text-muted-foreground hover:bg-gradient-to-br hover:from-muted/80 hover:to-muted/60 hover:text-foreground rounded-xl mb-1', 'hover:shadow-md hover:scale-[1.02] active:scale-[0.98]', isCollapsed ? 'justify-center px-2 py-3 h-11' : 'justify-start gap-3 px-3 py-2.5 h-11')}+ title={isCollapsed ? 'Toggle theme' : undefined}+ onclick={toggleMode}+ >+ <div class="p-1 rounded-lg transition-colors duration-200 bg-transparent group-hover:bg-muted-foreground/10">{#if mode.current === 'dark'}- <Sun size={16} />+ <Sun size={16} class="transition-transform duration-200" />{:else}- <Moon size={16} />+ <Moon size={16} class="transition-transform duration-200" />{/if}</div>{#if !isCollapsed}- <span>Toggle theme</span>+ <span class="font-medium">Toggle theme</span>{/if}</Button>- <!-- Logout button - Enhanced with better hover effects -->+ <!-- Logout button - Enhanced with modern styling and hover effects --><form action="/auth/logout" method="POST">- <Button variant="ghost" class={cn('w-full flex items-center text-sm font-medium transition-colors text-muted-foreground hover:bg-muted hover:text-foreground rounded-lg', isCollapsed ? 'justify-center px-2 py-3' : 'justify-start gap-3 px-3 py-2.5')} title={isCollapsed ? 'Logout' : undefined} type="submit">- <div class={cn('p-1 rounded-md transition-colors', 'bg-transparent group-hover:bg-muted-foreground/10')}>- <LogOut size={16} />+ <Button+ variant="ghost"+ class={cn('w-full flex items-center text-sm font-medium transition-all duration-200 text-muted-foreground rounded-xl', 'hover:bg-gradient-to-br hover:from-destructive/10 hover:to-destructive/5 hover:text-destructive hover:shadow-md hover:scale-[1.02] active:scale-[0.98]', isCollapsed ? 'justify-center px-2 py-3 h-11' : 'justify-start gap-3 px-3 py-2.5 h-11')}+ title={isCollapsed ? 'Logout' : undefined}+ type="submit"+ >+ <div class="p-1 rounded-lg transition-colors duration-200 bg-transparent group-hover:bg-destructive/10">+ <LogOut size={16} class="transition-transform duration-200" /></div>{#if !isCollapsed}- <span>Logout</span>+ <span class="font-medium">Logout</span>{/if}</Button></form></div></div>-<!-- Mobile backdrop - Enhanced with smoother blur effect -->+<!-- Mobile backdrop - Enhanced with better blur and transition -->{#if isOpen}- <button type="button" class="md:hidden fixed inset-0 w-full h-full bg-background/60 backdrop-blur-sm z-30 border-none" aria-label="Close menu" onclick={() => (isOpen = false)} transition:fly={{ duration: 200, y: -5 }}></button>+ <button type="button" class="md:hidden fixed inset-0 w-full h-full bg-background/60 backdrop-blur-md z-30 border-none cursor-pointer" aria-label="Close menu" onclick={() => (isOpen = false)} transition:fly={{ duration: 250, opacity: 0 }}></button>{/if}<style>- .custom-scrollbar {+ .modern-scrollbar {scrollbar-width: thin;- scrollbar-color: var(--scrollbar-thumb) transparent;+ scrollbar-color: hsl(var(--border)) transparent;}- .custom-scrollbar::-webkit-scrollbar {+ .modern-scrollbar::-webkit-scrollbar {width: 6px;}- .custom-scrollbar::-webkit-scrollbar-track {+ .modern-scrollbar::-webkit-scrollbar-track {background: transparent;}- .custom-scrollbar::-webkit-scrollbar-thumb {- background-color: var(--scrollbar-thumb, rgba(0, 0, 0, 0.2));- border-radius: 3px;+ .modern-scrollbar::-webkit-scrollbar-thumb {+ background-color: hsl(var(--border));+ border-radius: 6px;+ transition: background-color 0.2s ease;+ }++ .modern-scrollbar::-webkit-scrollbar-thumb:hover {+ background-color: hsl(var(--border) / 0.8);+ }++ :global(.dark) .modern-scrollbar::-webkit-scrollbar-thumb {+ background-color: hsl(var(--border) / 0.6);}- :global(.dark) .custom-scrollbar::-webkit-scrollbar-thumb {- --scrollbar-thumb: rgba(255, 255, 255, 0.2);+ :global(.dark) .modern-scrollbar::-webkit-scrollbar-thumb:hover {+ background-color: hsl(var(--border) / 0.8);}</style>diff --git a/src/lib/components/universal-table.svelte b/src/lib/components/universal-table.svelteindex 967d18171..c43f66daf 100644--- a/src/lib/components/universal-table.svelte+++ b/src/lib/components/universal-table.svelte@@ -1,18 +1,50 @@-<script lang="ts" generics="TData extends object">- import { getCoreRowModel, getPaginationRowModel, getSortedRowModel, type SortingState, getFilteredRowModel, type ColumnFiltersState } from '@tanstack/table-core';+<script lang="ts" generics="TData extends Record<string, any>">+ import { getCoreRowModel, getPaginationRowModel, getSortedRowModel, getFilteredRowModel, type SortingState, type ColumnFiltersState } from '@tanstack/table-core';import { createSvelteTable, FlexRender } from '$lib/components/ui/data-table/index.js';import * as Table from '$lib/components/ui/table/index.js';import * as Pagination from '$lib/components/ui/pagination/index.js';import * as Select from '$lib/components/ui/select/index.js';import { Input } from '$lib/components/ui/input/index.js';import { Button } from '$lib/components/ui/button/index.js';- import { debounced } from '$lib/utils';import { Checkbox } from '$lib/components/ui/checkbox/index.js';import { ChevronDown } from '@lucide/svelte';import { cn } from '$lib/utils';+ import { debounced } from '$lib/utils';import type { UniversalTableProps } from '$lib/types/table-types';import type { Snippet } from 'svelte';+ // Better type constraints+ interface TableData extends Record<string, any> {+ isExternal?: boolean;+ }++ interface TableFeatures {+ sorting?: boolean;+ filtering?: boolean;+ selection?: boolean;+ }++ interface TableDisplay {+ pageSize?: number;+ pageSizeOptions?: number[];+ itemsPerPageLabel?: string;+ filterPlaceholder?: string;+ noResultsMessage?: string;+ isDashboardTable?: boolean;+ class?: string;+ }++ interface TablePagination {+ pageSize?: number;+ pageSizeOptions?: number[];+ itemsPerPageLabel?: string;+ }++ interface TableSort {+ defaultSort?: { id: string; desc: boolean };+ }++ // Props with better defaults and validationlet {data,columns,@@ -30,66 +62,80 @@onPageSizeChange?: ((size: number) => void) | undefined;} = $props();- let { sorting: enableSorting = true, filtering: enableFiltering = true, selection: enableSelection = true } = features;- let { pageSize: initialPageSize = 10, pageSizeOptions = [10, 20, 50, 100], itemsPerPageLabel = 'Items per page' } = pagination;- let { filterPlaceholder = 'Search...', noResultsMessage = 'No results found', isDashboardTable = false, class: className = '' } = display;- let { defaultSort = { id: 'Name', desc: false } } = sort;+ // Destructure with proper defaults+ const { sorting: enableSorting = true, filtering: enableFiltering = true, selection: enableSelection = true }: TableFeatures = features;- let pageSize = $state(initialPageSize);+ const { pageSize: initialPageSize = 10, pageSizeOptions = [10, 20, 50, 100], itemsPerPageLabel = 'Items per page' }: TablePagination = pagination;++ const { filterPlaceholder = 'Search...', noResultsMessage = 'No results found', isDashboardTable = false, class: className = '' }: TableDisplay = display;++ const { defaultSort }: TableSort = sort;++ // State management with better initialization+ let pageSize = $state(Math.max(1, initialPageSize));let pageIndex = $state(0);let currentPage = $state(1);let sorting = $state<SortingState>(defaultSort ? [defaultSort] : []);let columnFilters = $state<ColumnFiltersState>([]);let globalFilter = $state<string>('');- let selectedRowIds = $derived<Record<string, boolean>>({});+ let rowSelection = $state<Record<string, boolean>>({});++ // Optimized debounced filter function+ const debouncedFilter = debounced((value: string) => {+ table.setGlobalFilter(value);+ }, 300);+ // Effect for syncing external selectedIds with internal state$effect(() => {- const newTanstackSelectionState: Record<string, boolean> = {};- (selectedIds || []).forEach((id) => {- newTanstackSelectionState[id] = true;+ if (!enableSelection) return;++ const newSelection: Record<string, boolean> = {};+ selectedIds.forEach((id) => {+ if (id) newSelection[id] = true;});- const currentTanstackSelectedKeys = Object.keys(selectedRowIds)- .filter((k) => selectedRowIds[k])+ const currentKeys = Object.keys(rowSelection)+ .filter((k) => rowSelection[k]).sort();- const newPropSelectedKeys = Object.keys(newTanstackSelectionState).sort();+ const newKeys = Object.keys(newSelection).sort();- if (JSON.stringify(currentTanstackSelectedKeys) !== JSON.stringify(newPropSelectedKeys)) {- table.setRowSelection(newTanstackSelectionState);+ if (JSON.stringify(currentKeys) !== JSON.stringify(newKeys)) {+ rowSelection = newSelection;}});+ // Effect for syncing page changes$effect(() => {- pageIndex = currentPage - 1;+ const newPageIndex = Math.max(0, currentPage - 1);+ if (pageIndex !== newPageIndex) {+ pageIndex = newPageIndex;+ }});+ // Effect for syncing table page state$effect(() => {const tablePageIndex = table.getState().pagination.pageIndex;- if (tablePageIndex !== pageIndex) {- currentPage = tablePageIndex + 1;+ const expectedCurrentPage = tablePageIndex + 1;+ if (currentPage !== expectedCurrentPage) {+ currentPage = expectedCurrentPage;}});+ // Create table instanceconst table = createSvelteTable({get data() {return data;},columns,- getRowId: idKey- ? (originalRow: TData) => {- return String(originalRow[idKey]);- }- : undefined,+ getRowId: idKey ? (originalRow: TData) => String(originalRow[idKey]) : undefined,getCoreRowModel: getCoreRowModel(),+ ...(enableSorting && { getSortedRowModel: getSortedRowModel() }),+ ...(enableFiltering && { getFilteredRowModel: getFilteredRowModel() }),getPaginationRowModel: getPaginationRowModel(),- getSortedRowModel: enableSorting ? getSortedRowModel() : undefined,- getFilteredRowModel: enableFiltering ? getFilteredRowModel() : undefined,+ enableRowSelection: enableSelection,state: {get pagination() {- return {- pageIndex,- pageSize- };+ return { pageIndex, pageSize };},get sorting() {return sorting;@@ -101,78 +147,94 @@return globalFilter;},get rowSelection() {- return selectedRowIds;+ return rowSelection;}},onSortingChange: (updater) => {- if (typeof updater === 'function') {- sorting = updater(sorting);- } else {- sorting = updater;- }+ sorting = typeof updater === 'function' ? updater(sorting) : updater;},onColumnFiltersChange: (updater) => {- if (typeof updater === 'function') {- columnFilters = updater(columnFilters);- } else {- columnFilters = updater;- }+ columnFilters = typeof updater === 'function' ? updater(columnFilters) : updater;},onGlobalFilterChange: (value) => {- globalFilter = value;+ globalFilter = value ?? '';pageIndex = 0;currentPage = 1;},onRowSelectionChange: (updater) => {- const newInternalState = typeof updater === 'function' ? updater(selectedRowIds) : updater;+ if (!enableSelection) return;- if (JSON.stringify(newInternalState) !== JSON.stringify(selectedRowIds)) {- selectedRowIds = newInternalState;- }+ const newSelection = typeof updater === 'function' ? updater(rowSelection) : updater;- const newSelectedIdsArray = Object.entries(selectedRowIds)- .filter(([key, selected]) => selected)- .map(([id]) => id);+ if (JSON.stringify(newSelection) !== JSON.stringify(rowSelection)) {+ rowSelection = newSelection;- const sortedCurrentProp = [...(selectedIds || [])].sort();- const sortedNewInternal = [...newSelectedIdsArray].sort();+ // Update external selectedIds+ const newSelectedIds = Object.entries(newSelection)+ .filter(([_, selected]) => selected)+ .map(([id]) => id);- if (JSON.stringify(sortedCurrentProp) !== JSON.stringify(sortedNewInternal)) {- selectedIds = newSelectedIdsArray;+ if (JSON.stringify(selectedIds.sort()) !== JSON.stringify(newSelectedIds.sort())) {+ selectedIds = newSelectedIds;+ }}- },- enableRowSelection: enableSelection+ }});- const pageCount = $derived(table.getPageCount());- const filteredRowCount = $derived(table.getFilteredRowModel().rows.length);+ // Memoized computations+ const validPageSizeOptions = $derived(pageSizeOptions.filter((size) => size > 0).sort((a, b) => a - b));- const handleFilterChange = debounced((value: string) => {- table.setGlobalFilter(value);- }, 300);+ const shouldShowPagination = $derived(!isDashboardTable && (table.getPageCount() > 1 || validPageSizeOptions.length > 1));++ const shouldShowFiltering = $derived(enableFiltering && !isDashboardTable);const allRowsSelected = $derived(table.getIsAllPageRowsSelected() && table.getRowModel().rows.length > 0);+ const filteredRowCount = $derived(table.getFilteredRowModel().rows.length);++ // Event handlers+ function handleFilterChange(value: string) {+ debouncedFilter(value);+ }+function handlePageSizeChange(size: string | number) {- const sizeNumber = typeof size === 'string' ? parseInt(size) : size;- pageSize = sizeNumber;- table.setPageSize(sizeNumber);- pageIndex = 0;- currentPage = 1;-- if (onPageSizeChange) {- onPageSizeChange(sizeNumber);+ const sizeNumber = typeof size === 'string' ? parseInt(size, 10) : size;++ if (!isNaN(sizeNumber) && sizeNumber > 0) {+ pageSize = sizeNumber;+ table.setPageSize(sizeNumber);+ pageIndex = 0;+ currentPage = 1;++ onPageSizeChange?.(sizeNumber);}}++ function handleSelectAllChange(checked: boolean) {+ table.toggleAllPageRowsSelected(checked);+ }++ function handleRowSelectionChange(row: any, checked: boolean) {+ const isDisabled = row.original?.isExternal ?? false;+ if (!isDisabled) {+ row.toggleSelected(checked);+ }+ }++ function handleSortChange(header: any) {+ header.column.toggleSorting(header.column.getIsSorted() === 'asc');+ }</script><div class={cn('space-y-4', className, isDashboardTable && 'dashboard-table')}>- {#if enableFiltering && !isDashboardTable}+ <!-- Search Filter -->+ {#if shouldShowFiltering}<div class="flex items-center"><Input placeholder={filterPlaceholder} value={globalFilter} oninput={(e) => handleFilterChange(e.currentTarget.value)} class="max-w-sm" /></div>{/if}+ <!-- Table --><div class={cn('rounded-md border', isDashboardTable && 'border-none rounded-none')}><Table.Root><Table.Header>@@ -180,17 +242,17 @@<Table.Row>{#if enableSelection}<Table.Head class="size-12">- <Checkbox checked={allRowsSelected} onCheckedChange={(checked) => table.toggleAllPageRowsSelected(!!checked)} />+ <Checkbox checked={allRowsSelected} onCheckedChange={handleSelectAllChange} aria-label="Select all rows" /></Table.Head>{/if}{#each headerGroup.headers as header (header.id)}<Table.Head>{#if !header.isPlaceholder}{#if header.column.getCanSort()}- <Button variant="ghost" class="flex items-center p-0 hover:bg-transparent" onclick={() => header.column.toggleSorting(header.column.getIsSorted() === 'asc')}>+ <Button variant="ghost" class="flex items-center p-0 hover:bg-transparent" onclick={() => handleSortChange(header)} aria-label="Sort by {header.column.columnDef.header}"><FlexRender content={header.column.columnDef.header} context={header.getContext()} />{#if header.column.getIsSorted()}- <ChevronDown class={cn('ml-2 h-4 w-4', header.column.getIsSorted() === 'asc' ? 'rotate-180' : '')} />+ <ChevronDown class={cn('ml-2 h-4 w-4 transition-transform', header.column.getIsSorted() === 'asc' && 'rotate-180')} />{/if}</Button>{:else}@@ -205,20 +267,11 @@<Table.Body>{#if table.getRowModel().rows.length > 0}{#each table.getRowModel().rows as row (row.id)}- {@const isDisabled = 'isExternal' in row.original && !!row.original.isExternal}- <Table.Row data-state={row.getIsSelected() && 'selected'}>+ {@const isDisabled = row.original?.isExternal ?? false}+ <Table.Row data-state={row.getIsSelected() ? 'selected' : undefined}>{#if enableSelection}<Table.Cell class="size-12">- <Checkbox- checked={row.getIsSelected()}- disabled={isDisabled}- onCheckedChange={(checked) => {- if (!isDisabled) {- row.toggleSelected(!!checked);- }- }}- aria-label="Select row"- />+ <Checkbox checked={row.getIsSelected()} disabled={isDisabled} onCheckedChange={(checked) => handleRowSelectionChange(row, !!checked)} aria-label="Select row" /></Table.Cell>{/if}@@ -245,19 +298,17 @@</div><!-- Pagination Controls -->- {#if (pageCount > 1 || pageSizeOptions.length > 1) && !isDashboardTable}+ {#if shouldShowPagination}<div class="flex flex-col sm:flex-row items-center justify-between gap-4">- {#if pageSizeOptions.length > 1}+ {#if validPageSizeOptions.length > 1}<div class="flex items-center gap-4">- <span class="text-sm my-auto">{itemsPerPageLabel}</span>- <Select.Root type="single" value={pageSize.toString()} onValueChange={(value) => handlePageSizeChange(value)}>- <Select.Trigger class="h-8 w-[70px]" id="pageSize">- <span>- {pageSize}- </span>+ <span class="text-sm whitespace-nowrap">{itemsPerPageLabel}</span>+ <Select.Root type="single" value={pageSize.toString()} onValueChange={handlePageSizeChange}>+ <Select.Trigger class="h-8 w-[70px]" aria-label="Items per page">+ <span>{pageSize}</span></Select.Trigger><Select.Content>- {#each pageSizeOptions as size}+ {#each validPageSizeOptions as size (size)}<Select.Item value={size.toString()}>{size}</Select.Item>@@ -269,7 +320,7 @@<div class="ml-auto"><Pagination.Root count={filteredRowCount} perPage={pageSize} bind:page={currentPage}>- {#snippet children({ pages, currentPage })}+ {#snippet children({ pages, currentPage: paginationCurrentPage })}<Pagination.Content><Pagination.Item><Pagination.PrevButton />@@ -281,7 +332,7 @@</Pagination.Item>{:else}<Pagination.Item>- <Pagination.Link {page} isActive={currentPage === page.value}>+ <Pagination.Link {page} isActive={paginationCurrentPage === page.value}>{page.value}</Pagination.Link></Pagination.Item>diff --git a/src/lib/types/settings.type.ts b/src/lib/types/settings.type.tsindex f853140c3..05048cb5e 100644--- a/src/lib/types/settings.type.ts+++ b/src/lib/types/settings.type.ts@@ -40,7 +40,7 @@ export interface Settings {autoUpdateInterval: number;pollingEnabled: boolean;pollingInterval: number;- pruneMode: 'all' | 'dangling';+ pruneMode: 'all' | 'dangling' | undefined;registryCredentials: RegistryCredential[];auth: AuthSettings;onboarding?: Onboarding;diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.tsindex 0d1343dfd..6df42d8bc 100644--- a/src/routes/+layout.server.ts+++ b/src/routes/+layout.server.ts@@ -10,6 +10,7 @@ let versionInformationLastUpdated: number;export const load = (async (locals) => {// If update checks are disabled via env var, return only current versionconst updateCheckDisabled = env.UPDATE_CHECK_DISABLED === 'true';+ const csrf = crypto.randomUUID();if (updateCheckDisabled) {return {@@ -37,6 +38,7 @@ export const load = (async (locals) => {return {versionInformation,- user: locals.locals.user || null+ user: locals.locals.user || null,+ csrf};}) satisfies LayoutServerLoad;diff --git a/src/routes/+page.svelte b/src/routes/+page.svelteindex a135d3b17..83ea101c9 100644--- a/src/routes/+page.svelte+++ b/src/routes/+page.svelte@@ -3,7 +3,7 @@import * as Card from '$lib/components/ui/card/index.js';import { Button } from '$lib/components/ui/button/index.js';import UniversalTable from '$lib/components/universal-table.svelte';- import { AlertCircle, Box, HardDrive, Cpu, MemoryStick, ArrowRight, PlayCircle, StopCircle, Trash2, Settings, RefreshCw, Loader2 } from '@lucide/svelte';+ import { AlertCircle, Box, HardDrive, Cpu, MemoryStick, ArrowRight, PlayCircle, StopCircle, Trash2, Settings, RefreshCw, Loader2, Monitor } from '@lucide/svelte';import * as Alert from '$lib/components/ui/alert/index.js';import { Progress } from '$lib/components/ui/progress/index.js';import { capitalizeFirstLetter, truncateString, shortId } from '$lib/utils/string.utils';@@ -26,6 +26,7 @@import { maturityStore } from '$lib/stores/maturity-store';import ImageAPIService from '$lib/services/api/image-api-service';import type { PruneType } from '$lib/types/actions.type';+ import DropdownCard from '$lib/components/dropdown-card.svelte';let { data }: { data: PageData & { containers: ContainerInfo[] } } = $props();@@ -201,93 +202,107 @@{/if}<section>- <div class="flex items-center justify-between mb-4">- <h2 class="text-lg font-semibold tracking-tight">Engine Overview</h2>- </div>-- <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">- <Card.Root class="overflow-hidden border-l-4 border-l-green-500">- <Card.Content class="p-6">- <div class="flex justify-between items-start">- <div>- <p class="text-sm font-medium text-muted-foreground">Running Containers</p>- <div class="mt-1">- <p class="text-2xl font-bold">- {runningContainers}- <span class="text-xs font-normal text-muted-foreground ml-1">/ {dashboardStates.containers?.length || 0}</span>- </p>+ <DropdownCard id="system-overview" title="System Overview" description="Hardware and Docker engine information" icon={Monitor} defaultExpanded={true}>+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">+ <Card.Root class="overflow-hidden border-l-4 border-l-green-500">+ <Card.Content class="p-6">+ <div class="flex justify-between items-start">+ <div>+ <p class="text-sm font-medium text-muted-foreground">Running Containers</p>+ <div class="mt-1">+ <p class="text-2xl font-bold">+ {runningContainers}+ <span class="text-xs font-normal text-muted-foreground ml-1">/ {dashboardStates.containers?.length || 0}</span>+ </p>+ </div>+ </div>+ <div class="bg-green-500/10 p-2 rounded-full">+ <Box class="text-green-500 size-5" /></div></div>- <div class="bg-green-500/10 p-2 rounded-full">- <Box class="text-green-500 size-5" />- </div>- </div>- {#if dashboardStates.containers?.length}- <Progress value={(runningContainers / (dashboardStates.containers.length || 1)) * 100} class="mt-4 h-2" />- {/if}- </Card.Content>- </Card.Root>-- <Card.Root class="overflow-hidden border-l-4 border-l-blue-500">- <Card.Content class="p-6">- <div class="flex justify-between items-start">- <div>- <p class="text-sm font-medium text-muted-foreground">Images</p>- <p class="text-2xl font-bold mt-1">{dashboardStates.dockerInfo?.Images || 0}</p>+ {#if dashboardStates.containers?.length}+ <Progress value={(runningContainers / (dashboardStates.containers.length || 1)) * 100} class="mt-4 h-2" />+ {/if}+ </Card.Content>+ </Card.Root>++ <Card.Root class="overflow-hidden border-l-4 border-l-blue-500">+ <Card.Content class="p-6">+ <div class="flex justify-between items-start">+ <div>+ <p class="text-sm font-medium text-muted-foreground">Images</p>+ <p class="text-2xl font-bold mt-1">{dashboardStates.dockerInfo?.Images || 0}</p>+ </div>+ <div class="bg-blue-500/10 p-2 rounded-full">+ <HardDrive class="text-blue-500 size-5" />+ </div></div>- <div class="bg-blue-500/10 p-2 rounded-full">- <HardDrive class="text-blue-500 size-5" />+ {#if totalImageSize > 0}+ <div class="mt-4 text-xs text-muted-foreground">+ Total size: {formatBytes(totalImageSize)}+ </div>+ {:else if dashboardStates.dockerInfo?.Images === 0}+ <div class="mt-4 text-xs text-muted-foreground">No images stored</div>+ {/if}+ </Card.Content>+ </Card.Root>++ <Card.Root class="overflow-hidden border-l-4 border-l-purple-500">+ <Card.Content class="p-6">+ <div class="flex justify-between items-start">+ <div>+ <p class="text-sm font-medium text-muted-foreground">Hardware Resources</p>+ <div class="grid grid-cols-2 gap-x-4 mt-2">+ <div>+ <p class="text-xs text-muted-foreground">CPU</p>+ <p class="text-lg font-semibold">{dashboardStates.dockerInfo?.NCPU || 'N/A'}</p>+ </div>+ <div>+ <p class="text-xs text-muted-foreground">Memory</p>+ <p class="text-lg font-semibold">{dashboardStates.dockerInfo?.MemTotal ? formatBytes(dashboardStates.dockerInfo.MemTotal, 0) : 'N/A'}</p>+ </div>+ </div>+ </div>+ <div class="bg-purple-500/10 p-2 rounded-full">+ <Cpu class="text-purple-500 size-5" />+ </div></div>- </div>- {#if totalImageSize > 0}<div class="mt-4 text-xs text-muted-foreground">- Total size: {formatBytes(totalImageSize)}+ {dashboardStates.dockerInfo?.Architecture || 'Unknown architecture'}</div>- {:else if dashboardStates.dockerInfo?.Images === 0}- <div class="mt-4 text-xs text-muted-foreground">No images stored</div>- {/if}- </Card.Content>- </Card.Root>-- <Card.Root class="overflow-hidden border-l-4 border-l-purple-500">- <Card.Content class="p-6">- <div class="flex justify-between items-start">- <div>- <p class="text-sm font-medium text-muted-foreground">CPU</p>- <p class="text-2xl font-bold mt-1">{dashboardStates.dockerInfo?.NCPU || 'N/A'}</p>- </div>- <div class="bg-purple-500/10 p-2 rounded-full">- <Cpu class="text-purple-500 size-5" />- </div>- </div>- <div class="mt-4 text-xs text-muted-foreground">- {dashboardStates.dockerInfo?.Architecture || 'Unknown architecture'}- </div>- </Card.Content>- </Card.Root>-- <Card.Root class="overflow-hidden border-l-4 border-l-amber-500">- <Card.Content class="p-6">- <div class="flex justify-between items-start">- <div>- <p class="text-sm font-medium text-muted-foreground">Memory</p>- <p class="text-2xl font-bold mt-1">- {dashboardStates.dockerInfo?.MemTotal ? formatBytes(dashboardStates.dockerInfo.MemTotal, 0) : 'N/A'}- </p>+ </Card.Content>+ </Card.Root>++ <Card.Root class="overflow-hidden border-l-4 border-l-amber-500">+ <Card.Content class="p-6">+ <div class="flex justify-between items-start">+ <div>+ <p class="text-sm font-medium text-muted-foreground">Docker Engine</p>+ <p class="text-xl font-semibold mt-1">+ {dashboardStates.dockerInfo?.ServerVersion || 'Unknown version'}+ </p>+ </div>+ <div class="bg-amber-500/10 p-2 rounded-full">+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-amber-500 size-5">+ <path d="M8 17v2a3 3 0 0 1-3 3H3"></path><path d="M12 17h10"></path><path d="M16 7H3a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h7"></path>+ <circle cx="20" cy="9" r="2"></circle>+ </svg>+ </div></div>- <div class="bg-amber-500/10 p-2 rounded-full">- <MemoryStick class="text-amber-500 size-5" />+ <div class="mt-4 grid grid-cols-2 gap-2">+ <div>+ <p class="text-xs font-medium text-muted-foreground">Operating System</p>+ <p class="text-sm">{dashboardStates.dockerInfo?.OperatingSystem || 'Unknown OS'}</p>+ </div>+ <div>+ <p class="text-xs font-medium text-muted-foreground">Kernel Version</p>+ <p class="text-sm">{dashboardStates.dockerInfo?.KernelVersion || 'Unknown'}</p>+ </div></div>- </div>- <div class="mt-4 text-xs text-muted-foreground">- {dashboardStates.dockerInfo?.OperatingSystem || 'Unknown OS'}- {#if dashboardStates.dockerInfo?.ServerVersion}- <span class="ml-1">• v{dashboardStates.dockerInfo.ServerVersion}</span>- {/if}- </div>- </Card.Content>- </Card.Root>- </div>+ </Card.Content>+ </Card.Root>+ </div>+ </DropdownCard></section><section>diff --git a/src/routes/api/volumes/+server.ts b/src/routes/api/volumes/+server.tsindex b5376f9fc..4a0e7965b 100644--- a/src/routes/api/volumes/+server.ts+++ b/src/routes/api/volumes/+server.ts@@ -1,10 +1,29 @@import { json } from '@sveltejs/kit';import type { RequestHandler } from './$types';-import { createVolume } from '$lib/services/docker/volume-service';+import { createVolume, listVolumes } from '$lib/services/docker/volume-service';import type { VolumeCreateOptions, VolumeInspectInfo } from 'dockerode';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';import { tryCatch } from '$lib/utils/try-catch';+export const GET: RequestHandler = async () => {+ const volumesResult = await tryCatch(listVolumes());++ if (volumesResult.error) {+ console.error('API Error fetching volumes:', volumesResult.error);+ const typedError = volumesResult.error as any;+ const response: ApiErrorResponse = {+ success: false,+ error: typedError.message || 'Failed to fetch volumes',+ code: typedError.code || ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: typedError.details || typedError+ };+ const status = typeof typedError.statusCode === 'number' ? typedError.statusCode : 500;+ return json(response, { status });+ }++ return json(volumesResult.data, { status: 200 });+};+export const POST: RequestHandler = async ({ request }) => {const bodyResult = await tryCatch(request.json());if (bodyResult.error) {diff --git a/src/routes/settings/+page.server.ts b/src/routes/settings/+page.server.tsdeleted file mode 100644index 6da86d013..000000000--- a/src/routes/settings/+page.server.ts+++ /dev/null@@ -1,27 +0,0 @@-import type { PageServerLoad } from './$types';-import { getSettings } from '$lib/services/settings-service';-import { listUsers } from '$lib/services/user-service';-import { env } from '$env/dynamic/private'; // Import private env--export const load: PageServerLoad = async () => {- const settings = await getSettings();- const users = await listUsers();-- const csrf = crypto.randomUUID();-- const sanitizedUsers = users.map((user) => {- // eslint-disable-next-line @typescript-eslint/no-unused-vars- const { passwordHash: _passwordHash, ...rest } = user;- return rest;- });-- // Check if essential OIDC environment variables are configured- const oidcEnvVarsConfigured = !!env.OIDC_CLIENT_ID && !!env.OIDC_CLIENT_SECRET && !!env.OIDC_REDIRECT_URI && !!env.OIDC_AUTHORIZATION_ENDPOINT && !!env.OIDC_TOKEN_ENDPOINT && !!env.OIDC_USERINFO_ENDPOINT;-- return {- settings,- csrf,- users: sanitizedUsers,- oidcEnvVarsConfigured // Pass this to the page- };-};diff --git a/src/routes/settings/+page.svelte b/src/routes/settings/+page.sveltedeleted file mode 100644index ece1e55e1..000000000--- a/src/routes/settings/+page.svelte+++ /dev/null@@ -1,94 +0,0 @@-<script lang="ts">- import * as Tabs from '$lib/components/ui/tabs/index.js';- import { Button } from '$lib/components/ui/button/index.js';- import { Save, RefreshCw } from '@lucide/svelte';- import type { PageData } from './$types';- import { toast } from 'svelte-sonner';- import { invalidateAll } from '$app/navigation';- import AppSettings from './tabs/app-settings.svelte';- import UserManagement from './tabs/user-management.svelte';- import Authentication from './tabs/authentication.svelte';- import { saveSettingsToServer, updateSettingsStore } from '$lib/stores/settings-store';- import { handleApiResultWithCallbacks } from '$lib/utils/api.util';- import { tryCatch } from '$lib/utils/try-catch';- import DockerSettings from './tabs/docker-settings.svelte';-- let { data } = $props<{ data: PageData }>();-- $effect(() => {- if (data.settings) {- updateSettingsStore(data.settings);- }- });-- let settingsPageStates = $state({- start: false,- error: <string | null>null,- activeTab: 'app-settings'- });-- let isLoading = $state({- saving: false- });-- const tabs = [- { id: 'app-settings', label: 'General', component: AppSettings },- { id: 'docker-settings', label: 'Docker', component: DockerSettings },- { id: 'user-management', label: 'User Management', component: UserManagement },- { id: 'authentication', label: 'Authentication', component: Authentication }- ];-- async function saveSettings() {- if (isLoading.saving) return;- isLoading.saving = true;- settingsPageStates.error = null;-- handleApiResultWithCallbacks({- result: await tryCatch(saveSettingsToServer()),- message: 'Error Saving Settings',- setLoadingState: (value) => (isLoading.saving = value),- onSuccess: async () => {- toast.success(`Settings Saved Successfully`);- await invalidateAll();- }- });- }-</script>--<div class="space-y-6">- <div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">- <div>- <h1 class="text-3xl font-bold tracking-tight">Settings</h1>- <p class="text-sm text-muted-foreground mt-1">Configure Arcane's settings and permissions</p>- </div>-- <Button onclick={saveSettings} disabled={isLoading.saving} class="h-10 arcane-button-save">- {#if isLoading.saving}- <RefreshCw class="animate-spin size-4" />- Saving...- {:else}- <Save class="size-4" />- Save Settings- {/if}- </Button>- </div>-- <Tabs.Root value={settingsPageStates.activeTab} onValueChange={(val) => (settingsPageStates.activeTab = val)} class="w-full">- <Tabs.List class="grid grid-cols-4 md:w-full md:max-w-3xl mb-4 dark:bg-slate-900">- {#each tabs as tab (tab.id)}- <Tabs.Trigger value={tab.id} class="whitespace-nowrap data-[state=active]:border data-[state=active]:border-primary/60">- {tab.label}- </Tabs.Trigger>- {/each}- </Tabs.List>-- <div id="settings-container">- <input type="hidden" id="csrf_token" value={data.csrf} />- {#each tabs as tab (tab.id)}- <Tabs.Content value={tab.id} class="space-y-4">- <tab.component {data} />- </Tabs.Content>- {/each}- </div>- </Tabs.Root>-</div>diff --git a/src/routes/settings/docker/+page.server.ts b/src/routes/settings/docker/+page.server.tsnew file mode 100644index 000000000..bd3665b4c--- /dev/null+++ b/src/routes/settings/docker/+page.server.ts@@ -0,0 +1,26 @@+import type { PageServerLoad } from './$types';+import { getSettings } from '$lib/services/settings-service';++export const load: PageServerLoad = async () => {+ try {+ const settings = await getSettings();++ return {+ settings+ };+ } catch (error) {+ console.error('Failed to load Docker settings:', error);+ return {+ settings: {+ dockerHost: 'unix:///var/run/docker.sock',+ registryCredentials: [],+ pollingEnabled: true,+ pollingInterval: 10,+ autoUpdate: false,+ autoUpdateInterval: 60,+ pruneMode: 'all'+ },+ csrf: crypto.randomUUID()+ };+ }+};diff --git a/src/routes/settings/docker/+page.svelte b/src/routes/settings/docker/+page.sveltenew file mode 100644index 000000000..cf3eb5fda--- /dev/null+++ b/src/routes/settings/docker/+page.svelte@@ -0,0 +1,386 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card/index.js';+ import { Input } from '$lib/components/ui/input/index.js';+ import { Switch } from '$lib/components/ui/switch/index.js';+ import { Button } from '$lib/components/ui/button/index.js';+ import { RefreshCw, Key, Plus, Trash2, ImageMinus, Server, Ellipsis, Pencil, Save } from '@lucide/svelte';+ import * as RadioGroup from '$lib/components/ui/radio-group/index.js';+ import { Label } from '$lib/components/ui/label/index.js';+ import type { PageData } from './$types';+ import { settingsStore, saveSettingsToServer, updateSettingsStore } from '$lib/stores/settings-store';+ import UniversalTable from '$lib/components/universal-table.svelte';+ import * as Table from '$lib/components/ui/table';+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';+ import RegistryFormDialog from '$lib/components/dialogs/registry-form-dialog.svelte';+ import { openConfirmDialog } from '$lib/components/confirm-dialog';+ import { toast } from 'svelte-sonner';+ import { invalidateAll } from '$app/navigation';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { tryCatch } from '$lib/utils/try-catch';+ import type { RegistryCredential } from '$lib/types/settings.type';++ let { data }: { data: PageData } = $props();++ let isRegistryDialogOpen = $state(false);+ let registryToEdit = $state<(RegistryCredential & { originalIndex?: number }) | null>(null);+ let isLoadingRegistryAction = $state(false);++ // Loading states+ let isLoading = $state({+ saving: false+ });++ $effect(() => {+ if (data.settings) {+ updateSettingsStore({+ ...data.settings,+ pruneMode: data.settings.pruneMode as 'all' | 'dangling'+ });+ }+ });++ function openCreateRegistryDialog() {+ registryToEdit = null;+ isRegistryDialogOpen = true;+ }++ function openEditRegistryDialog(credential: RegistryCredential, index: number) {+ registryToEdit = { ...credential, originalIndex: index };+ isRegistryDialogOpen = true;+ }++ async function handleRegistryDialogSubmit(eventDetail: { credential: RegistryCredential; isEditMode: boolean; originalIndex?: number }) {+ const { credential, isEditMode, originalIndex } = eventDetail;+ isLoadingRegistryAction = true;+ try {+ settingsStore.update((current) => {+ const updatedCredentials = [...(current.registryCredentials || [])];+ if (isEditMode && originalIndex !== undefined) {+ updatedCredentials[originalIndex] = credential;+ } else {+ updatedCredentials.push(credential);+ }+ return {+ ...current,+ registryCredentials: updatedCredentials+ };+ });++ const savedToServer = await saveSettingsToServer();+ if (savedToServer) {+ toast.success(isEditMode ? 'Registry Credential Updated Successfully' : 'Registry Credential Added Successfully');+ } else {+ toast.error('Failed to save registry settings to server.');+ }+ } catch (error) {+ console.error('Error handling registry dialog submit:', error);+ toast.error('An error occurred while saving registry settings.');+ } finally {+ isRegistryDialogOpen = false;+ isLoadingRegistryAction = false;+ }+ }++ function confirmRemoveRegistry(index: number) {+ const registryUrl = $settingsStore.registryCredentials?.[index]?.url || `Registry #${index + 1}`;+ openConfirmDialog({+ title: 'Remove Registry',+ message: `Are you sure you want to remove the registry "${registryUrl}"? This action cannot be undone.`,+ confirm: {+ label: 'Remove',+ destructive: true,+ action: async () => {+ await removeRegistry(index);+ }+ }+ });+ }++ async function removeRegistry(index: number) {+ isLoadingRegistryAction = true;+ try {+ settingsStore.update((current) => ({+ ...current,+ registryCredentials: (current.registryCredentials || []).filter((_, i) => i !== index)+ }));++ const savedToServer = await saveSettingsToServer();+ if (savedToServer) {+ toast.success('Registry Credential Removed Successfully');+ } else {+ toast.error('Failed to update registry settings on server.');+ }+ } catch (error) {+ console.error('Error removing registry:', error);+ toast.error('An error occurred while removing the registry.');+ } finally {+ isLoadingRegistryAction = false;+ }+ }++ // Save settings function+ async function saveSettings() {+ if (isLoading.saving) return;+ isLoading.saving = true;++ handleApiResultWithCallbacks({+ result: await tryCatch(saveSettingsToServer()),+ message: 'Error Saving Settings',+ setLoadingState: (value) => (isLoading.saving = value),+ onSuccess: async () => {+ toast.success(`Settings Saved Successfully`);+ await invalidateAll();+ }+ });+ }+</script>++<svelte:head>+ <title>Docker Settings - Arcane</title>+</svelte:head>++<RegistryFormDialog bind:open={isRegistryDialogOpen} bind:credentialToEdit={registryToEdit} onSubmit={handleRegistryDialogSubmit} isLoading={isLoadingRegistryAction} />++<div class="space-y-6">+ <div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">+ <div>+ <h1 class="text-3xl font-bold tracking-tight">Docker Settings</h1>+ <p class="text-sm text-muted-foreground mt-1">Configure Docker connection, registries, and automation</p>+ </div>++ <Button onclick={saveSettings} disabled={isLoading.saving} class="h-10 arcane-button-save">+ {#if isLoading.saving}+ <RefreshCw class="animate-spin size-4" />+ Saving...+ {:else}+ <Save class="size-4" />+ Save Settings+ {/if}+ </Button>+ </div>++ <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">+ <Card.Root class="border shadow-sm">+ <Card.Header class="pb-3">+ <div class="flex items-center gap-2">+ <div class="bg-blue-500/10 p-2 rounded-full">+ <Server class="text-blue-500 size-5" />+ </div>+ <div>+ <Card.Title>Docker Settings</Card.Title>+ <Card.Description>Configure Docker connection and registry credentials</Card.Description>+ </div>+ </div>+ </Card.Header>+ <Card.Content>+ <div class="space-y-4">+ <div class="space-y-2">+ <label for="dockerHost" class="text-sm font-medium block mb-1.5">Docker Host</label>+ <Input type="text" id="dockerHost" name="dockerHost" bind:value={$settingsStore.dockerHost} placeholder="unix:///var/run/docker.sock" required />+ <p class="text-xs text-muted-foreground">For local Docker: unix:///var/run/docker.sock (Unix)</p>+ </div>++ <div class="pt-4 border-t mt-4">+ <div class="flex items-center justify-between gap-2 mb-3">+ <div class="flex items-center gap-2">+ <div class="bg-green-500/10 p-2 rounded-full">+ <Key class="text-green-500 size-5" />+ </div>+ <div>+ <h3 class="font-medium">Docker Registry Credentials</h3>+ <p class="text-sm text-muted-foreground">Configure access to private Docker registries</p>+ </div>+ </div>+ <Button onclick={openCreateRegistryDialog} class="arcane-button-save">+ <Plus class="size-4" /> Add Registry+ </Button>+ </div>++ <div class="space-y-2">+ {#if !$settingsStore.registryCredentials || $settingsStore.registryCredentials.length === 0}+ <div class="text-center py-8 text-muted-foreground italic border rounded-md">No registry credentials configured yet.</div>+ {:else}+ <UniversalTable+ data={$settingsStore.registryCredentials}+ columns={[+ { accessorKey: 'url', header: 'Registry URL' },+ { accessorKey: 'username', header: 'Username' },+ { accessorKey: 'actions', header: ' ', enableSorting: false }+ ]}+ features={{+ sorting: true,+ filtering: false,+ selection: false+ }}+ pagination={{+ pageSize: 5,+ pageSizeOptions: [5]+ }}+ sort={{+ defaultSort: { id: 'url', desc: false }+ }}+ display={{+ noResultsMessage: 'No registry credentials found.'+ }}+ >+ {#snippet rows({ item, index })}+ {#if typeof index === 'number'}+ <Table.Cell class="font-medium">+ {item.url || 'Default (Docker Hub)'}+ </Table.Cell>+ <Table.Cell>{item.username || '-'}</Table.Cell>+ <Table.Cell class="text-right">+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ <Button variant="ghost" size="icon" class="size-8">+ <Ellipsis class="size-4" />+ <span class="sr-only">Open menu</span>+ </Button>+ </DropdownMenu.Trigger>+ <DropdownMenu.Content align="end">+ <DropdownMenu.Item onclick={() => openEditRegistryDialog(item, index)}>+ <Pencil class="mr-2 size-4" />+ Edit+ </DropdownMenu.Item>+ <DropdownMenu.Item onclick={() => confirmRemoveRegistry(index)} class="text-red-500 focus:text-red-700! focus:bg-destructive/10">+ <Trash2 class="mr-2 size-4" />+ Remove+ </DropdownMenu.Item>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ </Table.Cell>+ {/if}+ {/snippet}+ </UniversalTable>+ {/if}+ </div>+ </div>+ </div>+ </Card.Content>+ </Card.Root>++ <div class="space-y-6">+ <Card.Root class="border shadow-sm">+ <Card.Header class="pb-3">+ <div class="flex items-center gap-2">+ <div class="bg-amber-500/10 p-2 rounded-full">+ <RefreshCw class="text-amber-500 size-5" />+ </div>+ <div>+ <Card.Title>Image Polling</Card.Title>+ <Card.Description>Control container image polling</Card.Description>+ </div>+ </div>+ </Card.Header>+ <Card.Content class="space-y-6">+ <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">+ <div class="space-y-0.5">+ <label for="pollingEnabledSwitch" class="text-base font-medium">Check for New Images</label>+ <p class="text-sm text-muted-foreground">Periodically check for newer versions of container images</p>+ </div>+ <Switch+ id="pollingEnabledSwitch"+ name="pollingEnabled"+ checked={$settingsStore.pollingEnabled}+ onCheckedChange={(checked) => {+ settingsStore.update((current) => ({ ...current, pollingEnabled: checked }));+ }}+ />+ </div>++ {#if $settingsStore.pollingEnabled}+ <div class="space-y-2 px-1">+ <label for="pollingInterval" class="text-sm font-medium"> Polling Interval (minutes) </label>+ <Input+ id="pollingInterval"+ type="number"+ value={$settingsStore.pollingInterval}+ oninput={(e: Event) =>+ settingsStore.update((cur) => ({+ ...cur,+ pollingInterval: +(e.target as HTMLInputElement).value+ }))}+ min="5"+ max="60"+ />+ <p class="text-xs text-muted-foreground">Set between 5-60 minutes.</p>+ </div>++ <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">+ <div class="space-y-0.5">+ <Label for="autoUpdateSwitch" class="text-base font-medium">Auto Update Containers</Label>+ <p class="text-sm text-muted-foreground">Automatically update containers when newer images are available</p>+ </div>+ <Switch+ id="autoUpdateSwitch"+ checked={$settingsStore.autoUpdate}+ onCheckedChange={(checked) => {+ settingsStore.update((current) => ({ ...current, autoUpdate: checked }));+ }}+ />+ </div>++ {#if $settingsStore.autoUpdate}+ <div class="space-y-2 mt-4">+ <Label for="autoUpdateInterval" class="text-base font-medium">Auto-update check interval (minutes)</Label>+ <Input+ id="autoUpdateInterval"+ type="number"+ value={$settingsStore.autoUpdateInterval}+ oninput={(e: Event) =>+ settingsStore.update((cur) => ({+ ...cur,+ autoUpdateInterval: +(e.target as HTMLInputElement).value+ }))}+ min="5"+ max="1440"+ />+ <p class="text-sm text-muted-foreground">How often Arcane will check for container and stack updates (minimum 5 minutes, maximum 24 hours)</p>+ </div>+ {/if}+ {/if}+ </Card.Content>+ </Card.Root>++ <Card.Root class="border shadow-sm">+ <Card.Header class="pb-3">+ <div class="flex items-center gap-2">+ <div class="bg-purple-500/10 p-2 rounded-full">+ <ImageMinus class="text-purple-500 size-5" />+ </div>+ <div>+ <Card.Title>Image Pruning</Card.Title>+ <Card.Description>Configure image prune behavior</Card.Description>+ </div>+ </div>+ </Card.Header>+ <Card.Content class="space-y-4">+ <div>+ <Label for="pruneMode" class="text-base font-medium block mb-2">Prune Action Behavior</Label>+ <RadioGroup.Root+ value={$settingsStore.pruneMode}+ onValueChange={(val) => {+ settingsStore.update((current) => ({ ...current, pruneMode: val as 'all' | 'dangling' }));+ }}+ class="flex flex-col space-y-1"+ id="pruneMode"+ >+ <div class="flex items-center space-x-2">+ <RadioGroup.Item value="all" id="prune-all" />+ <Label for="prune-all" class="font-normal">All Unused Images (like `docker image prune -a`)</Label>+ </div>+ <div class="flex items-center space-x-2">+ <RadioGroup.Item value="dangling" id="prune-dangling" />+ <Label for="prune-dangling" class="font-normal">Dangling Images Only (like `docker image prune`)</Label>+ </div>+ </RadioGroup.Root>+ <p class="text-xs text-muted-foreground mt-2">Select which images are removed by the "Prune Unused" action on the Images page.</p>+ </div>+ </Card.Content>+ </Card.Root>+ </div>+ </div>++ <!-- Hidden CSRF token if needed -->+ <input type="hidden" id="csrf_token" value={data.csrf} />+</div>diff --git a/src/routes/settings/general/+page.server.ts b/src/routes/settings/general/+page.server.tsnew file mode 100644index 000000000..1ac0816f2--- /dev/null+++ b/src/routes/settings/general/+page.server.ts@@ -0,0 +1,21 @@+import type { PageServerLoad } from './$types';+import { getSettings } from '$lib/services/settings-service';++export const load: PageServerLoad = async () => {+ try {+ const settings = await getSettings();++ return {+ settings+ };+ } catch (error) {+ console.error('Failed to load settings:', error);+ return {+ settings: {+ stacksDirectory: 'data/stacks',+ baseServerUrl: 'localhost',+ maturityThresholdDays: 30+ }+ };+ }+};diff --git a/src/routes/settings/general/+page.svelte b/src/routes/settings/general/+page.sveltenew file mode 100644index 000000000..6bd485d48--- /dev/null+++ b/src/routes/settings/general/+page.svelte@@ -0,0 +1,184 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card/index.js';+ import FormInput from '$lib/components/form/form-input.svelte';+ import { Button } from '$lib/components/ui/button/index.js';+ import { Cog, Save, RefreshCw } from '@lucide/svelte';+ import type { PageData } from './$types';+ import { settingsStore, saveSettingsToServer, updateSettingsStore } from '$lib/stores/settings-store';+ import type { FormInput as FormInputType } from '$lib/types/form.type';+ import { toast } from 'svelte-sonner';+ import { invalidateAll } from '$app/navigation';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { tryCatch } from '$lib/utils/try-catch';++ let { data }: { data: PageData } = $props();++ // Initialize form inputs+ let stacksDirectoryInput = $state<FormInputType<string>>({+ value: '',+ valid: true,+ touched: false,+ error: null,+ errors: []+ });++ let baseServerUrlInput = $state<FormInputType<string>>({+ value: '',+ valid: true,+ touched: false,+ error: null,+ errors: []+ });++ let maturityThresholdInput = $state<FormInputType<number>>({+ value: 30,+ valid: true,+ touched: false,+ error: null,+ errors: []+ });++ // Loading states+ let isLoading = $state({+ saving: false+ });++ // Synchronize values when settings change+ $effect(() => {+ // Get the latest values from the store+ const settings = $settingsStore;++ // Update form inputs with values from the store+ stacksDirectoryInput.value = settings.stacksDirectory || 'data/stacks';+ baseServerUrlInput.value = settings.baseServerUrl || 'localhost';+ maturityThresholdInput.value = settings.maturityThresholdDays || 30;+ });++ // Initialize settings from page data once+ let initialized = false;+ $effect(() => {+ if (data.settings) {+ updateSettingsStore(data.settings);+ }+ });++ // No automatic syncing - just event handlers for changes+ function onStacksDirectoryChange() {+ stacksDirectoryInput.touched = true;+ settingsStore.update((settings) => ({+ ...settings,+ stacksDirectory: stacksDirectoryInput.value+ }));+ }++ function onBaseServerUrlChange() {+ baseServerUrlInput.touched = true;+ settingsStore.update((settings) => ({+ ...settings,+ baseServerUrl: baseServerUrlInput.value+ }));+ }++ function onMaturityThresholdChange() {+ maturityThresholdInput.touched = true;+ const rawValue = maturityThresholdInput.value;+ const numericValue = parseInt(String(rawValue), 10);++ if (!isNaN(numericValue)) {+ maturityThresholdInput.value = numericValue;+ settingsStore.update((settings) => ({+ ...settings,+ maturityThresholdDays: numericValue+ }));+ maturityThresholdInput.valid = true;+ maturityThresholdInput.error = null;+ } else {+ maturityThresholdInput.valid = false;+ maturityThresholdInput.error = 'Please enter a valid whole number.';+ }+ }++ // Save settings function+ async function saveSettings() {+ if (isLoading.saving) return;+ isLoading.saving = true;++ handleApiResultWithCallbacks({+ result: await tryCatch(saveSettingsToServer()),+ message: 'Error Saving Settings',+ setLoadingState: (value) => (isLoading.saving = value),+ onSuccess: async () => {+ toast.success(`Settings Saved Successfully`);+ await invalidateAll();+ }+ });+ }+</script>++<svelte:head>+ <title>General Settings - Arcane</title>+</svelte:head>++<div class="space-y-6">+ <div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">+ <div>+ <h1 class="text-3xl font-bold tracking-tight">General Settings</h1>+ <p class="text-sm text-muted-foreground mt-1">Core configuration for how Arcane operates</p>+ </div>++ <Button onclick={saveSettings} disabled={isLoading.saving} class="h-10 arcane-button-save">+ {#if isLoading.saving}+ <RefreshCw class="animate-spin size-4" />+ Saving...+ {:else}+ <Save class="size-4" />+ Save Settings+ {/if}+ </Button>+ </div>++ <div class="grid auto-cols-auto lg:auto-cols-auto gap-6">+ <Card.Root class="border shadow-sm">+ <Card.Header class="pb-3">+ <div class="flex items-center gap-2">+ <div class="bg-primary/10 p-2 rounded-full">+ <Cog class="text-primary size-5" />+ </div>+ <div>+ <Card.Title>Core Arcane Configuration</Card.Title>+ <Card.Description>Essential settings for how Arcane operates.</Card.Description>+ </div>+ </div>+ </Card.Header>+ <Card.Content>+ <div class="space-y-6">+ <FormInput+ bind:input={stacksDirectoryInput}+ type="text"+ id="stacksDirectory"+ label="Stack Projects Directory"+ placeholder="data/stacks"+ description="The primary folder where Arcane will store and manage your Docker Compose stack projects. This path is inside Arcane's container."+ warningText="Important: Changing this path will not automatically move existing stack projects."+ oninput={() => onStacksDirectoryChange()}+ />++ <FormInput+ bind:input={baseServerUrlInput}+ type="text"+ id="baseServerUrl"+ label="Default Service Access URL"+ placeholder="localhost"+ description="When Arcane provides links to your services (e.g., web UIs), this URL (like 'localhost' or an IP address) is used as the default. This is primarily for services not on directly accessible networks (e.g., macvlan)."+ oninput={() => onBaseServerUrlChange()}+ />++ <FormInput bind:input={maturityThresholdInput} type="number" id="maturityThresholdDays" label="Image Maturity Threshold (days)" placeholder="30" description="The number of days after an image release before it's considered 'matured'." warningText="Higher values mean more caution with new images." oninput={() => onMaturityThresholdChange()} />+ </div>+ </Card.Content>+ </Card.Root>+ </div>++ <!-- Hidden CSRF token if needed -->+ <input type="hidden" id="csrf_token" value={data.csrf} />+</div>diff --git a/src/routes/settings/rbac/+page.server.ts b/src/routes/settings/rbac/+page.server.tsnew file mode 100644index 000000000..a10da9f23--- /dev/null+++ b/src/routes/settings/rbac/+page.server.ts@@ -0,0 +1,10 @@+import type { PageServerLoad } from './$types';+import { getSettings } from '$lib/services/settings-service';++export const load: PageServerLoad = async () => {+ const settings = await getSettings();++ return {+ settings+ };+};diff --git a/src/routes/settings/rbac/+page.svelte b/src/routes/settings/rbac/+page.sveltenew file mode 100644index 000000000..0ba74a40e--- /dev/null+++ b/src/routes/settings/rbac/+page.svelte@@ -0,0 +1,235 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card/index.js';+ import { Button } from '$lib/components/ui/button/index.js';+ import { Input } from '$lib/components/ui/input/index.js';+ import { Shield, Plus, Users, Settings, Save, RefreshCw } from '@lucide/svelte';+ import type { PageData } from './$types';+ import Switch from '$lib/components/ui/switch/switch.svelte';+ import { settingsStore, saveSettingsToServer, updateSettingsStore } from '$lib/stores/settings-store';+ import { toast } from 'svelte-sonner';+ import { invalidateAll } from '$app/navigation';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { tryCatch } from '$lib/utils/try-catch';++ let { data }: { data: PageData } = $props();++ // Loading states+ let isLoading = $state({+ saving: false+ });++ // Initialize settings from page data+ $effect(() => {+ if (data.settings) {+ updateSettingsStore(data.settings);+ }+ });++ const roles = [+ {+ id: 1,+ name: 'Admin',+ description: 'Full system access',+ permissions: ['containers:manage', 'stacks:manage', 'volumes:manage', 'networks:manage', 'settings:manage', 'users:manage']+ },+ {+ id: 2,+ name: 'User',+ description: 'Container and stack operations',+ permissions: ['containers:view', 'containers:manage', 'stacks:view', 'stacks:manage', 'volumes:view', 'networks:view']+ },+ {+ id: 3,+ name: 'Viewer',+ description: 'Read-only access',+ permissions: ['containers:view', 'stacks:view', 'volumes:view', 'networks:view']+ }+ ];++ // Available permissions categories+ const permissionCategories = [+ {+ name: 'Containers',+ permissions: ['containers:view', 'containers:manage', 'containers:deploy']+ },+ {+ name: 'Stacks',+ permissions: ['stacks:view', 'stacks:manage', 'stacks:deploy']+ },+ {+ name: 'Volumes',+ permissions: ['volumes:view', 'volumes:manage', 'volumes:create']+ },+ {+ name: 'Networks',+ permissions: ['networks:view', 'networks:manage', 'networks:create']+ },+ {+ name: 'Settings',+ permissions: ['settings:view', 'settings:manage']+ },+ {+ name: 'Users',+ permissions: ['users:view', 'users:manage', 'users:create']+ }+ ];++ let selectedRole = $state(roles[0]);++ // Save settings function+ async function saveSettings() {+ if (isLoading.saving) return;+ isLoading.saving = true;++ handleApiResultWithCallbacks({+ result: await tryCatch(saveSettingsToServer()),+ message: 'Error Saving Settings',+ setLoadingState: (value) => (isLoading.saving = value),+ onSuccess: async () => {+ toast.success(`Settings Saved Successfully`);+ await invalidateAll();+ }+ });+ }+</script>++<svelte:head>+ <title>RBAC Settings - Arcane</title>+</svelte:head>++<div class="space-y-6">+ <div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">+ <div>+ <h1 class="text-3xl font-bold tracking-tight">Role-Based Access Control</h1>+ <p class="text-sm text-muted-foreground mt-1">Manage user roles and permissions</p>+ </div>++ <Button onclick={saveSettings} disabled={isLoading.saving} class="h-10 arcane-button-save">+ {#if isLoading.saving}+ <RefreshCw class="animate-spin size-4" />+ Saving...+ {:else}+ <Save class="size-4" />+ Save Settings+ {/if}+ </Button>+ </div>++ <div class="mb-6">+ <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">+ <div class="space-y-0.5">+ <label for="rbacEnabledSwitch" class="text-base font-medium">Enable Role-Based Access Control</label>+ <p class="text-sm text-muted-foreground">Control user permissions with customizable roles</p>+ </div>+ <Switch+ id="rbacEnabledSwitch"+ name="rbacEnabled"+ checked={$settingsStore.auth?.rbacEnabled}+ onCheckedChange={(checked) => {+ settingsStore.update((current) => ({+ ...current,+ auth: {+ ...current.auth,+ rbacEnabled: checked+ }+ }));+ }}+ />+ </div>+ </div>++ <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">+ <div class="lg:col-span-1">+ <Card.Root class="border shadow-sm h-full">+ <Card.Header class="pb-3">+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-2">+ <div class="bg-blue-500/10 p-2 rounded-full">+ <Users class="text-blue-500 size-5" />+ </div>+ <Card.Title>Roles</Card.Title>+ </div>+ <Button variant="outline" size="sm">+ <Plus class="mr-1 size-4" /> Add+ </Button>+ </div>+ </Card.Header>+ <Card.Content>+ <div class="space-y-2">+ {#each roles as role (role.id)}+ <button class="w-full text-left p-3 rounded-md border transition-colors flex items-center justify-between {selectedRole.id === role.id ? 'bg-primary text-primary-foreground border-primary' : 'hover:bg-muted/50'}" onclick={() => (selectedRole = role)}>+ <div>+ <div class="font-medium">{role.name}</div>+ <div class="text-xs {selectedRole.id === role.id ? 'text-primary-foreground/90' : 'text-muted-foreground'}">+ {role.description}+ </div>+ </div>+ <Shield class="opacity-70 size-4" />+ </button>+ {/each}+ </div>+ </Card.Content>+ </Card.Root>+ </div>++ <div class="lg:col-span-2">+ <Card.Root class="border shadow-sm">+ <Card.Header class="pb-3">+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-2">+ <div class="bg-purple-500/10 p-2 rounded-full">+ <Settings class="text-purple-500 size-5" />+ </div>+ <div>+ <Card.Title>Role: {selectedRole.name}</Card.Title>+ <Card.Description>{selectedRole.description}</Card.Description>+ </div>+ </div>+ <div class="space-x-2">+ <Button variant="outline" size="sm">Delete</Button>+ <Button size="sm">Save Changes</Button>+ </div>+ </div>+ </Card.Header>+ <Card.Content>+ <div class="space-y-6">+ <!-- Role Info -->+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">+ <div class="space-y-2">+ <label for="roleName" class="text-sm font-medium">Role Name</label>+ <Input id="roleName" name="roleName" value={selectedRole.name} placeholder="Enter role name" />+ </div>+ <div class="space-y-2">+ <label for="roleDescription" class="text-sm font-medium">Description</label>+ <Input id="roleDescription" name="roleDescription" value={selectedRole.description} placeholder="Brief description" />+ </div>+ </div>++ <!-- Permissions -->+ <div>+ <h3 class="text-sm font-medium mb-3">Permissions</h3>+ <div class="border rounded-md divide-y">+ {#each permissionCategories as category (category.name)}+ <div class="p-3">+ <h4 class="font-medium mb-2">{category.name}</h4>+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-2">+ {#each category.permissions as permission (permission)}+ <label class="flex items-center space-x-2 text-sm">+ <input type="checkbox" class="rounded border-gray-300 text-primary focus:ring-primary" checked={selectedRole.permissions.includes(permission)} />+ <span>{permission.split(':')[1]}</span>+ </label>+ {/each}+ </div>+ </div>+ {/each}+ </div>+ </div>+ </div>+ </Card.Content>+ </Card.Root>+ </div>+ </div>++ <!-- Hidden CSRF token if needed -->+ <input type="hidden" id="csrf_token" value={data.csrf} />+</div>diff --git a/src/routes/settings/security/+page.server.ts b/src/routes/settings/security/+page.server.tsnew file mode 100644index 000000000..c85d91534--- /dev/null+++ b/src/routes/settings/security/+page.server.ts@@ -0,0 +1,14 @@+import type { PageServerLoad } from './$types';+import { getSettings } from '$lib/services/settings-service';+import { env } from '$env/dynamic/private';++export const load: PageServerLoad = async () => {+ const settings = await getSettings();++ const oidcEnvVarsConfigured = !!env.OIDC_CLIENT_ID && !!env.OIDC_CLIENT_SECRET && !!env.OIDC_REDIRECT_URI && !!env.OIDC_AUTHORIZATION_ENDPOINT && !!env.OIDC_TOKEN_ENDPOINT && !!env.OIDC_USERINFO_ENDPOINT;++ return {+ settings,+ oidcEnvVarsConfigured+ };+};diff --git a/src/routes/settings/security/+page.svelte b/src/routes/settings/security/+page.sveltenew file mode 100644index 000000000..615b42fde--- /dev/null+++ b/src/routes/settings/security/+page.svelte@@ -0,0 +1,420 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { env as publicEnv } from '$env/dynamic/public';+ 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 { Input } from '$lib/components/ui/input/index.js';+ import { Switch } from '$lib/components/ui/switch/index.js';+ import { Lock, Key, AlertTriangle, Info, Save, RefreshCw } from '@lucide/svelte';+ import { settingsStore, saveSettingsToServer, updateSettingsStore } from '$lib/stores/settings-store';+ import * as Dialog from '$lib/components/ui/dialog/index.js';+ import { Label } from '$lib/components/ui/label/index.js';+ import { toast } from 'svelte-sonner';+ import { invalidateAll } from '$app/navigation';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { tryCatch } from '$lib/utils/try-catch';++ let { data }: { data: PageData } = $props();++ const isOidcForcedByPublicEnv = publicEnv.PUBLIC_OIDC_ENABLED === 'true';++ let showOidcConfigDialog = $state(false);+ let oidcConfigForm = $state({+ clientId: data.settings?.auth?.oidc?.clientId || '',+ clientSecret: '',+ redirectUri: data.settings?.auth?.oidc?.redirectUri || 'http://localhost:3000/auth/oidc/callback',+ authorizationEndpoint: data.settings?.auth?.oidc?.authorizationEndpoint || '',+ tokenEndpoint: data.settings?.auth?.oidc?.tokenEndpoint || '',+ userinfoEndpoint: data.settings?.auth?.oidc?.userinfoEndpoint || '',+ scopes: data.settings?.auth?.oidc?.scopes || 'openid email profile'+ });++ // Loading states+ let isLoading = $state({+ saving: false+ });++ let isOidcViewMode = $derived(data.oidcEnvVarsConfigured);+ let oidcConfiguredViaAppSettings = $derived(!!(data.settings?.auth?.oidc?.clientId && data.settings?.auth?.oidc?.redirectUri && data.settings?.auth?.oidc?.authorizationEndpoint && data.settings?.auth?.oidc?.tokenEndpoint));++ $effect(() => {+ if (data.settings) {+ updateSettingsStore(data.settings);+ }+ });++ onMount(() => {+ if (isOidcForcedByPublicEnv) {+ if (!$settingsStore.auth?.oidcEnabled) {+ settingsStore.update((current) => ({+ ...current,+ auth: {+ ...(current.auth || {}),+ oidcEnabled: true+ }+ }));+ }+ if (!data.oidcEnvVarsConfigured) {+ showOidcConfigDialog = true;+ }+ }+ });++ function handleOidcSwitchChange(checked: boolean) {+ settingsStore.update((current) => ({+ ...current,+ auth: {+ ...(current.auth || {}),+ oidcEnabled: checked+ }+ }));++ if (checked && !data.oidcEnvVarsConfigured) {+ showOidcConfigDialog = true;+ }+ }++ function openOidcDialog() {+ showOidcConfigDialog = true;+ }++ async function handleSaveOidcConfig() {+ try {+ settingsStore.update((current) => {+ const existingAuth = { ...(current.auth || {}) };+ const newOidcConfig = {+ clientId: oidcConfigForm.clientId,+ clientSecret: oidcConfigForm.clientSecret,+ redirectUri: oidcConfigForm.redirectUri,+ authorizationEndpoint: oidcConfigForm.authorizationEndpoint,+ tokenEndpoint: oidcConfigForm.tokenEndpoint,+ userinfoEndpoint: oidcConfigForm.userinfoEndpoint,+ scopes: oidcConfigForm.scopes+ };++ return {+ ...current,+ auth: {+ ...existingAuth,+ oidcEnabled: true,+ oidc: newOidcConfig+ }+ };+ });++ await saveSettingsToServer();++ toast.success('OIDC configuration saved successfully.');+ showOidcConfigDialog = false;+ } catch (error) {+ console.error('Failed to save OIDC configuration:', error);+ toast.error('Failed to save OIDC configuration.', {+ description: error instanceof Error ? error.message : 'An unknown error occurred.'+ });+ }+ }++ // Save settings function+ async function saveSettings() {+ if (isLoading.saving) return;+ isLoading.saving = true;++ handleApiResultWithCallbacks({+ result: await tryCatch(saveSettingsToServer()),+ message: 'Error Saving Settings',+ setLoadingState: (value) => (isLoading.saving = value),+ onSuccess: async () => {+ toast.success(`Settings Saved Successfully`);+ await invalidateAll();+ }+ });+ }+</script>++<svelte:head>+ <title>Security Settings - Arcane</title>+</svelte:head>++<div class="space-y-6">+ <div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">+ <div>+ <h1 class="text-3xl font-bold tracking-tight">Security Settings</h1>+ <p class="text-sm text-muted-foreground mt-1">Configure authentication methods and security policies</p>+ </div>++ <Button onclick={saveSettings} disabled={isLoading.saving} class="h-10 arcane-button-save">+ {#if isLoading.saving}+ <RefreshCw class="animate-spin size-4" />+ Saving...+ {:else}+ <Save class="size-4" />+ Save Settings+ {/if}+ </Button>+ </div>++ <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">+ <Card.Root class="border shadow-sm">+ <Card.Header class="pb-3">+ <div class="flex items-center gap-2">+ <div class="bg-indigo-500/10 p-2 rounded-full">+ <Lock class="text-indigo-500 size-5" />+ </div>+ <div>+ <Card.Title>Authentication Methods</Card.Title>+ <Card.Description>Configure how users sign in</Card.Description>+ </div>+ </div>+ </Card.Header>+ <Card.Content>+ <div class="space-y-4">+ <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">+ <div class="space-y-0.5">+ <label for="localAuthSwitch" class="text-base font-medium">Local Authentication</label>+ <p class="text-sm text-muted-foreground">Username and password stored in the system</p>+ <p class="text-xs text-muted-foreground mt-1">This is recommended to be enabled as a fallback option if OIDC authentication is unavailable.</p>+ </div>+ <Switch+ id="localAuthSwitch"+ checked={$settingsStore.auth?.localAuthEnabled ?? true}+ onCheckedChange={(checked) => {+ settingsStore.update((current) => ({+ ...current,+ auth: {+ ...(current.auth || {}),+ localAuthEnabled: checked+ }+ }));+ }}+ />+ </div>+ <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">+ <div class="space-y-0.5">+ <label for="oidcAuthSwitch" class="text-base font-medium">OIDC Authentication</label>+ <p class="text-sm text-muted-foreground">+ Use an External OIDC Provider+ {#if isOidcForcedByPublicEnv}+ <span class="text-xs text-muted-foreground">(Forced ON by environment)</span>+ {/if}+ </p>+ {#if isOidcForcedByPublicEnv || $settingsStore.auth?.oidcEnabled}+ {#if isOidcForcedByPublicEnv && !data.oidcEnvVarsConfigured}+ <Button variant="link" class="p-0 h-auto text-xs text-destructive hover:underline" onclick={openOidcDialog}>+ <AlertTriangle class="mr-1 size-3" />+ OIDC is forced ON, but critical server settings are missing. Click for details.+ </Button>+ {:else if data.oidcEnvVarsConfigured}+ <Button variant="link" class="p-0 h-auto text-xs text-sky-600 hover:underline" onclick={openOidcDialog}>+ <Info class="mr-1 size-3" />+ OIDC is configured on server. View Status.+ </Button>+ {:else if oidcConfiguredViaAppSettings}+ <Button variant="link" class="p-0 h-auto text-xs text-sky-600 hover:underline" onclick={openOidcDialog}>+ <Info class="mr-1 size-3" />+ OIDC configured via application settings. Click to Manage Them.+ </Button>+ {:else if !showOidcConfigDialog}+ <!-- This case: Not forced by public env, store has it enabled, but neither server vars nor app settings are fully configured -->+ <Button variant="link" class="p-0 h-auto text-xs text-destructive hover:underline" onclick={openOidcDialog}>+ <AlertTriangle class="mr-1 size-3" />+ OIDC application settings not configured. Click to configure.+ </Button>+ {/if}+ {/if}+ </div>+ <Switch id="oidcAuthSwitch" checked={isOidcForcedByPublicEnv || ($settingsStore.auth?.oidcEnabled ?? false)} disabled={isOidcForcedByPublicEnv} onCheckedChange={handleOidcSwitchChange} />+ </div>+ </div>+ </Card.Content>+ </Card.Root>++ <!-- OIDC Configuration/Status Dialog -->+ <Dialog.Root bind:open={showOidcConfigDialog}>+ <Dialog.Content class="sm:max-w-[600px]">+ <Dialog.Header>+ <Dialog.Title+ >{#if isOidcViewMode}OIDC Configuration Status{:else}Configure OIDC Provider{/if}</Dialog.Title+ >+ <Dialog.Description>+ {#if isOidcViewMode}+ OIDC authentication is configured using server-side environment variables.+ {#if $settingsStore.auth?.oidcEnabled}+ It is currently active.+ {:else if isOidcForcedByPublicEnv}+ It is forced ON by environment variables but may require application settings to be saved if this is the first run.+ {:else}+ It is configured but currently disabled in application settings. You can enable it using the switch.+ {/if}+ <p class="mt-2">The following OIDC settings are loaded from the server environment:</p>+ <ul class="list-disc list-inside mt-1 text-xs space-y-1">+ {#if data.settings?.auth?.oidc}+ <li><strong>Client ID:</strong> {data.settings.auth.oidc.clientId}</li>+ <li><strong>Client Secret:</strong> <span class="italic text-muted-foreground">(Sensitive - Not Displayed)</span></li>+ <li><strong>Redirect URI:</strong> {data.settings.auth.oidc.redirectUri}</li>+ <li><strong>Authorization Endpoint:</strong> {data.settings.auth.oidc.authorizationEndpoint}</li>+ <li><strong>Token Endpoint:</strong> {data.settings.auth.oidc.tokenEndpoint}</li>+ <li><strong>User Info Endpoint:</strong> {data.settings.auth.oidc.userinfoEndpoint}</li>+ <li><strong>Scopes:</strong> {data.settings.auth.oidc.scopes}</li>+ {:else}+ <li><span class="text-destructive">OIDC configuration details not found in settings.</span></li>+ {/if}+ </ul>+ <p class="mt-2 text-xs">Changes to these settings must be made in your server's environment configuration.</p>+ {:else}+ Configure the OIDC settings for your application. These settings will be saved and used for OIDC authentication.+ {#if isOidcForcedByPublicEnv && !data.oidcEnvVarsConfigured}+ <br />+ <strong class="text-orange-600 text-xs mt-1 block">OIDC usage is currently forced ON by <code>PUBLIC_OIDC_ENABLED</code>, but critical server-side OIDC environment variables appear to be missing. Please configure them below and save, or ensure the corresponding server environment variables are set.</strong>+ {:else if isOidcForcedByPublicEnv}+ <br />+ <strong class="text-orange-600 text-xs mt-1 block">OIDC usage is currently forced ON by <code>PUBLIC_OIDC_ENABLED</code>.</strong>+ {/if}+ {/if}+ </Dialog.Description>+ </Dialog.Header>++ {#if !isOidcViewMode}+ <!-- Form for setup/configuration -->+ <div class="grid gap-4 py-4 max-h-[50vh] overflow-y-auto pr-2">+ <div class="grid grid-cols-4 items-center gap-4">+ <Label for="oidcClientId" class="text-right col-span-1">Client ID</Label>+ <Input id="oidcClientId" bind:value={oidcConfigForm.clientId} class="col-span-3" placeholder="Provided by your OIDC Provider" />+ </div>+ <div class="grid grid-cols-4 items-center gap-4">+ <Label for="oidcClientSecret" class="text-right col-span-1">Client Secret</Label>+ <Input id="oidcClientSecret" type="password" bind:value={oidcConfigForm.clientSecret} class="col-span-3" placeholder="Provided by your OIDC Provider" />+ </div>+ <div class="grid grid-cols-4 items-center gap-4">+ <Label for="oidcRedirectUri" class="text-right col-span-1">Redirect URI</Label>+ <Input id="oidcRedirectUri" bind:value={oidcConfigForm.redirectUri} placeholder="e.g., http://localhost:3000/auth/oidc/callback" class="col-span-3" />+ </div>+ <div class="grid grid-cols-4 items-center gap-4">+ <Label for="oidcAuthEndpoint" class="text-right col-span-1">Authorization URL</Label>+ <Input id="oidcAuthEndpoint" bind:value={oidcConfigForm.authorizationEndpoint} class="col-span-3" placeholder="OIDC Provider's Authorization Endpoint" />+ </div>+ <div class="grid grid-cols-4 items-center gap-4">+ <Label for="oidcTokenEndpoint" class="text-right col-span-1">Token URL</Label>+ <Input id="oidcTokenEndpoint" bind:value={oidcConfigForm.tokenEndpoint} class="col-span-3" placeholder="OIDC Provider's Token Endpoint" />+ </div>+ <div class="grid grid-cols-4 items-center gap-4">+ <Label for="oidcUserinfoEndpoint" class="text-right col-span-1">User Info URL</Label>+ <Input id="oidcUserinfoEndpoint" bind:value={oidcConfigForm.userinfoEndpoint} class="col-span-3" placeholder="OIDC Provider's UserInfo Endpoint" />+ </div>+ <div class="grid grid-cols-4 items-center gap-4">+ <Label for="oidcScopes" class="text-right col-span-1">Scopes</Label>+ <Input id="oidcScopes" bind:value={oidcConfigForm.scopes} placeholder="e.g., openid email profile" class="col-span-3" />+ </div>+ </div>+ {/if}++ <Dialog.Footer>+ <Button variant="outline" onclick={() => (showOidcConfigDialog = false)}>Close</Button>+ {#if !isOidcViewMode}+ <Button onclick={handleSaveOidcConfig}>Save Configuration</Button>+ {/if}+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog.Root>++ <div class="space-y-6">+ <Card.Root class="border shadow-sm">+ <Card.Header class="pb-3">+ <div class="flex items-center gap-2">+ <div class="bg-cyan-500/10 p-2 rounded-full">+ <Key class="text-cyan-500 size-5" />+ </div>+ <div>+ <Card.Title>Session Settings</Card.Title>+ <Card.Description>Configure session behavior</Card.Description>+ </div>+ </div>+ </Card.Header>+ <Card.Content>+ <div class="space-y-4">+ <div class="space-y-2">+ <label for="sessionTimeout" class="text-sm font-medium">Session Timeout (minutes)</label>+ <Input+ type="number"+ id="sessionTimeout"+ name="sessionTimeout"+ value={$settingsStore.auth?.sessionTimeout ?? 60}+ min="15"+ max="1440"+ oninput={(event) => {+ const target = event.target as HTMLInputElement;+ settingsStore.update((current) => ({+ ...current,+ auth: {+ ...(current.auth ?? {}),+ sessionTimeout: parseInt(target.value)+ }+ }));+ }}+ />+ <p class="text-xs text-muted-foreground">Time until inactive sessions are automatically logged out (15-1440 minutes)</p>+ </div>++ <div class="space-y-2">+ <label for="passwordPolicy" class="text-sm font-medium">Password Policy</label>+ <div class="grid grid-cols-3 gap-2">+ <Button+ variant={($settingsStore.auth?.passwordPolicy || 'strong') === 'basic' ? 'default' : 'outline'}+ class={($settingsStore.auth?.passwordPolicy || 'strong') === 'basic' ? 'w-full arcane-button-create' : 'w-full arcane-button-restart'}+ onclick={() => {+ settingsStore.update((current) => ({+ ...current,+ auth: {+ ...current.auth,+ passwordPolicy: 'basic'+ }+ }));+ }}>Basic</Button+ >+ <Button+ variant={($settingsStore.auth?.passwordPolicy || 'strong') === 'standard' ? 'default' : 'outline'}+ class={($settingsStore.auth?.passwordPolicy || 'strong') === 'standard' ? 'w-full arcane-button-create' : 'w-full arcane-button-restart'}+ onclick={() => {+ settingsStore.update((current) => ({+ ...current,+ auth: {+ ...current.auth,+ passwordPolicy: 'standard'+ }+ }));+ }}>Standard</Button+ >+ <Button+ variant={($settingsStore.auth?.passwordPolicy || 'strong') === 'strong' ? 'default' : 'outline'}+ class={($settingsStore.auth?.passwordPolicy || 'strong') === 'strong' ? 'w-full arcane-button-create' : 'w-full arcane-button-restart'}+ onclick={() => {+ settingsStore.update((current) => ({+ ...current,+ auth: {+ ...current.auth,+ passwordPolicy: 'strong'+ }+ }));+ }}>Strong</Button+ >+ </div>+ <input type="hidden" id="passwordPolicy" name="passwordPolicy" value={$settingsStore.auth?.passwordPolicy || 'strong'} />+ <p class="text-xs text-muted-foreground mt-1">+ {#if $settingsStore.auth?.passwordPolicy === 'basic'}+ Basic: Minimum 8 characters+ {:else if $settingsStore.auth?.passwordPolicy === 'standard'}+ Standard: Minimum 10 characters, requires mixed case and numbers+ {:else}+ Strong: Minimum 12 characters, requires mixed case, numbers and special characters+ {/if}+ </p>+ </div>+ </div>+ </Card.Content>+ </Card.Root>+ </div>+ </div>++ <!-- Hidden CSRF token if needed -->+ <input type="hidden" id="csrf_token" value={data.csrf} />+</div>diff --git a/src/routes/settings/tabs/app-settings.svelte b/src/routes/settings/tabs/app-settings.sveltedeleted file mode 100644index f27ade5f7..000000000--- a/src/routes/settings/tabs/app-settings.svelte+++ /dev/null@@ -1,136 +0,0 @@-<script lang="ts">- import * as Card from '$lib/components/ui/card/index.js';- import FormInput from '$lib/components/form/form-input.svelte';- import { Cog } from '@lucide/svelte';- import type { PageData } from '../$types';- import { settingsStore } from '$lib/stores/settings-store';- import type { FormInput as FormInputType } from '$lib/types/form.type';-- let { data } = $props<{ data: PageData }>();-- // Initialize form inputs- let stacksDirectoryInput = $state<FormInputType<string>>({- value: '',- valid: true,- touched: false,- error: null,- errors: []- });-- let baseServerUrlInput = $state<FormInputType<string>>({- value: '',- valid: true,- touched: false,- error: null,- errors: []- });-- let maturityThresholdInput = $state<FormInputType<number>>({- value: 30,- valid: true,- touched: false,- error: null,- errors: []- });-- // Synchronize values when settings change- $effect(() => {- // Get the latest values from the store- const settings = $settingsStore;-- // Update form inputs with values from the store- stacksDirectoryInput.value = settings.stacksDirectory || 'data/stacks';- baseServerUrlInput.value = settings.baseServerUrl || 'localhost';- maturityThresholdInput.value = settings.maturityThresholdDays || 30;- });-- // Initialize settings from page data once- let initialized = false;- $effect(() => {- if (data.settings && !initialized) {- settingsStore.update((current) => ({- ...current,- ...data.settings- }));- initialized = true;- }- });-- // No automatic syncing - just event handlers for changes- function onStacksDirectoryChange() {- stacksDirectoryInput.touched = true;- settingsStore.update((settings) => ({- ...settings,- stacksDirectory: stacksDirectoryInput.value- }));- }-- function onBaseServerUrlChange() {- baseServerUrlInput.touched = true;- settingsStore.update((settings) => ({- ...settings,- baseServerUrl: baseServerUrlInput.value- }));- }-- function onMaturityThresholdChange() {- maturityThresholdInput.touched = true;- const rawValue = maturityThresholdInput.value;- const numericValue = parseInt(String(rawValue), 10);-- if (!isNaN(numericValue)) {- maturityThresholdInput.value = numericValue;- settingsStore.update((settings) => ({- ...settings,- maturityThresholdDays: numericValue- }));- maturityThresholdInput.valid = true;- maturityThresholdInput.error = null;- } else {- maturityThresholdInput.valid = false;- maturityThresholdInput.error = 'Please enter a valid whole number.';- }- }-</script>--<div class="grid auto-cols-auto lg:auto-cols-auto gap-6">- <Card.Root class="border shadow-sm">- <Card.Header class="pb-3">- <div class="flex items-center gap-2">- <div class="bg-primary/10 p-2 rounded-full">- <Cog class="text-primary size-5" />- </div>- <div>- <Card.Title>Core Arcane Configuration</Card.Title>- <Card.Description>Essential settings for how Arcane operates.</Card.Description>- </div>- </div>- </Card.Header>- <Card.Content>- <div class="space-y-6">- <FormInput- bind:input={stacksDirectoryInput}- type="text"- id="stacksDirectory"- label="Stack Projects Directory"- placeholder="data/stacks"- description="The primary folder where Arcane will store and manage your Docker Compose stack projects. This path is inside Arcane's container."- warningText="Important: Changing this path will not automatically move existing stack projects."- oninput={() => onStacksDirectoryChange()}- />-- <FormInput- bind:input={baseServerUrlInput}- type="text"- id="baseServerUrl"- label="Default Service Access URL"- placeholder="localhost"- description="When Arcane provides links to your services (e.g., web UIs), this URL (like 'localhost' or an IP address) is used as the default. This is primarily for services not on directly accessible networks (e.g., macvlan)."- oninput={() => onBaseServerUrlChange()}- />-- <FormInput bind:input={maturityThresholdInput} type="number" id="maturityThresholdDays" label="Image Maturity Threshold (days)" placeholder="30" description="The number of days after an image release before it's considered 'matured'." warningText="Higher values mean more caution with new images." oninput={() => onMaturityThresholdChange()} />- </div>- </Card.Content>- </Card.Root>-</div>diff --git a/src/routes/settings/tabs/authentication.svelte b/src/routes/settings/tabs/authentication.sveltedeleted file mode 100644index 10c942ebd..000000000--- a/src/routes/settings/tabs/authentication.svelte+++ /dev/null@@ -1,364 +0,0 @@-<script lang="ts">- import { onMount } from 'svelte';- import { env as publicEnv } from '$env/dynamic/public';- 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 { Input } from '$lib/components/ui/input/index.js';- import { Switch } from '$lib/components/ui/switch/index.js';- import { Lock, Key, AlertTriangle, Info } from '@lucide/svelte';- import { settingsStore, saveSettingsToServer } from '$lib/stores/settings-store';- import * as Dialog from '$lib/components/ui/dialog/index.js';- import { Label } from '$lib/components/ui/label/index.js';- import { toast } from 'svelte-sonner';-- let { data } = $props<{ data: PageData }>();-- const isOidcForcedByPublicEnv = publicEnv.PUBLIC_OIDC_ENABLED === 'true';-- let showOidcConfigDialog = $state(false);- let oidcConfigForm = $state({- clientId: data.settings?.auth?.oidc?.clientId || '',- clientSecret: '',- redirectUri: data.settings?.auth?.oidc?.redirectUri || 'http://localhost:3000/auth/oidc/callback',- authorizationEndpoint: data.settings?.auth?.oidc?.authorizationEndpoint || '',- tokenEndpoint: data.settings?.auth?.oidc?.tokenEndpoint || '',- userinfoEndpoint: data.settings?.auth?.oidc?.userinfoEndpoint || '',- scopes: data.settings?.auth?.oidc?.scopes || 'openid email profile'- });-- let isOidcViewMode = $derived(data.oidcEnvVarsConfigured);- let oidcConfiguredViaAppSettings = $derived(!!(data.settings?.auth?.oidc?.clientId && data.settings?.auth?.oidc?.redirectUri && data.settings?.auth?.oidc?.authorizationEndpoint && data.settings?.auth?.oidc?.tokenEndpoint));-- onMount(() => {- if (isOidcForcedByPublicEnv) {- if (!$settingsStore.auth?.oidcEnabled) {- settingsStore.update((current) => ({- ...current,- auth: {- ...(current.auth || {}),- oidcEnabled: true- }- }));- }- if (!data.oidcEnvVarsConfigured) {- showOidcConfigDialog = true;- }- }- });-- function handleOidcSwitchChange(checked: boolean) {- settingsStore.update((current) => ({- ...current,- auth: {- ...(current.auth || {}),- oidcEnabled: checked- }- }));-- if (checked && !data.oidcEnvVarsConfigured) {- showOidcConfigDialog = true;- }- }-- function openOidcDialog() {- showOidcConfigDialog = true;- }-- async function handleSaveOidcConfig() {- try {- settingsStore.update((current) => {- const existingAuth = { ...(current.auth || {}) };- const newOidcConfig = {- clientId: oidcConfigForm.clientId,- clientSecret: oidcConfigForm.clientSecret,- redirectUri: oidcConfigForm.redirectUri,- authorizationEndpoint: oidcConfigForm.authorizationEndpoint,- tokenEndpoint: oidcConfigForm.tokenEndpoint,- userinfoEndpoint: oidcConfigForm.userinfoEndpoint,- scopes: oidcConfigForm.scopes- };-- return {- ...current,- auth: {- ...existingAuth,- oidcEnabled: true,- oidc: newOidcConfig- }- };- });-- await saveSettingsToServer();-- toast.success('OIDC configuration saved successfully.');- showOidcConfigDialog = false;- } catch (error) {- console.error('Failed to save OIDC configuration:', error);- toast.error('Failed to save OIDC configuration.', {- description: error instanceof Error ? error.message : 'An unknown error occurred.'- });- }- }-</script>--<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">- <Card.Root class="border shadow-sm">- <Card.Header class="pb-3">- <div class="flex items-center gap-2">- <div class="bg-indigo-500/10 p-2 rounded-full">- <Lock class="text-indigo-500 size-5" />- </div>- <div>- <Card.Title>Authentication Methods</Card.Title>- <Card.Description>Configure how users sign in</Card.Description>- </div>- </div>- </Card.Header>- <Card.Content>- <div class="space-y-4">- <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">- <div class="space-y-0.5">- <label for="localAuthSwitch" class="text-base font-medium">Local Authentication</label>- <p class="text-sm text-muted-foreground">Username and password stored in the system</p>- <p class="text-xs text-muted-foreground mt-1">This is recommended to be enabled as a fallback option if OIDC authentication is unavailable.</p>- </div>- <Switch- id="localAuthSwitch"- checked={$settingsStore.auth?.localAuthEnabled ?? true}- onCheckedChange={(checked) => {- settingsStore.update((current) => ({- ...current,- auth: {- ...(current.auth || {}),- localAuthEnabled: checked- }- }));- }}- />- </div>- <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">- <div class="space-y-0.5">- <label for="oidcAuthSwitch" class="text-base font-medium">OIDC Authentication</label>- <p class="text-sm text-muted-foreground">- Use an External OIDC Provider- {#if isOidcForcedByPublicEnv}- <span class="text-xs text-muted-foreground">(Forced ON by environment)</span>- {/if}- </p>- {#if isOidcForcedByPublicEnv || $settingsStore.auth?.oidcEnabled}- {#if isOidcForcedByPublicEnv && !data.oidcEnvVarsConfigured}- <Button variant="link" class="p-0 h-auto text-xs text-destructive hover:underline" onclick={openOidcDialog}>- <AlertTriangle class="mr-1 size-3" />- OIDC is forced ON, but critical server settings are missing. Click for details.- </Button>- {:else if data.oidcEnvVarsConfigured}- <Button variant="link" class="p-0 h-auto text-xs text-sky-600 hover:underline" onclick={openOidcDialog}>- <Info class="mr-1 size-3" />- OIDC is configured on server. View Status.- </Button>- {:else if oidcConfiguredViaAppSettings}- <Button variant="link" class="p-0 h-auto text-xs text-sky-600 hover:underline" onclick={openOidcDialog}>- <Info class="mr-1 size-3" />- OIDC configured via application settings. Click to Manage Them.- </Button>- {:else if !showOidcConfigDialog}- <!-- This case: Not forced by public env, store has it enabled, but neither server vars nor app settings are fully configured -->- <Button variant="link" class="p-0 h-auto text-xs text-destructive hover:underline" onclick={openOidcDialog}>- <AlertTriangle class="mr-1 size-3" />- OIDC application settings not configured. Click to configure.- </Button>- {/if}- {/if}- </div>- <Switch id="oidcAuthSwitch" checked={isOidcForcedByPublicEnv || ($settingsStore.auth?.oidcEnabled ?? false)} disabled={isOidcForcedByPublicEnv} onCheckedChange={handleOidcSwitchChange} />- </div>- </div>- </Card.Content>- </Card.Root>-- <!-- OIDC Configuration/Status Dialog -->- <Dialog.Root bind:open={showOidcConfigDialog}>- <Dialog.Content class="sm:max-w-[600px]">- <Dialog.Header>- <Dialog.Title- >{#if isOidcViewMode}OIDC Configuration Status{:else}Configure OIDC Provider{/if}</Dialog.Title- >- <Dialog.Description>- {#if isOidcViewMode}- OIDC authentication is configured using server-side environment variables.- {#if $settingsStore.auth?.oidcEnabled}- It is currently active.- {:else if isOidcForcedByPublicEnv}- It is forced ON by environment variables but may require application settings to be saved if this is the first run.- {:else}- It is configured but currently disabled in application settings. You can enable it using the switch.- {/if}- <p class="mt-2">The following OIDC settings are loaded from the server environment:</p>- <ul class="list-disc list-inside mt-1 text-xs space-y-1">- {#if data.settings?.auth?.oidc}- <li><strong>Client ID:</strong> {data.settings.auth.oidc.clientId}</li>- <li><strong>Client Secret:</strong> <span class="italic text-muted-foreground">(Sensitive - Not Displayed)</span></li>- <li><strong>Redirect URI:</strong> {data.settings.auth.oidc.redirectUri}</li>- <li><strong>Authorization Endpoint:</strong> {data.settings.auth.oidc.authorizationEndpoint}</li>- <li><strong>Token Endpoint:</strong> {data.settings.auth.oidc.tokenEndpoint}</li>- <li><strong>User Info Endpoint:</strong> {data.settings.auth.oidc.userinfoEndpoint}</li>- <li><strong>Scopes:</strong> {data.settings.auth.oidc.scopes}</li>- {:else}- <li><span class="text-destructive">OIDC configuration details not found in settings.</span></li>- {/if}- </ul>- <p class="mt-2 text-xs">Changes to these settings must be made in your server's environment configuration.</p>- {:else}- Configure the OIDC settings for your application. These settings will be saved and used for OIDC authentication.- {#if isOidcForcedByPublicEnv && !data.oidcEnvVarsConfigured}- <br />- <strong class="text-orange-600 text-xs mt-1 block">OIDC usage is currently forced ON by <code>PUBLIC_OIDC_ENABLED</code>, but critical server-side OIDC environment variables appear to be missing. Please configure them below and save, or ensure the corresponding server environment variables are set.</strong>- {:else if isOidcForcedByPublicEnv}- <br />- <strong class="text-orange-600 text-xs mt-1 block">OIDC usage is currently forced ON by <code>PUBLIC_OIDC_ENABLED</code>.</strong>- {/if}- {/if}- </Dialog.Description>- </Dialog.Header>-- {#if !isOidcViewMode}- <!-- Form for setup/configuration -->- <div class="grid gap-4 py-4 max-h-[50vh] overflow-y-auto pr-2">- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcClientId" class="text-right col-span-1">Client ID</Label>- <Input id="oidcClientId" bind:value={oidcConfigForm.clientId} class="col-span-3" placeholder="Provided by your OIDC Provider" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcClientSecret" class="text-right col-span-1">Client Secret</Label>- <Input id="oidcClientSecret" type="password" bind:value={oidcConfigForm.clientSecret} class="col-span-3" placeholder="Provided by your OIDC Provider" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcRedirectUri" class="text-right col-span-1">Redirect URI</Label>- <Input id="oidcRedirectUri" bind:value={oidcConfigForm.redirectUri} placeholder="e.g., http://localhost:3000/auth/oidc/callback" class="col-span-3" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcAuthEndpoint" class="text-right col-span-1">Authorization URL</Label>- <Input id="oidcAuthEndpoint" bind:value={oidcConfigForm.authorizationEndpoint} class="col-span-3" placeholder="OIDC Provider's Authorization Endpoint" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcTokenEndpoint" class="text-right col-span-1">Token URL</Label>- <Input id="oidcTokenEndpoint" bind:value={oidcConfigForm.tokenEndpoint} class="col-span-3" placeholder="OIDC Provider's Token Endpoint" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcUserinfoEndpoint" class="text-right col-span-1">User Info URL</Label>- <Input id="oidcUserinfoEndpoint" bind:value={oidcConfigForm.userinfoEndpoint} class="col-span-3" placeholder="OIDC Provider's UserInfo Endpoint" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcScopes" class="text-right col-span-1">Scopes</Label>- <Input id="oidcScopes" bind:value={oidcConfigForm.scopes} placeholder="e.g., openid email profile" class="col-span-3" />- </div>- </div>- {/if}-- <Dialog.Footer>- <Button variant="outline" onclick={() => (showOidcConfigDialog = false)}>Close</Button>- {#if !isOidcViewMode}- <Button onclick={handleSaveOidcConfig}>Save Configuration</Button>- {/if}- </Dialog.Footer>- </Dialog.Content>- </Dialog.Root>-- <div class="space-y-6">- <Card.Root class="border shadow-sm">- <Card.Header class="pb-3">- <div class="flex items-center gap-2">- <div class="bg-cyan-500/10 p-2 rounded-full">- <Key class="text-cyan-500 size-5" />- </div>- <div>- <Card.Title>Session Settings</Card.Title>- <Card.Description>Configure session behavior</Card.Description>- </div>- </div>- </Card.Header>- <Card.Content>- <div class="space-y-4">- <div class="space-y-2">- <label for="sessionTimeout" class="text-sm font-medium">Session Timeout (minutes)</label>- <Input- type="number"- id="sessionTimeout"- name="sessionTimeout"- value={$settingsStore.auth?.sessionTimeout ?? 60}- min="15"- max="1440"- oninput={(event) => {- const target = event.target as HTMLInputElement;- settingsStore.update((current) => ({- ...current,- auth: {- ...(current.auth ?? {}),- sessionTimeout: parseInt(target.value)- }- }));- }}- />- <p class="text-xs text-muted-foreground">Time until inactive sessions are automatically logged out (15-1440 minutes)</p>- </div>-- <div class="space-y-2">- <label for="passwordPolicy" class="text-sm font-medium">Password Policy</label>- <div class="grid grid-cols-3 gap-2">- <Button- variant={($settingsStore.auth?.passwordPolicy || 'strong') === 'basic' ? 'default' : 'outline'}- class={($settingsStore.auth?.passwordPolicy || 'strong') === 'basic' ? 'w-full arcane-button-create' : 'w-full arcane-button-restart'}- onclick={() => {- settingsStore.update((current) => ({- ...current,- auth: {- ...current.auth,- passwordPolicy: 'basic'- }- }));- }}>Basic</Button- >- <Button- variant={($settingsStore.auth?.passwordPolicy || 'strong') === 'standard' ? 'default' : 'outline'}- class={($settingsStore.auth?.passwordPolicy || 'strong') === 'standard' ? 'w-full arcane-button-create' : 'w-full arcane-button-restart'}- onclick={() => {- settingsStore.update((current) => ({- ...current,- auth: {- ...current.auth,- passwordPolicy: 'standard'- }- }));- }}>Standard</Button- >- <Button- variant={($settingsStore.auth?.passwordPolicy || 'strong') === 'strong' ? 'default' : 'outline'}- class={($settingsStore.auth?.passwordPolicy || 'strong') === 'strong' ? 'w-full arcane-button-create' : 'w-full arcane-button-restart'}- onclick={() => {- settingsStore.update((current) => ({- ...current,- auth: {- ...current.auth,- passwordPolicy: 'strong'- }- }));- }}>Strong</Button- >- </div>- <input type="hidden" id="passwordPolicy" name="passwordPolicy" value={$settingsStore.auth?.passwordPolicy || 'strong'} />- <p class="text-xs text-muted-foreground mt-1">- {#if $settingsStore.auth?.passwordPolicy === 'basic'}- Basic: Minimum 8 characters- {:else if $settingsStore.auth?.passwordPolicy === 'standard'}- Standard: Minimum 10 characters, requires mixed case and numbers- {:else}- Strong: Minimum 12 characters, requires mixed case, numbers and special characters- {/if}- </p>- </div>- </div>- </Card.Content>- </Card.Root>- </div>-</div>diff --git a/src/routes/settings/tabs/docker-settings.svelte b/src/routes/settings/tabs/docker-settings.sveltedeleted file mode 100644index 4c44da725..000000000--- a/src/routes/settings/tabs/docker-settings.svelte+++ /dev/null@@ -1,336 +0,0 @@-<script lang="ts">- import * as Card from '$lib/components/ui/card/index.js';- import { Input } from '$lib/components/ui/input/index.js';- import { Switch } from '$lib/components/ui/switch/index.js';- import { RefreshCw, Key, Plus, Trash2, ImageMinus, Server, Ellipsis, Pencil } from '@lucide/svelte';- import * as RadioGroup from '$lib/components/ui/radio-group/index.js';- import { Label } from '$lib/components/ui/label/index.js';- import type { PageData } from '../$types';- import { Button } from '$lib/components/ui/button/index.js';- import { settingsStore, saveSettingsToServer } from '$lib/stores/settings-store';- import UniversalTable from '$lib/components/universal-table.svelte';- import * as Table from '$lib/components/ui/table';- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';- import RegistryFormDialog from '$lib/components/dialogs/registry-form-dialog.svelte';- import { openConfirmDialog } from '$lib/components/confirm-dialog';- import { toast } from 'svelte-sonner';- import type { RegistryCredential } from '$lib/types/settings.type';-- let { data } = $props<{ data: PageData }>();-- let isRegistryDialogOpen = $state(false);- let registryToEdit = $state<(RegistryCredential & { originalIndex?: number }) | null>(null);- let isLoadingRegistryAction = $state(false);-- $effect(() => {- if (data.settings) {- settingsStore.update((current) => ({- ...current,- ...data.settings- }));- }- });-- function openCreateRegistryDialog() {- registryToEdit = null;- isRegistryDialogOpen = true;- }-- function openEditRegistryDialog(credential: RegistryCredential, index: number) {- registryToEdit = { ...credential, originalIndex: index };- isRegistryDialogOpen = true;- }-- async function handleRegistryDialogSubmit(eventDetail: { credential: RegistryCredential; isEditMode: boolean; originalIndex?: number }) {- const { credential, isEditMode, originalIndex } = eventDetail;- isLoadingRegistryAction = true;- try {- settingsStore.update((current) => {- const updatedCredentials = [...(current.registryCredentials || [])];- if (isEditMode && originalIndex !== undefined) {- updatedCredentials[originalIndex] = credential;- } else {- updatedCredentials.push(credential);- }- return {- ...current,- registryCredentials: updatedCredentials- };- });-- const savedToServer = await saveSettingsToServer();- if (savedToServer) {- toast.success(isEditMode ? 'Registry Credential Updated Successfully' : 'Registry Credential Added Successfully');- } else {- toast.error('Failed to save registry settings to server.');- }- } catch (error) {- console.error('Error handling registry dialog submit:', error);- toast.error('An error occurred while saving registry settings.');- } finally {- isRegistryDialogOpen = false;- isLoadingRegistryAction = false;- }- }-- function confirmRemoveRegistry(index: number) {- const registryUrl = $settingsStore.registryCredentials?.[index]?.url || `Registry #${index + 1}`;- openConfirmDialog({- title: 'Remove Registry',- message: `Are you sure you want to remove the registry "${registryUrl}"? This action cannot be undone.`,- confirm: {- label: 'Remove',- destructive: true,- action: async () => {- await removeRegistry(index);- }- }- });- }-- async function removeRegistry(index: number) {- isLoadingRegistryAction = true;- try {- settingsStore.update((current) => ({- ...current,- registryCredentials: (current.registryCredentials || []).filter((_, i) => i !== index)- }));-- const savedToServer = await saveSettingsToServer();- if (savedToServer) {- toast.success('Registry Credential Removed Successfully');- } else {- toast.error('Failed to update registry settings on server.');- }- } catch (error) {- console.error('Error removing registry:', error);- toast.error('An error occurred while removing the registry.');- } finally {- isLoadingRegistryAction = false;- }- }-</script>--<RegistryFormDialog bind:open={isRegistryDialogOpen} bind:credentialToEdit={registryToEdit} onSubmit={handleRegistryDialogSubmit} isLoading={isLoadingRegistryAction} />--<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">- <Card.Root class="border shadow-sm">- <Card.Header class="pb-3">- <div class="flex items-center gap-2">- <div class="bg-blue-500/10 p-2 rounded-full">- <Server class="text-blue-500 size-5" />- </div>- <div>- <Card.Title>Docker Settings</Card.Title>- <Card.Description>Configure Docker connection and registry credentials</Card.Description>- </div>- </div>- </Card.Header>- <Card.Content>- <div class="space-y-4">- <div class="space-y-2">- <label for="dockerHost" class="text-sm font-medium block mb-1.5">Docker Host</label>- <Input type="text" id="dockerHost" name="dockerHost" bind:value={$settingsStore.dockerHost} placeholder="unix:///var/run/docker.sock" required />- <p class="text-xs text-muted-foreground">For local Docker: unix:///var/run/docker.sock (Unix)</p>- </div>-- <div class="pt-4 border-t mt-4">- <div class="flex items-center justify-between gap-2 mb-3">- <div class="flex items-center gap-2">- <div class="bg-green-500/10 p-2 rounded-full">- <Key class="text-green-500 size-5" />- </div>- <div>- <h3 class="font-medium">Docker Registry Credentials</h3>- <p class="text-sm text-muted-foreground">Configure access to private Docker registries</p>- </div>- </div>- <Button onclick={openCreateRegistryDialog} class="arcane-button-save">- <Plus class="size-4" /> Add Registry- </Button>- </div>-- <div class="space-y-2">- {#if !$settingsStore.registryCredentials || $settingsStore.registryCredentials.length === 0}- <div class="text-center py-8 text-muted-foreground italic border rounded-md">No registry credentials configured yet.</div>- {:else}- <UniversalTable- data={$settingsStore.registryCredentials}- columns={[- { accessorKey: 'url', header: 'Registry URL' },- { accessorKey: 'username', header: 'Username' },- { accessorKey: 'actions', header: ' ', enableSorting: false }- ]}- features={{- sorting: true,- filtering: false,- selection: false- }}- pagination={{- pageSize: 5,- pageSizeOptions: [5]- }}- sort={{- defaultSort: { id: 'url', desc: false }- }}- display={{- noResultsMessage: 'No registry credentials found.'- }}- >- {#snippet rows({ item, index })}- {#if typeof index === 'number'}- <Table.Cell class="font-medium">- {item.url || 'Default (Docker Hub)'}- </Table.Cell>- <Table.Cell>{item.username || '-'}</Table.Cell>- <Table.Cell class="text-right">- <DropdownMenu.Root>- <DropdownMenu.Trigger>- <Button variant="ghost" size="icon" class="size-8">- <Ellipsis class="size-4" />- <span class="sr-only">Open menu</span>- </Button>- </DropdownMenu.Trigger>- <DropdownMenu.Content align="end">- <DropdownMenu.Item onclick={() => openEditRegistryDialog(item, index)}>- <Pencil class="mr-2 size-4" />- Edit- </DropdownMenu.Item>- <DropdownMenu.Item onclick={() => confirmRemoveRegistry(index)} class="text-red-500 focus:text-red-700! focus:bg-destructive/10">- <Trash2 class="mr-2 size-4" />- Remove- </DropdownMenu.Item>- </DropdownMenu.Content>- </DropdownMenu.Root>- </Table.Cell>- {/if}- {/snippet}- </UniversalTable>- {/if}- </div>- </div>- </div>- </Card.Content>- </Card.Root>-- <div class="space-y-6">- <Card.Root class="border shadow-sm">- <Card.Header class="pb-3">- <div class="flex items-center gap-2">- <div class="bg-amber-500/10 p-2 rounded-full">- <RefreshCw class="text-amber-500 size-5" />- </div>- <div>- <Card.Title>Image Polling</Card.Title>- <Card.Description>Control container image polling</Card.Description>- </div>- </div>- </Card.Header>- <Card.Content class="space-y-6">- <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">- <div class="space-y-0.5">- <label for="pollingEnabledSwitch" class="text-base font-medium">Check for New Images</label>- <p class="text-sm text-muted-foreground">Periodically check for newer versions of container images</p>- </div>- <Switch- id="pollingEnabledSwitch"- name="pollingEnabled"- checked={$settingsStore.pollingEnabled}- onCheckedChange={(checked) => {- settingsStore.update((current) => ({ ...current, pollingEnabled: checked }));- }}- />- </div>-- {#if $settingsStore.pollingEnabled}- <div class="space-y-2 px-1">- <label for="pollingInterval" class="text-sm font-medium"> Polling Interval (minutes) </label>- <Input- id="pollingInterval"- type="number"- value={$settingsStore.pollingInterval}- oninput={(e: Event) =>- settingsStore.update((cur) => ({- ...cur,- pollingInterval: +(e.target as HTMLInputElement).value- }))}- min="5"- max="60"- />- <p class="text-xs text-muted-foreground">Set between 5-60 minutes.</p>- </div>-- <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">- <div class="space-y-0.5">- <Label for="autoUpdateSwitch" class="text-base font-medium">Auto Update Containers</Label>- <p class="text-sm text-muted-foreground">Automatically update containers when newer images are available</p>- </div>- <Switch- id="autoUpdateSwitch"- checked={$settingsStore.autoUpdate}- onCheckedChange={(checked) => {- settingsStore.update((current) => ({ ...current, autoUpdate: checked }));- }}- />- </div>-- {#if $settingsStore.autoUpdate}- <div class="space-y-2 mt-4">- <Label for="autoUpdateInterval" class="text-base font-medium">Auto-update check interval (minutes)</Label>- <Input- id="autoUpdateInterval"- type="number"- value={$settingsStore.autoUpdateInterval}- oninput={(e: Event) =>- settingsStore.update((cur) => ({- ...cur,- autoUpdateInterval: +(e.target as HTMLInputElement).value- }))}- min="5"- max="1440"- />- <p class="text-sm text-muted-foreground">How often Arcane will check for container and stack updates (minimum 5 minutes, maximum 24 hours)</p>- </div>- {/if}- {/if}- </Card.Content>- </Card.Root>-- <Card.Root class="border shadow-sm">- <Card.Header class="pb-3">- <div class="flex items-center gap-2">- <div class="bg-purple-500/10 p-2 rounded-full">- <ImageMinus class="text-purple-500 size-5" />- </div>- <div>- <Card.Title>Image Pruning</Card.Title>- <Card.Description>Configure image prune behavior</Card.Description>- </div>- </div>- </Card.Header>- <Card.Content class="space-y-4">- <div>- <Label for="pruneMode" class="text-base font-medium block mb-2">Prune Action Behavior</Label>- <RadioGroup.Root- value={$settingsStore.pruneMode}- onValueChange={(val) => {- settingsStore.update((current) => ({ ...current, pruneMode: val as 'all' | 'dangling' }));- }}- class="flex flex-col space-y-1"- id="pruneMode"- >- <div class="flex items-center space-x-2">- <RadioGroup.Item value="all" id="prune-all" />- <Label for="prune-all" class="font-normal">All Unused Images (like `docker image prune -a`)</Label>- </div>- <div class="flex items-center space-x-2">- <RadioGroup.Item value="dangling" id="prune-dangling" />- <Label for="prune-dangling" class="font-normal">Dangling Images Only (like `docker image prune`)</Label>- </div>- </RadioGroup.Root>- <p class="text-xs text-muted-foreground mt-2">Select which images are removed by the "Prune Unused" action on the Images page.</p>- </div>- </Card.Content>- </Card.Root>- </div>-</div>diff --git a/src/routes/settings/tabs/external-services.svelte b/src/routes/settings/tabs/external-services.sveltedeleted file mode 100644index b9d4beea8..000000000--- a/src/routes/settings/tabs/external-services.svelte+++ /dev/null@@ -1,34 +0,0 @@-<script lang="ts">- import * as Card from '$lib/components/ui/card/index.js';- import { Key } from '@lucide/svelte';- import type { PageData } from '../$types';-- let { data } = $props<{ data: PageData }>();-</script>--<div class="grid grid-cols-1 gap-6">- <div class="space-y-2">- <h2 class="text-2xl font-bold tracking-tight">External Services</h2>- <p class="text-muted-foreground">Configure connections to external services for enhanced functionality.</p>- </div>-- <Card.Root class="border shadow-sm border-dashed">- <Card.Header class="pb-3">- <div class="flex items-center gap-2">- <div class="bg-gray-500/10 p-2 rounded-full">- <Key class="text-gray-500 size-5" />- </div>- <div>- <Card.Title>Additional Services</Card.Title>- <Card.Description>More integrations will be available in future updates</Card.Description>- </div>- </div>- </Card.Header>- <Card.Content>- <div class="text-center py-8 text-muted-foreground">- <p>Future services MAY include database connections, monitoring tools, and more.</p>- <p class="text-sm mt-2">Check back for updates or suggest integrations!</p>- </div>- </Card.Content>- </Card.Root>-</div>diff --git a/src/routes/settings/tabs/rbac-settings.svelte b/src/routes/settings/tabs/rbac-settings.sveltedeleted file mode 100644index b2415019e..000000000--- a/src/routes/settings/tabs/rbac-settings.svelte+++ /dev/null@@ -1,177 +0,0 @@-<script lang="ts">- import * as Card from '$lib/components/ui/card/index.js';- import { Button } from '$lib/components/ui/button/index.js';- import { Input } from '$lib/components/ui/input/index.js';- import { Shield, Plus, Users, Settings } from '@lucide/svelte';- import type { PageData } from '../$types';- import Switch from '$lib/components/ui/switch/switch.svelte';- import { settingsStore } from '$lib/stores/settings-store';-- let { data } = $props<{ data: PageData }>();-- const roles = [- {- id: 1,- name: 'Admin',- description: 'Full system access',- permissions: ['containers:manage', 'stacks:manage', 'volumes:manage', 'networks:manage', 'settings:manage', 'users:manage']- },- {- id: 2,- name: 'User',- description: 'Container and stack operations',- permissions: ['containers:view', 'containers:manage', 'stacks:view', 'stacks:manage', 'volumes:view', 'networks:view']- },- {- id: 3,- name: 'Viewer',- description: 'Read-only access',- permissions: ['containers:view', 'stacks:view', 'volumes:view', 'networks:view']- }- ];-- // Available permissions categories- const permissionCategories = [- {- name: 'Containers',- permissions: ['containers:view', 'containers:manage', 'containers:deploy']- },- {- name: 'Stacks',- permissions: ['stacks:view', 'stacks:manage', 'stacks:deploy']- },- {- name: 'Volumes',- permissions: ['volumes:view', 'volumes:manage', 'volumes:create']- },- {- name: 'Networks',- permissions: ['networks:view', 'networks:manage', 'networks:create']- },- {- name: 'Settings',- permissions: ['settings:view', 'settings:manage']- },- {- name: 'Users',- permissions: ['users:view', 'users:manage', 'users:create']- }- ];-- let selectedRole = $state(roles[0]);-</script>--<div class="mb-6">- <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">- <div class="space-y-0.5">- <label for="rbacEnabledSwitch" class="text-base font-medium">Enable Role-Based Access Control</label>- <p class="text-sm text-muted-foreground">Control user permissions with customizable roles</p>- </div>- <Switch- id="rbacEnabledSwitch"- name="rbacEnabled"- checked={$settingsStore.auth?.rbacEnabled}- onCheckedChange={(checked) => {- settingsStore.update((current) => ({- ...current,- auth: {- ...current.auth,- rbacEnabled: checked- }- }));- }}- />- </div>-</div>--<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">- <div class="lg:col-span-1">- <Card.Root class="border shadow-sm h-full">- <Card.Header class="pb-3">- <div class="flex items-center justify-between">- <div class="flex items-center gap-2">- <div class="bg-blue-500/10 p-2 rounded-full">- <Users class="text-blue-500 size-5" />- </div>- <Card.Title>Roles</Card.Title>- </div>- <Button variant="outline" size="sm">- <Plus class="mr-1 size-4" /> Add- </Button>- </div>- </Card.Header>- <Card.Content>- <div class="space-y-2">- {#each roles as role (role.id)}- <button class="w-full text-left p-3 rounded-md border transition-colors flex items-center justify-between {selectedRole.id === role.id ? 'bg-primary text-primary-foreground border-primary' : 'hover:bg-muted/50'}" onclick={() => (selectedRole = role)}>- <div>- <div class="font-medium">{role.name}</div>- <div class="text-xs {selectedRole.id === role.id ? 'text-primary-foreground/90' : 'text-muted-foreground'}">- {role.description}- </div>- </div>- <Shield class="opacity-70 size-4" />- </button>- {/each}- </div>- </Card.Content>- </Card.Root>- </div>-- <div class="lg:col-span-2">- <Card.Root class="border shadow-sm">- <Card.Header class="pb-3">- <div class="flex items-center justify-between">- <div class="flex items-center gap-2">- <div class="bg-purple-500/10 p-2 rounded-full">- <Settings class="text-purple-500 size-5" />- </div>- <div>- <Card.Title>Role: {selectedRole.name}</Card.Title>- <Card.Description>{selectedRole.description}</Card.Description>- </div>- </div>- <div class="space-x-2">- <Button variant="outline" size="sm">Delete</Button>- <Button size="sm">Save Changes</Button>- </div>- </div>- </Card.Header>- <Card.Content>- <div class="space-y-6">- <!-- Role Info -->- <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">- <div class="space-y-2">- <label for="roleName" class="text-sm font-medium">Role Name</label>- <Input id="roleName" name="roleName" value={selectedRole.name} placeholder="Enter role name" />- </div>- <div class="space-y-2">- <label for="roleDescription" class="text-sm font-medium">Description</label>- <Input id="roleDescription" name="roleDescription" value={selectedRole.description} placeholder="Brief description" />- </div>- </div>-- <!-- Permissions -->- <div>- <h3 class="text-sm font-medium mb-3">Permissions</h3>- <div class="border rounded-md divide-y">- {#each permissionCategories as category (category.name)}- <div class="p-3">- <h4 class="font-medium mb-2">{category.name}</h4>- <div class="grid grid-cols-1 sm:grid-cols-2 gap-2">- {#each category.permissions as permission (permission)}- <label class="flex items-center space-x-2 text-sm">- <input type="checkbox" class="rounded border-gray-300 text-primary focus:ring-primary" checked={selectedRole.permissions.includes(permission)} />- <span>{permission.split(':')[1]}</span>- </label>- {/each}- </div>- </div>- {/each}- </div>- </div>- </div>- </Card.Content>- </Card.Root>- </div>-</div>diff --git a/src/routes/settings/tabs/user-management.svelte b/src/routes/settings/tabs/user-management.sveltedeleted file mode 100644index c45bbae4c..000000000--- a/src/routes/settings/tabs/user-management.svelte+++ /dev/null@@ -1,198 +0,0 @@-<script lang="ts">- import * as Card from '$lib/components/ui/card/index.js';- import { Button } from '$lib/components/ui/button/index.js';- import { toast } from 'svelte-sonner';- import { UserPlus, UserCheck, Ellipsis, Pencil, UserX } from '@lucide/svelte';- import type { PageData } from '../$types';- import UniversalTable from '$lib/components/universal-table.svelte';- import type { User } from '$lib/types/user.type';- import UserFormDialog from '$lib/components/dialogs/user-form-dialog.svelte';- import * as Table from '$lib/components/ui/table';- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';- import { handleApiResultWithCallbacks } from '$lib/utils/api.util';- import { tryCatch } from '$lib/utils/try-catch';- import UserAPIService from '$lib/services/api/user-api-service';- import { invalidateAll } from '$app/navigation';- import { openConfirmDialog } from '$lib/components/confirm-dialog';- import StatusBadge from '$lib/components/badges/status-badge.svelte';-- let { data } = $props<{ data: PageData }>();-- const userApi = new UserAPIService();-- let userPageStates = $state({- users: <User[]>data.users,- isUserDialogOpen: false,- userToEdit: <User | null>null- });-- let isLoading = $state({- saving: false- });-- let userDialogRef: UserFormDialog | null = $state(null);-- $effect(() => {- userPageStates.users = data.users;- });-- const roles = [- { id: 'admin', name: 'Administrator' },- { id: 'user', name: 'Standard User' },- { id: 'viewer', name: 'Viewer (read-only)' }- ];-- function openCreateUserDialog() {- userPageStates.userToEdit = null;- userPageStates.isUserDialogOpen = true;- }-- function openEditUserDialog(user: User) {- userPageStates.userToEdit = user;- userPageStates.isUserDialogOpen = true;- }-- async function handleDialogSubmit({ user: userData, isEditMode, userId }: { user: Partial<User> & { password?: string }; isEditMode: boolean; userId?: string }) {- isLoading.saving = true;-- handleApiResultWithCallbacks({- result: await tryCatch(isEditMode ? userApi.update(userId || '', userData as User) : userApi.create(userData as User)),- message: isEditMode ? 'Error Updating User' : 'Error Creating User',- setLoadingState: (value) => (isLoading.saving = value),- onSuccess: async () => {- userPageStates.isUserDialogOpen = false;- toast.success(isEditMode ? 'User Updated Successfully' : 'User Created Successfully');- await invalidateAll();- isLoading.saving = false;- }- });- }-- async function handleRemoveUser(userId: string) {- openConfirmDialog({- title: 'Delete Container',- message: 'Are you sure you want to delete this container? This action cannot be undone.',- confirm: {- label: 'Delete',- destructive: true,- action: async () => {- handleApiResultWithCallbacks({- result: await tryCatch(userApi.delete(userId)),- message: 'Failed to Delete User',- setLoadingState: (value) => (isLoading.saving = value),- onSuccess: async () => {- toast.success('User Deleted Successfully.');- await invalidateAll();- }- });- }- }- });- }-</script>--<UserFormDialog bind:open={userPageStates.isUserDialogOpen} bind:userToEdit={userPageStates.userToEdit} {roles} onSubmit={handleDialogSubmit} bind:this={userDialogRef} isLoading={isLoading.saving} />--<div class="grid grid-cols-1 gap-6 h-full">- <!-- User List Card -->- <Card.Root class="border shadow-sm flex flex-col">- <Card.Header class="pb-3 flex flex-row items-center justify-between space-y-0">- <div class="flex items-center gap-2">- <div class="bg-blue-500/10 p-2 rounded-full">- <UserCheck class="text-blue-500 size-5" />- </div>- <div>- <Card.Title>User Accounts</Card.Title>- <Card.Description>Manage local user accounts</Card.Description>- </div>- </div>- <Button class="arcane-button-save" onclick={openCreateUserDialog}>- <UserPlus class="size-4" />- Create User- </Button>- </Card.Header>- <Card.Content class="flex-1 flex flex-col">- {#if userPageStates.users.length > 0}- <div class="flex-1 flex flex-col h-full">- <UniversalTable- data={userPageStates.users}- columns={[- { accessorKey: 'user', header: 'User' },- { accessorKey: 'email', header: 'Email' },- { accessorKey: 'roles', header: 'Roles' },- { accessorKey: 'source', header: 'Source', enableSorting: false },- { accessorKey: 'actions', header: ' ' }- ]}- features={{- sorting: true,- filtering: true,- selection: false- }}- pagination={{- pageSize: 10,- pageSizeOptions: [5, 10, 15, 20]- }}- display={{- filterPlaceholder: 'Filter users...',- noResultsMessage: 'No users found'- }}- sort={{- defaultSort: {- id: 'user',- desc: false- }- }}- >- {#snippet rows({ item })}- <Table.Cell>- {item.displayName}- </Table.Cell>- <Table.Cell>- <div class="flex items-center gap-1.5">- {item.email}- </div>- </Table.Cell>- <Table.Cell>- <div class="flex flex-wrap">- {#each item.roles as role (role)}- {@const isAdmin = role === 'admin'}- <StatusBadge text={isAdmin ? 'Admin' : 'User'} variant={isAdmin ? 'amber' : 'blue'} />- {/each}- </div>- </Table.Cell>- <Table.Cell>- <StatusBadge text={item.oidcSubjectId ? 'OIDC' : 'Local'} variant={item.oidcSubjectId ? 'blue' : 'purple'} />- </Table.Cell>- <Table.Cell>- <DropdownMenu.Root>- <DropdownMenu.Trigger>- <Button variant="ghost" size="icon" class="size-8">- <Ellipsis class="size-4" />- <span class="sr-only">Open menu</span>- </Button>- </DropdownMenu.Trigger>- <DropdownMenu.Content align="end">- <DropdownMenu.Group>- {#if !item.oidcSubjectId}- <DropdownMenu.Item onclick={() => openEditUserDialog(item)}>- <Pencil class="size-4" />- Edit- </DropdownMenu.Item>- {/if}- <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleRemoveUser(item.id)}>- <UserX class="size-4" />- Remove User- </DropdownMenu.Item>- </DropdownMenu.Group>- </DropdownMenu.Content>- </DropdownMenu.Root>- </Table.Cell>- {/snippet}- </UniversalTable>- </div>- {:else}- <div class="text-center py-8 text-muted-foreground italic">No local users found</div>- {/if}- </Card.Content>- </Card.Root>-</div>diff --git a/src/routes/settings/users/+page.server.ts b/src/routes/settings/users/+page.server.tsnew file mode 100644index 000000000..8f2748856--- /dev/null+++ b/src/routes/settings/users/+page.server.ts@@ -0,0 +1,26 @@+import type { PageServerLoad } from './$types';+import UserAPIService from '$lib/services/api/user-api-service';+import { listUsers } from '$lib/services/user-service';++export const load: PageServerLoad = async ({ cookies }) => {+ try {+ const userApi = new UserAPIService();++ const users = await listUsers();++ const sanitizedUsers = users.map((user) => {+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ const { passwordHash: _passwordHash, ...rest } = user;+ return rest;+ });++ return {+ users: users || []+ };+ } catch (error) {+ console.error('Failed to load users:', error);+ return {+ users: []+ };+ }+};diff --git a/src/routes/settings/users/+page.svelte b/src/routes/settings/users/+page.sveltenew file mode 100644index 000000000..a4aa6f81b--- /dev/null+++ b/src/routes/settings/users/+page.svelte@@ -0,0 +1,209 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card/index.js';+ import { Button } from '$lib/components/ui/button/index.js';+ import { toast } from 'svelte-sonner';+ import { UserPlus, UserCheck, Ellipsis, Pencil, UserX } from '@lucide/svelte';+ import type { PageData } from './$types';+ import UniversalTable from '$lib/components/universal-table.svelte';+ import type { User } from '$lib/types/user.type';+ import UserFormDialog from '$lib/components/dialogs/user-form-dialog.svelte';+ import * as Table from '$lib/components/ui/table';+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { tryCatch } from '$lib/utils/try-catch';+ import UserAPIService from '$lib/services/api/user-api-service';+ import { invalidateAll } from '$app/navigation';+ import { openConfirmDialog } from '$lib/components/confirm-dialog';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';++ let { data }: { data: PageData } = $props();++ const userApi = new UserAPIService();++ let userPageStates = $state({+ users: <User[]>data.users,+ isUserDialogOpen: false,+ userToEdit: <User | null>null+ });++ let isLoading = $state({+ saving: false+ });++ let userDialogRef: UserFormDialog | null = $state(null);++ $effect(() => {+ userPageStates.users = data.users;+ });++ const roles = [+ { id: 'admin', name: 'Administrator' },+ { id: 'user', name: 'Standard User' },+ { id: 'viewer', name: 'Viewer (read-only)' }+ ];++ function openCreateUserDialog() {+ userPageStates.userToEdit = null;+ userPageStates.isUserDialogOpen = true;+ }++ function openEditUserDialog(user: User) {+ userPageStates.userToEdit = user;+ userPageStates.isUserDialogOpen = true;+ }++ async function handleDialogSubmit({ user: userData, isEditMode, userId }: { user: Partial<User> & { password?: string }; isEditMode: boolean; userId?: string }) {+ isLoading.saving = true;++ handleApiResultWithCallbacks({+ result: await tryCatch(isEditMode ? userApi.update(userId || '', userData as User) : userApi.create(userData as User)),+ message: isEditMode ? 'Error Updating User' : 'Error Creating User',+ setLoadingState: (value) => (isLoading.saving = value),+ onSuccess: async () => {+ userPageStates.isUserDialogOpen = false;+ toast.success(isEditMode ? 'User Updated Successfully' : 'User Created Successfully');+ await invalidateAll();+ isLoading.saving = false;+ }+ });+ }++ async function handleRemoveUser(userId: string) {+ openConfirmDialog({+ title: 'Delete User',+ message: 'Are you sure you want to delete this user? This action cannot be undone.',+ confirm: {+ label: 'Delete',+ destructive: true,+ action: async () => {+ handleApiResultWithCallbacks({+ result: await tryCatch(userApi.delete(userId)),+ message: 'Failed to Delete User',+ setLoadingState: (value) => (isLoading.saving = value),+ onSuccess: async () => {+ toast.success('User Deleted Successfully.');+ await invalidateAll();+ }+ });+ }+ }+ });+ }+</script>++<svelte:head>+ <title>User Management - Arcane</title>+</svelte:head>++<UserFormDialog bind:open={userPageStates.isUserDialogOpen} bind:userToEdit={userPageStates.userToEdit} {roles} onSubmit={handleDialogSubmit} bind:this={userDialogRef} isLoading={isLoading.saving} />++<div class="space-y-6">+ <div>+ <h1 class="text-3xl font-bold tracking-tight">User Management</h1>+ <p class="text-sm text-muted-foreground mt-1">Manage user accounts and permissions</p>+ </div>++ <div class="grid grid-cols-1 gap-6 h-full">+ <!-- User List Card -->+ <Card.Root class="border shadow-sm flex flex-col">+ <Card.Header class="pb-3 flex flex-row items-center justify-between space-y-0">+ <div class="flex items-center gap-2">+ <div class="bg-blue-500/10 p-2 rounded-full">+ <UserCheck class="text-blue-500 size-5" />+ </div>+ <div>+ <Card.Title>User Accounts</Card.Title>+ <Card.Description>Manage local user accounts</Card.Description>+ </div>+ </div>+ <Button class="arcane-button-save" onclick={openCreateUserDialog}>+ <UserPlus class="size-4" />+ Create User+ </Button>+ </Card.Header>+ <Card.Content class="flex-1 flex flex-col">+ {#if userPageStates.users.length > 0}+ <div class="flex-1 flex flex-col h-full">+ <UniversalTable+ data={userPageStates.users}+ columns={[+ { accessorKey: 'user', header: 'User' },+ { accessorKey: 'email', header: 'Email' },+ { accessorKey: 'roles', header: 'Roles' },+ { accessorKey: 'source', header: 'Source', enableSorting: false },+ { accessorKey: 'actions', header: ' ' }+ ]}+ features={{+ sorting: true,+ filtering: true,+ selection: false+ }}+ pagination={{+ pageSize: 10,+ pageSizeOptions: [5, 10, 15, 20]+ }}+ display={{+ filterPlaceholder: 'Filter users...',+ noResultsMessage: 'No users found'+ }}+ sort={{+ defaultSort: {+ id: 'user',+ desc: false+ }+ }}+ >+ {#snippet rows({ item })}+ <Table.Cell>+ {item.displayName}+ </Table.Cell>+ <Table.Cell>+ <div class="flex items-center gap-1.5">+ {item.email}+ </div>+ </Table.Cell>+ <Table.Cell>+ <div class="flex flex-wrap">+ {#each item.roles as role (role)}+ {@const isAdmin = role === 'admin'}+ <StatusBadge text={isAdmin ? 'Admin' : 'User'} variant={isAdmin ? 'amber' : 'blue'} />+ {/each}+ </div>+ </Table.Cell>+ <Table.Cell>+ <StatusBadge text={item.oidcSubjectId ? 'OIDC' : 'Local'} variant={item.oidcSubjectId ? 'blue' : 'purple'} />+ </Table.Cell>+ <Table.Cell>+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ <Button variant="ghost" size="icon" class="size-8">+ <Ellipsis class="size-4" />+ <span class="sr-only">Open menu</span>+ </Button>+ </DropdownMenu.Trigger>+ <DropdownMenu.Content align="end">+ <DropdownMenu.Group>+ {#if !item.oidcSubjectId}+ <DropdownMenu.Item onclick={() => openEditUserDialog(item)}>+ <Pencil class="size-4" />+ Edit+ </DropdownMenu.Item>+ {/if}+ <DropdownMenu.Item class="text-red-500 focus:text-red-700!" onclick={() => handleRemoveUser(item.id)}>+ <UserX class="size-4" />+ Remove User+ </DropdownMenu.Item>+ </DropdownMenu.Group>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ </Table.Cell>+ {/snippet}+ </UniversalTable>+ </div>+ {:else}+ <div class="text-center py-8 text-muted-foreground italic">No local users found</div>+ {/if}+ </Card.Content>+ </Card.Root>+ </div>+</div>diff --git a/tests/.auth/login.json b/tests/.auth/login.jsonindex 6c7f33850..c702524cb 100644--- a/tests/.auth/login.json+++ b/tests/.auth/login.json@@ -2,10 +2,10 @@"cookies": [{"name": "kit.session",- "value": "34c4e6426282ba6a47fe970a6f0426cad1a56b60e1d23ad8b3189735e382bdb6d8c879b86246f19b62c8dfd26a54fbe8fb044aee7fa8fa99f28fcff23d99e30f19df1e98356ac1abe4bd7f3c81359f7d01f010f82130dfda6b3d4660bf93d755ce99625d4aa1b3812917de1fcd439ced20ac8be6f183a62f8c1c333b41655372988d8e514bc74e174bb8fe6bd10a73e6aced4423608e501c38fc67b82f31702185de1e772e44a90ed057e871dac58029ba32b06bb387a2f7f403a055d7%26id%3D1",+ "value": "91db7b852496b39ef73bd81573df7c55fad3696257b160cf2d2f98e876a42622bc423a1130e065c8b4e0a7048fc19b489da9a44900c1e95696ec0745fc1e6a08d7232f32e19655db9509540bdace6084620291c51668c51bfb0910b6fe079df639d2feca20f64711ca8f1503d093f82637c0329722212cf9e74c709a2e8b61dec2f97cc4f4fbacee80ff8a8b5b76affc8891b7b321fec72f837507f10b99d0275f1bad678fc9002f59729d2ad3c747a3b83516c56b0e820c7de5f77604%26id%3D1","domain": "localhost","path": "/",- "expires": 1782498902.815969,+ "expires": 1782584367.292194,"httpOnly": true,"secure": false,"sameSite": "Lax"diff --git a/tests/networks.spec.ts b/tests/networks.spec.tsindex 46c81196c..580d06516 100644--- a/tests/networks.spec.ts+++ b/tests/networks.spec.ts@@ -31,7 +31,7 @@ test.describe('Network Management Page', () => {await page.getByRole('button', { name: 'Create Network' }).click();const dialogTitle = page.getByTestId('create-network-dialog-header');await expect(dialogTitle).toBeVisible({ timeout: 10000 });- await expect(page.getByLabel('Name')).toBeVisible();+ await expect(page.getByRole('textbox', { name: 'Name' })).toBeVisible();await page.getByRole('button', { name: 'Cancel' }).click();await expect(dialogTitle).not.toBeVisible({ timeout: 5000 });});diff --git a/tests/volumes.spec.ts b/tests/volumes.spec.tsnew file mode 100644index 000000000..1cf3ba281--- /dev/null+++ b/tests/volumes.spec.ts@@ -0,0 +1,224 @@+import { test, expect, type Page } from '@playwright/test';++async function fetchVolumesWithRetry(page: Page, maxRetries = 3): Promise<any[]> {+ let retries = 0;+ while (retries < maxRetries) {+ try {+ const response = await page.request.get('/api/volumes');+ const volumes = await response.json();+ console.log(`Successfully fetched ${volumes.length} volumes on attempt ${retries + 1}`);+ return volumes;+ } catch (error) {+ retries++;+ console.log(`Attempt ${retries} failed, ${maxRetries - retries} retries left`);+ if (retries >= maxRetries) throw error;+ // Wait before retrying+ await new Promise((resolve) => setTimeout(resolve, 1000));+ }+ }+ return [];+}++let realVolumes: any[] = [];++test.beforeEach(async ({ page }) => {+ await page.goto('/volumes');+ await page.waitForLoadState('networkidle');++ try {+ realVolumes = await fetchVolumesWithRetry(page);+ } catch (error) {+ console.warn('Could not fetch volumes after multiple retries:', error);+ // Use default volumes if all retries fail+ realVolumes = [];+ }++ console.log(`Found ${realVolumes.length} real volumes for testing`);+});++test.describe('Volumes Page', () => {+ test('should display the volumes page title and description', async ({ page }) => {+ await page.goto('/volumes');++ await expect(page.getByRole('heading', { name: 'Volumes', level: 1 })).toBeVisible();+ await expect(page.getByText('Manage persistent data storage for containers').first()).toBeVisible();+ });++ test('should display stats cards with correct counts', async ({ page }) => {+ await page.goto('/volumes');++ await expect(page.locator('p:has-text("Total Volumes") + p')).toHaveText(realVolumes.length.toString());+ await expect(page.locator('p:has-text("Default Driver") + p')).toHaveText('local');+ });++ test('should display the volume table when volumes exist', async ({ page }) => {+ await page.goto('/volumes');+ await page.waitForLoadState('networkidle');++ if (realVolumes.length > 0) {+ await expect(page.getByText('Volume List')).toBeVisible();+ await expect(page.locator('table')).toBeVisible();+ } else {+ // Should show empty state instead+ await expect(page.getByText('No volumes found')).toBeVisible();+ }+ });++ test('should open the Create Volume dialog', async ({ page }) => {+ await page.goto('/volumes');+ await page.waitForLoadState('networkidle');++ await page.locator('button:has-text("Create Volume")').first().click();+ // Fix the dialog title selector - looking at the create-volume-dialog.svelte+ await expect(page.getByRole('dialog')).toBeVisible();+ await expect(page.getByText('Create New Volume')).toBeVisible();+ });++ test('should display filter dropdown and allow filtering', async ({ page }) => {+ await page.goto('/volumes');+ await page.waitForLoadState('networkidle');++ // Open filter dropdown+ await page.locator('button:has-text("Filter")').click();+ await expect(page.getByText('Volume Usage')).toBeVisible();+ await expect(page.getByText('Show Used Volumes')).toBeVisible();+ await expect(page.getByText('Show Unused Volumes')).toBeVisible();+ });++ test('should navigate to volume details on inspect click', async ({ page }) => {+ test.skip(!realVolumes.length, 'No volumes available for inspect test');++ await page.goto('/volumes');+ await page.waitForLoadState('networkidle');++ const firstRow = page.locator('tbody tr').first();+ await firstRow.getByRole('button', { name: 'Open menu' }).click();+ await page.getByRole('menuitem', { name: 'Inspect' }).click();++ // Check that we navigated to the volume details page+ await expect(page).toHaveURL(new RegExp(`/volumes/.+`));+ });++ test('should call remove API on row action delete click and confirmation', async ({ page }) => {+ test.skip(!realVolumes.length, 'No volumes available for remove API test');++ await page.goto('/volumes');+ await page.waitForLoadState('networkidle');++ // Find a volume that's not in use (if any)+ const unusedVolume = realVolumes.find((vol) => !vol.inUse);+ test.skip(!unusedVolume, 'No unused volumes available for deletion test');++ const volumeRow = page.locator(`tr:has-text("${unusedVolume.Name}")`);+ await volumeRow.getByRole('button', { name: 'Open menu' }).click();+ await page.getByRole('menuitem', { name: 'Delete' }).click();++ // Wait for confirmation dialog+ await expect(page.getByRole('heading', { name: 'Delete Volume' })).toBeVisible();++ const removePromise = page.waitForRequest((req) => req.url().includes(`/api/volumes/${unusedVolume.Name}`) && req.method() === 'DELETE');++ await page.locator('button:has-text("Delete")').click();+ const removeRequest = await removePromise;++ expect(removeRequest).toBeTruthy();++ await expect(page.locator('li[data-sonner-toast][data-type="success"] div[data-title]')).toBeVisible();+ });++ test('should create volume via dialog', async ({ page }) => {+ await page.goto('/volumes');+ await page.waitForLoadState('networkidle');++ await page.locator('button:has-text("Create Volume")').first().click();+ await expect(page.getByRole('dialog')).toBeVisible();++ const volumeName = `test-volume-${Date.now()}`;+ await page.locator('input[id="volume-name"]').fill(volumeName);++ const createPromise = page.waitForRequest((req) => req.url().includes('/api/volumes') && req.method() === 'POST');++ await page.getByRole('dialog').locator('button:has-text("Create Volume")').click();+ const createRequest = await createPromise;++ expect(createRequest).toBeTruthy();+ const postData = createRequest.postDataJSON();+ expect(postData.Name).toBe(volumeName);++ await expect(page.locator(`li[data-sonner-toast][data-type="success"] div[data-title]:has-text("created successfully")`)).toBeVisible();+ });++ test('should disable delete action for volumes in use', async ({ page }) => {+ test.skip(!realVolumes.length, 'No volumes available for in-use test');++ const volumeInUse = realVolumes.find((vol) => vol.inUse);+ test.skip(!volumeInUse, 'No volumes in use found for test');++ await page.goto('/volumes');+ await page.waitForLoadState('networkidle');++ const volumeRow = page.locator(`tr:has-text("${volumeInUse.Name}")`);+ await volumeRow.getByRole('button', { name: 'Open menu' }).click();++ // Check that delete button is disabled+ const deleteButton = page.getByRole('menuitem', { name: 'Delete' });+ await expect(deleteButton).toBeDisabled();+ });++ test('should display correct status badges for volume usage', async ({ page }) => {+ test.skip(!realVolumes.length, 'No volumes available for status badge test');++ await page.goto('/volumes');+ await page.waitForLoadState('networkidle');++ // Check for "In Use" and "Unused" badges+ const usedVolumes = realVolumes.filter((vol) => vol.inUse);+ const unusedVolumes = realVolumes.filter((vol) => !vol.inUse);++ if (usedVolumes.length > 0) {+ await expect(page.locator('text="In Use"').first()).toBeVisible();+ }++ if (unusedVolumes.length > 0) {+ await expect(page.locator('text="Unused"').first()).toBeVisible();+ }+ });++ test('should filter volumes by usage status', async ({ page }) => {+ test.skip(!realVolumes.length, 'No volumes available for filter test');++ const usedVolumes = realVolumes.filter((vol) => vol.inUse);+ const unusedVolumes = realVolumes.filter((vol) => !vol.inUse);++ // Skip if we don't have both types+ test.skip(usedVolumes.length === 0 || unusedVolumes.length === 0, 'Need both used and unused volumes for filter test');++ await page.goto('/volumes');+ await page.waitForLoadState('networkidle');++ // Open filter dropdown+ await page.locator('button:has-text("Filter")').click();++ // Uncheck "Show Used Volumes"+ await page.getByText('Show Used Volumes').click();++ // Close dropdown+ await page.locator('button:has-text("Filter")').click();++ // Should only show unused volumes+ await expect(page.locator('tbody tr')).toHaveCount(unusedVolumes.length);++ // Open filter dropdown again+ await page.locator('button:has-text("Filter")').click();++ // Check "Show Used Volumes" and uncheck "Show Unused Volumes"+ await page.getByText('Show Used Volumes').click();+ await page.getByText('Show Unused Volumes').click();++ // Close dropdown+ await page.locator('button:has-text("Filter")').click();++ // Should only show used volumes+ await expect(page.locator('tbody tr')).toHaveCount(usedVolumes.length);+ });+});