Skip to content

Modern Docker Management, Designed for Everyone

refactor: cleanup duplicated frontend code (#2834)

Kyle Mendell2b6857757ec4
diff --git a/backend/.air.toml b/backend/.air.toml
index 3abb25e9d..90ec24640 100644
--- a/backend/.air.toml
+++ b/backend/.air.toml
@@ -4,8 +4,8 @@ tmp_dir = ".bin"
env_files = [".env"]
[build]
- #cmd = "CGO_ENABLED=1 go build -tags 'exclude_frontend,buildables' -ldflags='-buildid= -X github.com/getarcaneapp/arcane/backend/buildables.EnabledFeatures=autologin' -o ./.bin/arcane ./cmd"
- cmd = "CGO_ENABLED=1 go build -tags 'exclude_frontend' -ldflags='-buildid=' -o ./.bin/arcane ./cmd"
+ #cmd = "CGO_ENABLED=1 go build -tags 'exclude_frontend,buildables' -ldflags='-X github.com/getarcaneapp/arcane/backend/buildables.EnabledFeatures=autologin' -o ./.bin/arcane ./cmd"
+ cmd = "CGO_ENABLED=1 go build -tags 'exclude_frontend' -o ./.bin/arcane ./cmd"
bin = "./.bin/arcane"
entrypoint = ["./.bin/arcane"]
include_ext = ["go", "tpl", "tmpl", "html"]
diff --git a/frontend/.fallowrc.json b/frontend/.fallowrc.json
new file mode 100644
index 000000000..4679cfa36
--- /dev/null
+++ b/frontend/.fallowrc.json
@@ -0,0 +1,22 @@
+{
+ "$schema": "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json",
+ "entry": [
+ "src/routes/**/*.{svelte,ts,js}",
+ "src/hooks.*.ts",
+ "src/lib/paraglide/messages/_index.js",
+ "src/lib/index.ts",
+ "src/lib/components/**/index.ts"
+ ],
+ "ignorePatterns": [
+ "src/lib/paraglide/server.js",
+ "src/lib/paraglide/runtime.js",
+ "src/lib/paraglide/registry.js",
+ "email-templates/**",
+ "tests/**"
+ ],
+ "ignoreDependencies": ["@iconify/json", "paneforge", "svelte-toolbelt", "isomorphic-dompurify", "tw-animate-css"],
+ "ignoreExportsUsedInFile": {
+ "type": true,
+ "interface": true
+ }
+}
diff --git a/frontend/knip.json b/frontend/knip.json
deleted file mode 100644
index 92143c49c..000000000
--- a/frontend/knip.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "$schema": "https://unpkg.com/knip@5/schema.json",
- "entry": [
- "src/routes/**/*.{svelte,ts,js}",
- "src/hooks.*.ts",
- "src/lib/paraglide/messages/_index.js",
- "src/lib/index.ts",
- "src/lib/components/**/index.ts"
- ],
- "project": ["src/**/*.{svelte,ts,js}"],
- "ignore": ["src/lib/paraglide/server.js", "src/lib/paraglide/runtime.js", "src/lib/paraglide/registry.js"],
- "ignoreDependencies": ["@iconify/json", "paneforge", "svelte-toolbelt", "isomorphic-dompurify", "tw-animate-css"],
- "ignoreExportsUsedInFile": {
- "interface": true,
- "type": true
- },
- "ignoreIssues": {
- "src/lib/components/ui/**/index.ts": ["exports"],
- "src/lib/components/**/index.ts": ["exports"],
- "src/lib/services/**/*.ts": ["exports"],
- "src/lib/stores/**/*.ts": ["exports"],
- "src/lib/utils/**/*.ts": ["exports"],
- "src/lib/layouts/**/*.ts": ["exports"],
- "src/lib/config/**/*.ts": ["exports"],
- "src/lib/hooks/**/*.ts": ["exports"]
- },
- "tags": ["-lintignore"]
-}
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 9b97e6d5f..bc73bb54b 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -309,6 +309,7 @@
"container_redeploy_success": "Container redeployed successfully.",
"container_redeploy_failed": "Failed to redeploy container",
"confirm_remove_project_files": "Remove project files",
+ "confirm_remove_project_files_warning": "This will remove the project's files from disk.",
"confirm_remove_volumes_warning": "Remove volumes (Warning: Data will be lost)",
"_comment_common_ui": "=== COMMON - UI COMPONENTS ===",
"common_details_title": "{resource} Details",
@@ -1650,8 +1651,10 @@
"customize_search_results": "Search Results for \"{query}\"",
"customize_result": "result",
"customize_results": "results",
+ "customize_searching": "Searching...",
"customize_no_options": "No customization options found",
"customize_try_adjusting": "Try adjusting your search terms or browse categories above.",
+ "customize_clear_search": "Clear search",
"customize_available_options": "Available Options:",
"customize_button": "Customize",
"customize_more": "more",
diff --git a/frontend/package.json b/frontend/package.json
index 6b87868ec..f28f0cd0a 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,82 +1,82 @@
{
- "name": "arcane-frontend",
- "private": true,
- "version": "1.20.0",
- "type": "module",
- "scripts": {
- "dev": "vite dev --port 3000 --host",
- "build": "vite build",
- "preview": "vite preview --port 3000",
- "check": "svelte-kit sync && svelte-check-rs --tsconfig ./tsconfig.json",
- "format": "prettier --write ./src",
- "format:check": "prettier --check ./src",
- "check:watch": "svelte-kit sync && svelte-check-rs --tsconfig ./tsconfig.json --watch",
- "knip": "knip --no-config-hints"
- },
- "dependencies": {
- "@codemirror/autocomplete": "^6.20.2",
- "@codemirror/lang-yaml": "^6.1.3",
- "@codemirror/language": "^6.12.3",
- "@codemirror/legacy-modes": "^6.5.3",
- "@codemirror/lint": "^6.9.6",
- "@codemirror/merge": "^6.12.1",
- "@codemirror/state": "^6.6.0",
- "@codemirror/view": "^6.43.0",
- "@fontsource-variable/geist-mono": "^5.2.8",
- "@fontsource-variable/montserrat": "^5.2.8",
- "@lezer/highlight": "^1.2.3",
- "@sveltejs/adapter-static": "^3.0.10",
- "@sveltejs/kit": "^2.61.1",
- "@tanstack/svelte-query": "^6.1.33",
- "@tanstack/table-core": "^8.21.3",
- "@uiw/codemirror-themes": "^4.25.10",
- "@xterm/addon-fit": "^0.11.0",
- "@xterm/xterm": "^6.0.0",
- "@xyflow/svelte": "^1.6.0",
- "ajv": "^8.20.0",
- "ansi-to-html": "^0.7.2",
- "date-fns": "^4.4.0",
- "embla-carousel-svelte": "^8.6.0",
- "ky": "^2.0.2",
- "marked": "^18.0.4",
- "prettier": "^3.8.3",
- "prettier-plugin-svelte": "^4.1.0",
- "prettier-plugin-tailwindcss": "^0.8.0",
- "svelte": "^5.56.1",
- "svelte-codemirror-editor": "^2.1.0",
- "yaml": "^2.9.0"
- },
- "devDependencies": {
- "@iconify/json": "^2.2.482",
- "@inlang/paraglide-js": "2.18.1",
- "@internationalized/date": "^3.12.2",
- "@prettier/plugin-oxc": "^0.1.4",
- "@sveltejs/vite-plugin-svelte": "^7.1.2",
- "@tailwindcss/vite": "^4.3.0",
- "@tanstack/svelte-query-devtools": "^6.1.33",
- "@types/node": "^25.9.1",
- "@typescript/native-preview": "7.0.0-dev.20260602.1",
- "bits-ui": "^2.18.1",
- "clsx": "^2.1.1",
- "formsnap": "^2.0.1",
- "isomorphic-dompurify": "^3.15.0",
- "knip": "^6.15.0",
- "mode-watcher": "^1.1.0",
- "paneforge": "^1.0.2",
- "runed": "^0.37.1",
- "svelte-check-rs": "^0.9.19",
- "svelte-sonner": "^1.1.1",
- "svelte-toolbelt": "^0.10.6",
- "sveltekit-superforms": "^2.30.1",
- "tailwind-merge": "^3.6.0",
- "tailwind-variants": "^3.2.2",
- "tailwindcss": "^4.3.0",
- "tsx": "^4.22.4",
- "tw-animate-css": "^1.4.0",
- "typescript": "^6.0.3",
- "unplugin-icons": "^23.0.1",
- "vaul-svelte": "1.0.0-next.7",
- "vite": "^8.0.16",
- "zod": "^4.4.3"
- }
+ "name": "arcane-frontend",
+ "private": true,
+ "version": "1.20.0",
+ "type": "module",
+ "scripts": {
+ "dev": "vite dev --port 3000 --host",
+ "build": "vite build",
+ "preview": "vite preview --port 3000",
+ "check": "svelte-kit sync && svelte-check-rs --tsconfig ./tsconfig.json",
+ "format": "prettier --write ./src",
+ "format:check": "prettier --check ./src",
+ "check:watch": "svelte-kit sync && svelte-check-rs --tsconfig ./tsconfig.json --watch",
+ "fallow": "fallow"
+ },
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.20.2",
+ "@codemirror/lang-yaml": "^6.1.3",
+ "@codemirror/language": "^6.12.3",
+ "@codemirror/legacy-modes": "^6.5.3",
+ "@codemirror/lint": "^6.9.6",
+ "@codemirror/merge": "^6.12.1",
+ "@codemirror/state": "^6.6.0",
+ "@codemirror/view": "^6.43.0",
+ "@fontsource-variable/geist-mono": "^5.2.8",
+ "@fontsource-variable/montserrat": "^5.2.8",
+ "@lezer/highlight": "^1.2.3",
+ "@sveltejs/kit": "^2.61.1",
+ "@tanstack/svelte-query": "^6.1.33",
+ "@tanstack/table-core": "^8.21.3",
+ "@uiw/codemirror-themes": "^4.25.10",
+ "@xterm/addon-fit": "^0.11.0",
+ "@xterm/xterm": "^6.0.0",
+ "@xyflow/svelte": "^1.6.0",
+ "ajv": "^8.20.0",
+ "ansi-to-html": "^0.7.2",
+ "date-fns": "^4.4.0",
+ "embla-carousel-svelte": "^8.6.0",
+ "ky": "^2.0.2",
+ "marked": "^18.0.4",
+ "prettier": "^3.8.3",
+ "prettier-plugin-svelte": "^4.1.0",
+ "prettier-plugin-tailwindcss": "^0.8.0",
+ "svelte": "^5.56.1",
+ "svelte-codemirror-editor": "^2.1.0",
+ "yaml": "^2.9.0"
+ },
+ "devDependencies": {
+ "@iconify/json": "^2.2.482",
+ "@inlang/paraglide-js": "2.18.1",
+ "@internationalized/date": "^3.12.2",
+ "@prettier/plugin-oxc": "^0.1.4",
+ "@sveltejs/adapter-static": "^3.0.10",
+ "@sveltejs/vite-plugin-svelte": "^7.1.2",
+ "@tailwindcss/vite": "^4.3.0",
+ "@tanstack/svelte-query-devtools": "^6.1.33",
+ "@types/node": "^25.9.1",
+ "@typescript/native-preview": "7.0.0-dev.20260602.1",
+ "bits-ui": "^2.18.1",
+ "clsx": "^2.1.1",
+ "formsnap": "^2.0.1",
+ "isomorphic-dompurify": "^3.15.0",
+ "fallow": "^2.89.0",
+ "mode-watcher": "^1.1.0",
+ "paneforge": "^1.0.2",
+ "runed": "^0.37.1",
+ "svelte-check-rs": "^0.9.19",
+ "svelte-sonner": "^1.1.1",
+ "svelte-toolbelt": "^0.10.6",
+ "sveltekit-superforms": "^2.30.1",
+ "tailwind-merge": "^3.6.0",
+ "tailwind-variants": "^3.2.2",
+ "tailwindcss": "^4.3.0",
+ "tsx": "^4.22.4",
+ "tw-animate-css": "^1.4.0",
+ "typescript": "^6.0.3",
+ "unplugin-icons": "^23.0.1",
+ "vaul-svelte": "1.0.0-next.7",
+ "vite": "^8.0.16",
+ "zod": "^4.4.3"
+ }
}
diff --git a/frontend/src/lib/components/action-buttons.svelte b/frontend/src/lib/components/action-buttons.svelte
index 79d550de4..3dc66ccde 100644
--- a/frontend/src/lib/components/action-buttons.svelte
+++ b/frontend/src/lib/components/action-buttons.svelte
@@ -17,6 +17,7 @@
import { EllipsisIcon } from '$lib/icons';
import { createMutation } from '@tanstack/svelte-query';
import { hasPermission } from '$lib/utils/auth';
+ import { isDepotBuildAvailable } from '$lib/utils/build-provider';
import { environmentStore } from '$lib/stores/environment.store.svelte';
type TargetType = 'container' | 'project';
@@ -193,11 +194,7 @@
const canPull = $derived(type === 'project' && hasPermission('projects:deploy', currentEnvId));
const canBuild = $derived(type === 'project' && hasPermission('projects:deploy', currentEnvId));
const deployButtonLabel = $derived(projectHasBuildDirective ? m.compose_build_and_deploy() : m.common_up());
- const depotAvailable = $derived.by(() => {
- const projectId = ($settingsStore?.depotProjectId ?? '').trim();
- const token = ($settingsStore?.depotToken ?? '').trim();
- return Boolean($settingsStore?.depotConfigured) || (Boolean(projectId) && Boolean(token));
- });
+ const depotAvailable = $derived(isDepotBuildAvailable($settingsStore));
const projectBuildProvider = $derived.by<'local' | 'depot'>(() => {
const configuredProvider = ($settingsStore?.buildProvider as 'local' | 'depot') ?? 'local';
if (configuredProvider === 'depot' && !depotAvailable) {
diff --git a/frontend/src/lib/components/arcane-table/arcane-table-desktop-view.svelte b/frontend/src/lib/components/arcane-table/arcane-table-desktop-view.svelte
index f7863ceef..9db97a957 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table-desktop-view.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table-desktop-view.svelte
@@ -6,7 +6,14 @@
import { FolderXIcon, ArrowRightIcon, ArrowDownIcon } from '$lib/icons';
import { m } from '$lib/paraglide/messages';
import { cn } from '$lib/utils';
- import type { ColumnWidth, ColumnAlign, GroupedData, GroupSelectionState } from './arcane-table.types.svelte.ts';
+ import {
+ getTableRowsForItems,
+ shouldIgnoreTableRowClick,
+ type ColumnWidth,
+ type ColumnAlign,
+ type GroupedData,
+ type GroupSelectionState
+ } from './arcane-table.types.svelte';
import TableCheckbox from './arcane-table-checkbox.svelte';
import type { Component, Snippet } from 'svelte';
import { slide } from 'svelte/transition';
@@ -70,13 +77,8 @@
const stickyActionsClasses = `sticky right-0 z-10 transition-colors ${stickyCellSurfaceClasses}`;
const stickySelectClasses = `w-0 pr-6! ${stickyCellSurfaceClasses}`;
- function shouldIgnoreRowClick(event: MouseEvent): boolean {
- const target = event.target as HTMLElement | null;
- return !!target?.closest('a, button, input, [role="checkbox"], [data-slot="checkbox"], [data-row-select-ignore]');
- }
-
function handleRowClick(event: MouseEvent, rowId: string) {
- if (shouldIgnoreRowClick(event)) return;
+ if (shouldIgnoreTableRowClick(event)) return;
if (hasExpand) {
onToggleRowExpanded?.(rowId);
return;
@@ -101,11 +103,6 @@
}
// Get rows for a specific group from the table model
- function getRowsForGroup(groupItems: any[]) {
- const groupIds = new Set(groupItems.map((item) => item.id));
- return table.getRowModel().rows.filter((row) => groupIds.has((row.original as any).id));
- }
-
const isGrouped = $derived(groupedRows !== null && groupedRows.length > 0);
</script>
@@ -143,7 +140,7 @@
{#if isGrouped && groupedRows}
{#each groupedRows as group (group.groupName)}
{@const isCollapsed = groupCollapsedState[group.groupName] ?? true}
- {@const groupRows = getRowsForGroup(group.items)}
+ {@const groupRows = getTableRowsForItems(table, group.items)}
{@const selectionState = getGroupSelectionState?.(group.items) ?? 'none'}
{@const hasSelection = selectionState !== 'none'}
{@const IconComponent = groupIcon?.(group.groupName)}
diff --git a/frontend/src/lib/components/arcane-table/arcane-table-mobile-view.svelte b/frontend/src/lib/components/arcane-table/arcane-table-mobile-view.svelte
index 474f6316f..8613f50e9 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table-mobile-view.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table-mobile-view.svelte
@@ -6,7 +6,7 @@
import { m } from '$lib/paraglide/messages';
import { cn } from '$lib/utils';
import type { Snippet, Component } from 'svelte';
- import type { GroupedData } from './arcane-table.types.svelte.ts';
+ import { getTableRowsForItems, shouldIgnoreTableRowClick, type GroupedData } from './arcane-table.types.svelte';
import { slide } from 'svelte/transition';
void slide;
@@ -35,22 +35,11 @@
const hasExpand = $derived(!!expandedRowContent);
- function shouldIgnoreRowClick(event: MouseEvent): boolean {
- const target = event.target as HTMLElement | null;
- return !!target?.closest('a, button, input, [role="checkbox"], [data-slot="checkbox"], [data-row-select-ignore]');
- }
-
function handleRowClick(event: MouseEvent, rowId: string) {
- if (shouldIgnoreRowClick(event)) return;
+ if (shouldIgnoreTableRowClick(event)) return;
if (hasExpand) onToggleRowExpanded?.(rowId);
}
- // Get rows for a specific group from the table model
- function getRowsForGroup(groupItems: any[]) {
- const groupIds = new Set(groupItems.map((item) => item.id));
- return table.getRowModel().rows.filter((row) => groupIds.has((row.original as any).id));
- }
-
// Check if we should render grouped view
const isGrouped = $derived(groupedRows !== null && groupedRows.length > 0);
</script>
@@ -59,7 +48,7 @@
{#if isGrouped && groupedRows}
<div class="space-y-4 py-2">
{#each groupedRows as group (group.groupName)}
- {@const groupRows = getRowsForGroup(group.items)}
+ {@const groupRows = getTableRowsForItems(table, group.items)}
{@const IconComponent = groupIcon?.(group.groupName)}
<DropdownCard
diff --git a/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte b/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
index f997a5341..cf28b69ba 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
@@ -1,6 +1,7 @@
<script lang="ts" generics="TData">
import type { Table } from '@tanstack/table-core';
- import { DataTableFacetedFilter, DataTableViewOptions } from './index.js';
+ import DataTableFacetedFilter from './arcane-table-filter.svelte';
+ import DataTableViewOptions from './arcane-table-view-options.svelte';
import { Input } from '$lib/components/ui/input/index.js';
import {
imageUpdateFilters,
diff --git a/frontend/src/lib/components/arcane-table/arcane-table.types.svelte.ts b/frontend/src/lib/components/arcane-table/arcane-table.types.svelte.ts
index 1c8c12801..dd3c62c63 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table.types.svelte.ts
+++ b/frontend/src/lib/components/arcane-table/arcane-table.types.svelte.ts
@@ -1,4 +1,4 @@
-import type { Row, Column, FilterFn, ColumnFiltersState, VisibilityState } from '@tanstack/table-core';
+import type { Row, Column, FilterFn, ColumnFiltersState, VisibilityState, Table as TableType } from '@tanstack/table-core';
import type { Snippet } from 'svelte';
import type { Component } from 'svelte';
@@ -102,7 +102,7 @@ export function encodeMobileVisibility(visibility: Record<string, boolean>): str
return encoded;
}
-export function decodeMobileVisibility(encoded?: string[]): Record<string, boolean> {
+function decodeMobileVisibility(encoded?: string[]): Record<string, boolean> {
if (!encoded?.length) return {};
const visibility: Record<string, boolean> = {};
for (const entry of encoded) {
@@ -145,3 +145,13 @@ export type GroupedData<T> = {
};
export type GroupSelectionState = 'none' | 'some' | 'all';
+
+export function shouldIgnoreTableRowClick(event: MouseEvent): boolean {
+ const target = event.target as HTMLElement | null;
+ return !!target?.closest('a, button, input, [role="checkbox"], [data-slot="checkbox"], [data-row-select-ignore]');
+}
+
+export function getTableRowsForItems<T extends { id?: string }>(table: TableType<T>, groupItems: Array<{ id: string }>) {
+ const groupIds = new Set(groupItems.map((item) => item.id));
+ return table.getRowModel().rows.filter((row) => groupIds.has(row.original.id ?? ''));
+}
diff --git a/frontend/src/lib/components/compose/docker-run-converter-dialog.svelte b/frontend/src/lib/components/compose/docker-run-converter-dialog.svelte
new file mode 100644
index 000000000..060006f82
--- /dev/null
+++ b/frontend/src/lib/components/compose/docker-run-converter-dialog.svelte
@@ -0,0 +1,106 @@
+<script lang="ts">
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import * as Dialog from '$lib/components/ui/dialog/index.js';
+ import { Label } from '$lib/components/ui/label/index.js';
+ import { Textarea } from '$lib/components/ui/textarea/index.js';
+ import { CopyIcon } from '$lib/icons';
+ import { m } from '$lib/paraglide/messages';
+ import { systemService } from '$lib/services/system-service.js';
+ import { handleApiResultWithCallbacks, tryCatch } from '$lib/utils/api';
+ import { tick } from 'svelte';
+ import { toast } from 'svelte-sonner';
+
+ type ConvertedDockerRun = {
+ dockerCompose: string;
+ envVars: string;
+ serviceName: string;
+ };
+
+ let {
+ open = $bindable(false),
+ converting = $bindable(false),
+ onConverted
+ }: {
+ open: boolean;
+ converting: boolean;
+ onConverted: (data: ConvertedDockerRun) => void;
+ } = $props();
+
+ let dockerRunCommand = $state('');
+ const exampleCommands = [m.compose_example_command_1(), m.compose_example_command_2(), m.compose_example_command_3()];
+
+ function useExample(command: string) {
+ dockerRunCommand = command;
+ }
+
+ async function handleConvertDockerRun() {
+ if (!dockerRunCommand.trim()) {
+ toast.error(m.compose_enter_docker_run_command());
+ return;
+ }
+
+ handleApiResultWithCallbacks({
+ result: await tryCatch(systemService.convert(dockerRunCommand)),
+ message: m.compose_convert_failed(),
+ setLoadingState: (value) => (converting = value),
+ onSuccess: async (data) => {
+ onConverted(data);
+ await tick();
+ toast.success(m.compose_convert_success());
+ dockerRunCommand = '';
+ open = false;
+ }
+ });
+ }
+</script>
+
+<Dialog.Root bind:open>
+ <Dialog.Content class="max-h-[80vh] sm:max-w-[800px]">
+ <Dialog.Header>
+ <Dialog.Title>{m.compose_converter_title()}</Dialog.Title>
+ <Dialog.Description>{m.compose_converter_description()}</Dialog.Description>
+ </Dialog.Header>
+
+ <div class="max-h-[60vh] space-y-4 overflow-y-auto">
+ <div class="space-y-2">
+ <Label for="dockerRunCommand">{m.compose_docker_run_command_label()}</Label>
+ <Textarea
+ id="dockerRunCommand"
+ bind:value={dockerRunCommand}
+ placeholder={m.compose_docker_run_placeholder()}
+ rows={3}
+ disabled={converting}
+ class="font-mono text-sm"
+ />
+ </div>
+
+ <div class="space-y-2">
+ <Label class="text-muted-foreground text-xs">{m.compose_example_commands_label()}</Label>
+ <div class="space-y-1">
+ {#each exampleCommands as command (command)}
+ <ArcaneButton
+ action="base"
+ tone="ghost"
+ size="sm"
+ class="h-auto w-full justify-start p-2 text-left font-mono text-xs break-all whitespace-normal"
+ onclick={() => useExample(command)}
+ icon={CopyIcon}
+ customLabel={command}
+ />
+ {/each}
+ </div>
+ </div>
+ </div>
+
+ <div class="flex w-full justify-end pt-4">
+ <ArcaneButton
+ action="create"
+ disabled={!dockerRunCommand.trim() || converting}
+ onclick={handleConvertDockerRun}
+ loading={converting}
+ customLabel={m.compose_convert_action()}
+ loadingLabel={m.compose_converting()}
+ />
+ </div>
+ </Dialog.Content>
+</Dialog.Root>
diff --git a/frontend/src/lib/components/confirm-dialog/confirm-dialog.svelte b/frontend/src/lib/components/confirm-dialog/confirm-dialog.svelte
index 3516d508c..d3bd53d57 100644
--- a/frontend/src/lib/components/confirm-dialog/confirm-dialog.svelte
+++ b/frontend/src/lib/components/confirm-dialog/confirm-dialog.svelte
@@ -1,10 +1,11 @@
<script lang="ts">
import * as Dialog from '$lib/components/ui/dialog';
import { AlertIcon } from '$lib/icons';
- import { confirmDialogStore } from '.';
+ import { confirmDialogStore } from './store';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import { Label } from '$lib/components/ui/label';
import Checkbox from '../ui/checkbox/checkbox.svelte';
+ import { m } from '$lib/paraglide/messages';
let checkboxStates = $state<Record<string, boolean>>({});
@@ -72,7 +73,7 @@
</Label>
{#if checkbox.id === 'files' && checkboxStates[checkbox.id]}
- <div class="text-destructive mt-1 text-xs leading-snug">This will remove the project's files from disk.</div>
+ <div class="text-destructive mt-1 text-xs leading-snug">{m.confirm_remove_project_files_warning()}</div>
{/if}
</div>
</div>
diff --git a/frontend/src/lib/components/confirm-dialog/index.ts b/frontend/src/lib/components/confirm-dialog/index.ts
index 963242c34..a165f44d5 100644
--- a/frontend/src/lib/components/confirm-dialog/index.ts
+++ b/frontend/src/lib/components/confirm-dialog/index.ts
@@ -1,62 +1,4 @@
-import { writable } from 'svelte/store';
import ConfirmDialog from './confirm-dialog.svelte';
+export { confirmDialogStore, openConfirmDialog } from './store';
-interface ConfirmDialogStore {
- open: boolean;
- title: string;
- message: string;
- confirm: {
- label?: string;
- destructive?: boolean;
- action: (checkboxStates: Record<string, boolean>) => void;
- };
- checkboxes?: Array<{
- id: string;
- label: string;
- initialState?: boolean;
- }>;
-}
-
-export const confirmDialogStore = writable<ConfirmDialogStore>({
- open: false,
- title: '',
- message: '',
- confirm: {
- label: 'Confirm',
- destructive: false,
- action: () => {}
- }
-});
-
-function openConfirmDialog({
- title,
- message,
- confirm,
- checkboxes
-}: {
- title: string;
- message: string;
- confirm: {
- label?: string;
- destructive?: boolean;
- action: (checkboxStates: Record<string, boolean>) => void;
- };
- checkboxes?: Array<{
- id: string;
- label: string;
- initialState?: boolean;
- }>;
-}) {
- confirmDialogStore.update((val) => ({
- open: true,
- title,
- message,
- confirm: {
- ...val.confirm,
- ...confirm
- },
- checkboxes
- }));
-}
-
-export { ConfirmDialog, openConfirmDialog };
+export { ConfirmDialog };
diff --git a/frontend/src/lib/components/confirm-dialog/store.ts b/frontend/src/lib/components/confirm-dialog/store.ts
new file mode 100644
index 000000000..771acdb87
--- /dev/null
+++ b/frontend/src/lib/components/confirm-dialog/store.ts
@@ -0,0 +1,60 @@
+import { writable } from 'svelte/store';
+import { m } from '$lib/paraglide/messages';
+
+interface ConfirmDialogStore {
+ open: boolean;
+ title: string;
+ message: string;
+ confirm: {
+ label?: string;
+ destructive?: boolean;
+ action: (checkboxStates: Record<string, boolean>) => void;
+ };
+ checkboxes?: Array<{
+ id: string;
+ label: string;
+ initialState?: boolean;
+ }>;
+}
+
+export const confirmDialogStore = writable<ConfirmDialogStore>({
+ open: false,
+ title: '',
+ message: '',
+ confirm: {
+ label: m.common_confirm(),
+ destructive: false,
+ action: () => {}
+ }
+});
+
+export function openConfirmDialog({
+ title,
+ message,
+ confirm,
+ checkboxes
+}: {
+ title: string;
+ message: string;
+ confirm: {
+ label?: string;
+ destructive?: boolean;
+ action: (checkboxStates: Record<string, boolean>) => void;
+ };
+ checkboxes?: Array<{
+ id: string;
+ label: string;
+ initialState?: boolean;
+ }>;
+}) {
+ confirmDialogStore.update((val) => ({
+ open: true,
+ title,
+ message,
+ confirm: {
+ ...val.confirm,
+ ...confirm
+ },
+ checkboxes
+ }));
+}
diff --git a/frontend/src/lib/components/copy-button.svelte b/frontend/src/lib/components/copy-button.svelte
deleted file mode 100644
index 9d3efc81f..000000000
--- a/frontend/src/lib/components/copy-button.svelte
+++ /dev/null
@@ -1,61 +0,0 @@
-<script lang="ts">
- import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import type { ArcaneButtonSize, ArcaneButtonTone } from '$lib/components/arcane-button';
- import { CopyIcon, CheckIcon } from '$lib/icons';
- import { UseClipboard } from '$lib/hooks/use-clipboard.svelte';
- import { toast } from 'svelte-sonner';
- import { m } from '$lib/paraglide/messages';
- import type { ClassValue } from 'svelte/elements';
-
- interface Props {
- /** The text copied to the clipboard when the button is pressed. */
- text: string;
- /** Accessible label / tooltip. Defaults to "Copy". */
- label?: string;
- /** Show a toast on a successful copy. Defaults to true. */
- toastOnCopy?: boolean;
- /** Custom success toast message. Defaults to "Copied to clipboard". */
- successMessage?: string;
- size?: ArcaneButtonSize;
- tone?: ArcaneButtonTone;
- disabled?: boolean;
- class?: ClassValue;
- }
-
- let {
- text,
- label = m.common_copy(),
- toastOnCopy = true,
- successMessage,
- size = 'icon',
- tone = 'ghost',
- disabled = false,
- class: className
- }: Props = $props();
-
- const clipboard = new UseClipboard();
-
- async function handleCopy() {
- const status = await clipboard.copy(text);
- if (status === 'success') {
- if (toastOnCopy) toast.success(successMessage ?? m.common_copied());
- } else if (typeof window !== 'undefined' && !window.isSecureContext) {
- toast.error(m.common_copy_https_required());
- } else {
- toast.error(m.common_copy_failed());
- }
- }
-</script>
-
-<ArcaneButton
- action="base"
- {tone}
- {size}
- {disabled}
- onclick={handleCopy}
- title={label}
- customLabel={label}
- showLabel={size !== 'icon'}
- icon={clipboard.copied ? CheckIcon : CopyIcon}
- class={className}
-/>
diff --git a/frontend/src/lib/components/dialogs/create-container-dialog.svelte b/frontend/src/lib/components/dialogs/create-container-dialog.svelte
index 9aba01bee..cfb8b448e 100644
--- a/frontend/src/lib/components/dialogs/create-container-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/create-container-dialog.svelte
@@ -11,6 +11,7 @@
import type { ContainerCreateRequest } from '$lib/types/docker';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/settings';
+ import { parseKeyValuePairs } from '$lib/utils/form-parsers';
import SelectWithLabel from '../form/select-with-label.svelte';
import { m } from '$lib/paraglide/messages';
import {
@@ -117,27 +118,6 @@
{ source: '', destination: '', readonly: false }
]);
- function parseKeyValuePairs(text: string): Record<string, string> {
- if (!text?.trim()) return {};
-
- const result: Record<string, string> = {};
- const lines = text.split('\n');
-
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed || !trimmed.includes('=')) continue;
-
- const [key, ...valueParts] = trimmed.split('=');
- const value = valueParts.join('=');
-
- if (key?.trim()) {
- result[key.trim()] = value.trim();
- }
- }
-
- return result;
- }
-
function parsePortList(text: string): Record<string, {}> {
if (!text?.trim()) return {};
diff --git a/frontend/src/lib/components/dialogs/rbac-migration-banner.svelte b/frontend/src/lib/components/dialogs/rbac-migration-banner.svelte
deleted file mode 100644
index 1e263d436..000000000
--- a/frontend/src/lib/components/dialogs/rbac-migration-banner.svelte
+++ /dev/null
@@ -1,71 +0,0 @@
-<script lang="ts">
- import * as Alert from '$lib/components/ui/alert';
- import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import userStore from '$lib/stores/user-store';
- import { BUILT_IN_ROLE_VIEWER } from '$lib/types/auth';
- import { CloseIcon } from '$lib/icons';
- import { m } from '$lib/paraglide/messages';
- import type { User } from '$lib/types/auth';
-
- const STORAGE_KEY = 'rbac-migration-banner-dismissed';
-
- let dismissed = $state(false);
-
- $effect(() => {
- if (typeof window === 'undefined') return;
- try {
- if (window.localStorage.getItem(STORAGE_KEY) === 'true') {
- dismissed = true;
- }
- } catch {
- // Ignore storage access errors (e.g., private browsing).
- }
- });
-
- function shouldShowFor(user: User | null): boolean {
- if (!user) return false;
- const assignments = user.roleAssignments ?? [];
- if (assignments.length === 0) return false;
-
- const manualAssignments = assignments.filter((a) => a.source === 'manual');
- if (manualAssignments.length === 0) return false;
-
- const hasViewerOnEnv = manualAssignments.some((a) => a.roleId === BUILT_IN_ROLE_VIEWER && !!a.environmentId);
- if (!hasViewerOnEnv) return false;
-
- const hasNonViewerManual = manualAssignments.some((a) => a.roleId !== BUILT_IN_ROLE_VIEWER);
- return !hasNonViewerManual;
- }
-
- const visible = $derived(!dismissed && shouldShowFor($userStore));
-
- function dismiss() {
- try {
- if (typeof window !== 'undefined') {
- window.localStorage.setItem(STORAGE_KEY, 'true');
- }
- } catch {
- // Ignore storage access errors.
- }
- dismissed = true;
- }
-</script>
-
-{#if visible}
- <Alert.Root variant="default" class="mb-4 flex items-start gap-3">
- <div class="flex-1">
- <Alert.Title>{m.rbac_migration_banner_title()}</Alert.Title>
- <Alert.Description>{m.rbac_migration_banner_body()}</Alert.Description>
- </div>
- <ArcaneButton
- action="base"
- tone="ghost"
- size="icon"
- icon={CloseIcon}
- showLabel={false}
- onclick={dismiss}
- customLabel={m.rbac_migration_banner_dismiss()}
- class="text-muted-foreground hover:text-foreground"
- />
- </Alert.Root>
-{/if}
diff --git a/frontend/src/lib/components/forms/role-assignments-editor.svelte b/frontend/src/lib/components/forms/role-assignments-editor.svelte
index 126c5a497..98c96980e 100644
--- a/frontend/src/lib/components/forms/role-assignments-editor.svelte
+++ b/frontend/src/lib/components/forms/role-assignments-editor.svelte
@@ -13,6 +13,7 @@
import type { Environment } from '$lib/types/environment';
import { CloseIcon } from '$lib/icons';
import { m } from '$lib/paraglide/messages';
+ import { buildGlobalEnvironmentOptions, createRoleEnvironmentLabelers, GLOBAL_ENVIRONMENT_OPTION_ID } from '$lib/utils/options';
type Assignment = { roleId: string; environmentId?: string };
@@ -25,14 +26,8 @@
let { assignments = $bindable([]), roles, environments, disabled = false }: Props = $props();
- const GLOBAL_OPTION_ID = 'global';
-
- type EnvOption = { id: string; name: string };
-
- const envOptions: EnvOption[] = $derived([
- { id: GLOBAL_OPTION_ID, name: m.users_role_assignments_scope_global() },
- ...environments.map((env) => ({ id: env.id, name: env.name }))
- ]);
+ const envOptions = $derived(buildGlobalEnvironmentOptions(environments, m.users_role_assignments_scope_global()));
+ const selectedLabel = $derived(createRoleEnvironmentLabelers(roles, envOptions, m.common_select_option()));
const quickPresetRoles = $derived(roles.filter((role) => role.id === BUILT_IN_ROLE_EDITOR || role.id === BUILT_IN_ROLE_ADMIN));
@@ -52,11 +47,11 @@
}
function envIdToSelectValue(envId: string | undefined): string {
- return envId ?? GLOBAL_OPTION_ID;
+ return envId ?? GLOBAL_ENVIRONMENT_OPTION_ID;
}
function selectValueToEnvId(value: string): string | undefined {
- return value === GLOBAL_OPTION_ID ? undefined : value;
+ return value === GLOBAL_ENVIRONMENT_OPTION_ID ? undefined : value;
}
function isEnvTaken(envValue: string, roleId: string, currentIndex: number): boolean {
@@ -83,14 +78,6 @@
assignments = assignments.filter((_, i) => i !== index);
}
- function envSelectedLabel(value: string): string {
- return envOptions.find((o) => o.id === value)?.name ?? m.common_select_option();
- }
-
- function roleSelectedLabel(value: string): string {
- return roles.find((r) => r.id === value)?.name ?? m.common_select_option();
- }
-
function hasGlobalRoleAssignment(roleId: string): boolean {
return assignments.some((assignment) => assignment.roleId === roleId && !assignment.environmentId);
}
@@ -154,7 +141,7 @@
onValueChange={(v) => updateAssignment(index, { environmentId: selectValueToEnvId(v) })}
>
<Select.Trigger class="w-full" aria-label={m.users_role_assignments_environment()}>
- <span>{envSelectedLabel(envValue)}</span>
+ <span>{selectedLabel.environment(envValue)}</span>
</Select.Trigger>
<Select.Content>
{#each envOptions as option (option.id)}
@@ -177,7 +164,7 @@
>
<Select.Trigger class="w-full" aria-label={m.users_role_assignments_role()}>
<span class="flex items-center gap-2">
- <span>{roleSelectedLabel(assignment.roleId)}</span>
+ <span>{selectedLabel.role(assignment.roleId)}</span>
</span>
</Select.Trigger>
<Select.Content>
diff --git a/frontend/src/lib/components/mobile-nav/gestures.svelte.ts b/frontend/src/lib/components/mobile-nav/gestures.svelte.ts
index 2f3d7ca65..1405bc0ce 100644
--- a/frontend/src/lib/components/mobile-nav/gestures.svelte.ts
+++ b/frontend/src/lib/components/mobile-nav/gestures.svelte.ts
@@ -210,14 +210,4 @@ export class MobileNavGestures {
updateOptions(options: GestureOptions) {
this.options = options;
}
-
- destroy() {
- this.swipeDetector.setElement(null);
- if (this.scrollTimeout) {
- clearTimeout(this.scrollTimeout);
- }
- if (this.flickDetectTimeout) {
- clearTimeout(this.flickDetectTimeout);
- }
- }
}
diff --git a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte
index 5401a3dc9..4ddd787f3 100644
--- a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte
+++ b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte
@@ -9,15 +9,10 @@
import MobileUserCard from './mobile-user-card.svelte';
import ActivityCenterTrigger from '$lib/components/activity/activity-center-trigger.svelte';
import * as Drawer from '$lib/components/ui/drawer/index.js';
- import { queryKeys } from '$lib/query/query-keys';
- import systemUpgradeService from '$lib/services/api/system-upgrade-service';
import UpdateCenterDialog from '$lib/components/dialogs/update-center-dialog.svelte';
- import { toast } from 'svelte-sonner';
- import { extractApiErrorMessage } from '$lib/utils/api';
- import { hasPermission } from '$lib/utils/auth';
+ import { useUpgradeCheck } from '$lib/hooks/use-upgrade-check.svelte';
import type { AppVersionInformation } from '$lib/types/settings';
import type { PermissionsManifest, User } from '$lib/types/auth';
- import { createMutation, createQuery } from '@tanstack/svelte-query';
let {
open = $bindable(false),
@@ -56,61 +51,12 @@
filterByPermissions(navigationItems.settingsItems, memoizedUser ?? null, currentEnvId, permissionsManifest)
);
- let upgrading = $state(false);
- let showConfirmDialog = $state(false);
- const canInstallUpdates = $derived(hasPermission('environments:update'));
-
- const shouldCheckUpgrade = $derived(!!(versionInformation?.updateAvailable && canInstallUpdates && !debug));
- const upgradeAvailabilityQuery = createQuery(() => ({
- queryKey: queryKeys.system.upgradeAvailable('mobile-nav'),
- queryFn: () => systemUpgradeService.checkUpgradeAvailable(),
- enabled: shouldCheckUpgrade,
- staleTime: 0
- }));
-
- const canUpgrade = $derived.by(() => {
- if (debug) return true;
- const result = upgradeAvailabilityQuery.data;
- return !!result?.canUpgrade && !result?.error;
- });
- const checkingUpgrade = $derived(
- !!(shouldCheckUpgrade && (upgradeAvailabilityQuery.isPending || upgradeAvailabilityQuery.isFetching))
- );
- const shouldShowUpgrade = $derived((canUpgrade && canInstallUpdates) || debug);
-
- const updateType = $derived.by(() => {
- if (!versionInformation) return 'none';
- if (versionInformation.isSemverVersion) return 'semver';
- if (versionInformation.currentTag && versionInformation.newestDigest) return 'digest';
- return 'none';
- });
-
- const versionChip = $derived.by(() => {
- if (!versionInformation) return '';
- if (updateType === 'semver') return versionInformation.newestVersion ?? '';
- if (updateType === 'digest') return versionInformation.currentTag ?? '';
- return '';
+ const upgradeCheck = useUpgradeCheck({
+ queryScope: 'mobile-nav',
+ getVersionInformation: () => versionInformation,
+ getDebug: () => debug
});
- const shouldShowBanner = $derived(versionInformation?.updateAvailable || debug);
- const triggerUpgradeMutation = createMutation(() => ({
- mutationFn: () => systemUpgradeService.triggerUpgrade(),
- onError: (error: unknown) => {
- const errorMessage = extractApiErrorMessage(error);
- const wrappedPrefix = m.upgrade_failed({ error: '' });
- toast.error(errorMessage.startsWith(wrappedPrefix) ? errorMessage : m.upgrade_failed({ error: errorMessage }));
- upgrading = false;
- }
- }));
-
- function handleUpgradeClick() {
- showConfirmDialog = true;
- }
-
- function handleConfirmUpgrade() {
- triggerUpgradeMutation.mutate();
- }
-
function handleItemClick() {
open = false;
}
@@ -372,11 +318,11 @@
{versionInformation.displayVersion ?? versionInformation.currentVersion}
</p>
</div>
- {#if shouldShowBanner}
+ {#if upgradeCheck.shouldShowBanner}
<button
type="button"
- onclick={handleUpgradeClick}
- disabled={upgrading || checkingUpgrade}
+ onclick={upgradeCheck.openDialog}
+ disabled={upgradeCheck.upgrading || upgradeCheck.checkingUpgrade}
class="group hover:bg-muted/50 focus-visible:ring-primary/40 mt-3 flex w-full items-center gap-2.5 rounded-xl px-3 py-2.5 text-left transition-colors focus-visible:ring-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60"
>
<span class="relative flex size-2 shrink-0 items-center justify-center">
@@ -386,9 +332,9 @@
<span class="text-foreground flex-1 text-sm font-medium">
{m.sidebar_update_available()}
</span>
- {#if versionChip}
+ {#if upgradeCheck.versionChip}
<span class="bg-muted text-muted-foreground rounded-md px-1.5 py-0.5 font-mono text-[11px]">
- {versionChip}
+ {upgradeCheck.versionChip}
</span>
{/if}
</button>
@@ -399,12 +345,12 @@
</Drawer.Root>
<UpdateCenterDialog
- bind:open={showConfirmDialog}
- bind:upgrading
+ bind:open={upgradeCheck.showConfirmDialog}
+ bind:upgrading={upgradeCheck.upgrading}
{versionInformation}
- canInstall={shouldShowUpgrade}
+ canInstall={upgradeCheck.shouldShowUpgrade}
{debug}
- onConfirm={handleConfirmUpgrade}
+ onConfirm={upgradeCheck.confirmUpgrade}
/>
<style>
diff --git a/frontend/src/lib/components/mobile-nav/mobile-nav.svelte b/frontend/src/lib/components/mobile-nav/mobile-nav.svelte
index 0c968f030..aa8fe9007 100644
--- a/frontend/src/lib/components/mobile-nav/mobile-nav.svelte
+++ b/frontend/src/lib/components/mobile-nav/mobile-nav.svelte
@@ -12,6 +12,7 @@
import type { AppVersionInformation } from '$lib/types/settings';
import type { PermissionsManifest, User } from '$lib/types/auth';
import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { registerNavigationVisibilityController } from '$lib/utils/navigation';
let {
navigationSettings,
@@ -52,6 +53,10 @@
let menuOpen = $state(false);
let navElement: HTMLElement;
+ function resetVisibility() {
+ visible = true;
+ }
+
const gestures = new MobileNavGestures(
{
onMenuOpen: () => (menuOpen = true),
@@ -97,10 +102,15 @@
// Show nav when menu closes
$effect(() => {
if (!menuOpen) {
- visible = true;
+ resetVisibility();
}
});
+ $effect(() => {
+ registerNavigationVisibilityController({ resetVisibility });
+ return () => registerNavigationVisibilityController(null);
+ });
+
// Keep page padding in sync with nav height via CSS variables
$effect(() => {
if (!navElement || typeof document === 'undefined') return;
diff --git a/frontend/src/lib/components/quick-actions.svelte b/frontend/src/lib/components/quick-actions.svelte
deleted file mode 100644
index 41eb9f5ad..000000000
--- a/frontend/src/lib/components/quick-actions.svelte
+++ /dev/null
@@ -1,117 +0,0 @@
-<script lang="ts">
- import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { ActionButtonGroup, type ActionButton } from '$lib/components/action-button-group/index.js';
- import { IsTablet } from '$lib/hooks/is-tablet.svelte.js';
- import { m } from '$lib/paraglide/messages';
- import { cn } from '$lib/utils';
- import { hasAnyPermission, hasPermission } from '$lib/utils/auth';
- import { environmentStore } from '$lib/stores/environment.store.svelte';
-
- type IsLoadingFlags = {
- starting: boolean;
- stopping: boolean;
- pruning: boolean;
- };
-
- let {
- stoppedContainers,
- runningContainers,
- isLoading,
- onStartAll,
- onStopAll,
- onOpenPruneDialog,
- onRefresh,
- refreshing = false,
- compact = false,
- class: className
- }: {
- stoppedContainers: number;
- runningContainers: number;
- isLoading: IsLoadingFlags;
- onStartAll: () => void;
- onStopAll: () => void;
- onOpenPruneDialog: () => void;
- onRefresh: () => void;
- refreshing?: boolean;
- compact?: boolean;
- class?: string;
- } = $props();
-
- const isTablet = new IsTablet();
- const isAnyActionLoading = $derived(isLoading.starting || isLoading.stopping || isLoading.pruning);
-
- const currentEnvId = $derived(environmentStore.selected?.id);
- const canStartAll = $derived(hasPermission('containers:start', currentEnvId));
- const canStopAll = $derived(hasPermission('containers:stop', currentEnvId));
- const canPrune = $derived(hasAnyPermission(['images:prune', 'volumes:prune', 'networks:prune'], currentEnvId));
-
- const actionButtons: ActionButton[] = $derived(
- [
- canStartAll
- ? {
- id: 'start-all',
- action: 'start_all' as const,
- label: m.quick_actions_start_all(),
- onclick: onStartAll,
- loading: isLoading.starting,
- disabled: stoppedContainers === 0 || isAnyActionLoading,
- badge: stoppedContainers
- }
- : null,
- canStopAll
- ? {
- id: 'stop-all',
- action: 'stop_all' as const,
- label: m.quick_actions_stop_all(),
- onclick: onStopAll,
- loading: isLoading.stopping,
- disabled: runningContainers === 0 || isAnyActionLoading,
- badge: runningContainers
- }
- : null,
- canPrune
- ? {
- id: 'prune',
- action: 'prune' as const,
- label: m.quick_actions_prune_system(),
- onclick: onOpenPruneDialog,
- loading: isLoading.pruning,
- disabled: isAnyActionLoading
- }
- : null,
- {
- id: 'refresh',
- action: 'refresh' as const,
- label: m.common_refresh(),
- onclick: onRefresh,
- loading: refreshing,
- disabled: isAnyActionLoading || refreshing
- }
- ].filter((b) => b !== null) as ActionButton[]
- );
-</script>
-
-<section class={cn(compact ? 'flex min-w-0 flex-1 items-center justify-end' : '', className)}>
- {#if compact}
- {#if isTablet.current}
- <div class="flex w-full min-w-0 items-center justify-center gap-2">
- {#each actionButtons as button (button.id)}
- <ArcaneButton
- action={button.action}
- customLabel={button.label}
- loadingLabel={button.loadingLabel}
- loading={button.loading}
- disabled={button.disabled}
- onclick={button.onclick}
- size="icon"
- showLabel={false}
- icon={button.icon}
- class="min-w-0 flex-1"
- />
- {/each}
- </div>
- {:else}
- <ActionButtonGroup buttons={actionButtons} />
- {/if}
- {/if}
-</section>
diff --git a/frontend/src/lib/components/sheets/create-network-sheet.svelte b/frontend/src/lib/components/sheets/create-network-sheet.svelte
index 2d044aacf..aa554797a 100644
--- a/frontend/src/lib/components/sheets/create-network-sheet.svelte
+++ b/frontend/src/lib/components/sheets/create-network-sheet.svelte
@@ -9,6 +9,7 @@
import type { NetworkCreateOptions } from '$lib/types/docker';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/settings';
+ import { parseKeyValuePairs } from '$lib/utils/form-parsers';
import SelectWithLabel from '../form/select-with-label.svelte';
import { m } from '$lib/paraglide/messages';
import { CloseIcon } from '$lib/icons';
@@ -58,27 +59,6 @@
// Dynamic labels state for the key-value pairs
let labels = $state<{ key: string; value: string }[]>([{ key: '', value: '' }]);
- function parseKeyValuePairs(text: string): Record<string, string> {
- if (!text?.trim()) return {};
-
- const result: Record<string, string> = {};
- const lines = text.split('\n');
-
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed || !trimmed.includes('=')) continue;
-
- const [key, ...valueParts] = trimmed.split('=');
- const value = valueParts.join('=');
-
- if (key?.trim()) {
- result[key.trim()] = value.trim();
- }
- }
-
- return result;
- }
-
function addLabel() {
labels = [...labels, { key: '', value: '' }];
}
diff --git a/frontend/src/lib/components/sheets/create-volume-sheet.svelte b/frontend/src/lib/components/sheets/create-volume-sheet.svelte
index 46dd59c69..06ee4e97d 100644
--- a/frontend/src/lib/components/sheets/create-volume-sheet.svelte
+++ b/frontend/src/lib/components/sheets/create-volume-sheet.svelte
@@ -6,6 +6,7 @@
import type { VolumeCreateRequest } from '$lib/types/docker';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/settings';
+ import { parseKeyValuePairs } from '$lib/utils/form-parsers';
import SelectWithLabel from '../form/select-with-label.svelte';
import { m } from '$lib/paraglide/messages';
@@ -41,27 +42,6 @@
let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
- function parseKeyValuePairs(text: string): Record<string, string> {
- if (!text?.trim()) return {};
-
- const result: Record<string, string> = {};
- const lines = text.split('\n');
-
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed || !trimmed.includes('=')) continue;
-
- const [key, ...valueParts] = trimmed.split('=');
- const value = valueParts.join('=');
-
- if (key?.trim()) {
- result[key.trim()] = value.trim();
- }
- }
-
- return result;
- }
-
function handleSubmit() {
const data = form.validate();
if (!data) return;
diff --git a/frontend/src/lib/components/sheets/image-pull-sheet.svelte b/frontend/src/lib/components/sheets/image-pull-sheet.svelte
index fe475cd30..31cfb092e 100644
--- a/frontend/src/lib/components/sheets/image-pull-sheet.svelte
+++ b/frontend/src/lib/components/sheets/image-pull-sheet.svelte
@@ -7,6 +7,7 @@
import { toast } from 'svelte-sonner';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { m } from '$lib/paraglide/messages';
+ import { readNdjsonStream } from '$lib/utils/streaming';
type ImagePullFormProps = {
open: boolean;
@@ -82,38 +83,21 @@
}
function drainPullStream(body: ReadableStream<Uint8Array>, fullImageName: string) {
- const reader = body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
-
(async () => {
+ let streamFailed = false;
try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
-
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split('\n');
- buffer = lines.pop() || '';
-
- for (const line of lines) {
- if (!line.trim()) continue;
- try {
- const parsed = JSON.parse(line);
- if (parsed?.error) {
- const errMsg =
- typeof parsed.error === 'string' ? parsed.error : parsed.error.message || m.images_pull_stream_error();
- toast.error(errMsg);
- onPullFinished(false, fullImageName, errMsg);
- return;
- }
- } catch {
- // ignore non-JSON lines
- }
+ await readNdjsonStream(body, (parsed) => {
+ if (parsed?.error) {
+ const errMsg = typeof parsed.error === 'string' ? parsed.error : parsed.error.message || m.images_pull_stream_error();
+ streamFailed = true;
+ toast.error(errMsg);
+ onPullFinished(false, fullImageName, errMsg);
+ throw new Error(errMsg);
}
- }
+ });
onPullFinished(true, fullImageName);
} catch (error: any) {
+ if (streamFailed) return;
const message = error.message || m.images_pull_unexpected_error();
toast.error(message);
onPullFinished(false, fullImageName, message);
diff --git a/frontend/src/lib/components/sheets/oidc-mapping-form-sheet.svelte b/frontend/src/lib/components/sheets/oidc-mapping-form-sheet.svelte
index 6eba49e36..31d6109ce 100644
--- a/frontend/src/lib/components/sheets/oidc-mapping-form-sheet.svelte
+++ b/frontend/src/lib/components/sheets/oidc-mapping-form-sheet.svelte
@@ -9,6 +9,7 @@
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/settings';
import { m } from '$lib/paraglide/messages';
+ import { buildGlobalEnvironmentOptions, createRoleEnvironmentLabelers, GLOBAL_ENVIRONMENT_OPTION_ID } from '$lib/utils/options';
type Props = {
open: boolean;
@@ -21,14 +22,10 @@
let { open = $bindable(false), mappingToEdit, roles, environments, isLoading, onSubmit }: Props = $props();
- const GLOBAL_OPTION_ID = 'global';
-
const isEditMode = $derived(!!mappingToEdit);
- const envOptions = $derived([
- { id: GLOBAL_OPTION_ID, name: m.oidc_mappings_scope_global_option() },
- ...environments.map((env) => ({ id: env.id, name: env.name }))
- ]);
+ const envOptions = $derived(buildGlobalEnvironmentOptions(environments, m.oidc_mappings_scope_global_option()));
+ const selectedLabel = $derived(createRoleEnvironmentLabelers(roles, envOptions, m.common_select_option()));
const formSchema = z.object({
claimValue: z.string().min(1, m.oidc_mappings_claim_required()),
@@ -39,26 +36,18 @@
const formData = $derived({
claimValue: mappingToEdit?.claimValue ?? '',
roleId: mappingToEdit?.roleId ?? roles[0]?.id ?? '',
- environmentId: mappingToEdit?.environmentId ?? GLOBAL_OPTION_ID
+ environmentId: mappingToEdit?.environmentId ?? GLOBAL_ENVIRONMENT_OPTION_ID
});
const { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
- function envSelectedLabel(value: string): string {
- return envOptions.find((o) => o.id === value)?.name ?? m.common_select_option();
- }
-
- function roleSelectedLabel(value: string): string {
- return roles.find((r) => r.id === value)?.name ?? m.common_select_option();
- }
-
function handleSubmit() {
const data = form.validate();
if (!data) return;
onSubmit({
claimValue: data.claimValue,
roleId: data.roleId,
- environmentId: data.environmentId === GLOBAL_OPTION_ID ? undefined : data.environmentId
+ environmentId: data.environmentId === GLOBAL_ENVIRONMENT_OPTION_ID ? undefined : data.environmentId
});
}
@@ -89,7 +78,7 @@
<Label for="oidc-mapping-role" class="mb-0">{m.oidc_mappings_role_label()}</Label>
<Select.Root type="single" bind:value={$inputs.roleId.value} disabled={isLoading}>
<Select.Trigger id="oidc-mapping-role" class="w-full {$inputs.roleId.error ? 'border-destructive' : ''}">
- <span>{roleSelectedLabel($inputs.roleId.value)}</span>
+ <span>{selectedLabel.role($inputs.roleId.value)}</span>
</Select.Trigger>
<Select.Content>
{#each roles as role (role.id)}
@@ -113,7 +102,7 @@
<Label for="oidc-mapping-env" class="mb-0">{m.oidc_mappings_scope_label()}</Label>
<Select.Root type="single" bind:value={$inputs.environmentId.value} disabled={isLoading}>
<Select.Trigger id="oidc-mapping-env" class="w-full">
- <span>{envSelectedLabel($inputs.environmentId.value)}</span>
+ <span>{selectedLabel.environment($inputs.environmentId.value)}</span>
</Select.Trigger>
<Select.Content>
{#each envOptions as option (option.id)}
diff --git a/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte b/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte
index 0284fb000..3400ebafe 100644
--- a/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte
@@ -5,14 +5,9 @@
import { useSidebar } from '$lib/components/ui/sidebar/index.js';
import type { AppVersionInformation } from '$lib/types/settings';
import { m } from '$lib/paraglide/messages';
- import { queryKeys } from '$lib/query/query-keys';
- import systemUpgradeService from '$lib/services/api/system-upgrade-service';
import UpdateCenterDialog from '$lib/components/dialogs/update-center-dialog.svelte';
- import { toast } from 'svelte-sonner';
import { DownloadIcon } from '$lib/icons';
- import { extractApiErrorMessage } from '$lib/utils/api';
- import { createMutation, createQuery } from '@tanstack/svelte-query';
- import { hasPermission } from '$lib/utils/auth';
+ import { useUpgradeCheck } from '$lib/hooks/use-upgrade-check.svelte';
let {
isCollapsed,
@@ -25,88 +20,37 @@
} = $props();
const sidebar = useSidebar();
-
- let upgrading = $state(false);
- let showConfirmDialog = $state(false);
- const canInstallUpdates = $derived(hasPermission('environments:update'));
-
- const shouldCheckUpgrade = $derived(!!(versionInformation?.updateAvailable && canInstallUpdates && !debug));
- const upgradeAvailabilityQuery = createQuery(() => ({
- queryKey: queryKeys.system.upgradeAvailable('sidebar'),
- queryFn: () => systemUpgradeService.checkUpgradeAvailable(),
- enabled: shouldCheckUpgrade,
- staleTime: 0
- }));
-
- const canUpgrade = $derived.by(() => {
- if (debug) return true;
- const result = upgradeAvailabilityQuery.data;
- return !!result?.canUpgrade && !result?.error;
- });
- const checkingUpgrade = $derived(
- !!(shouldCheckUpgrade && (upgradeAvailabilityQuery.isPending || upgradeAvailabilityQuery.isFetching))
- );
- const shouldShowUpgrade = $derived((canUpgrade && canInstallUpdates) || debug);
-
- const updateType = $derived.by(() => {
- if (!versionInformation) return 'none';
- if (versionInformation.isSemverVersion) return 'semver';
- if (versionInformation.currentTag && versionInformation.newestDigest) return 'digest';
- return 'none';
- });
-
- const versionChip = $derived.by(() => {
- if (!versionInformation) return '';
- if (updateType === 'semver') return versionInformation.newestVersion ?? '';
- if (updateType === 'digest') return versionInformation.currentTag ?? '';
- return '';
+ const upgradeCheck = useUpgradeCheck({
+ queryScope: 'sidebar',
+ getVersionInformation: () => versionInformation,
+ getDebug: () => debug
});
const tooltipText = $derived(
m.sidebar_update_available_tooltip({
- version: versionInformation?.newestVersion ?? versionChip ?? m.common_unknown()
+ version: versionInformation?.newestVersion ?? upgradeCheck.versionChip ?? m.common_unknown()
})
);
-
- const triggerUpgradeMutation = createMutation(() => ({
- mutationFn: () => systemUpgradeService.triggerUpgrade(),
- onError: (error: unknown) => {
- const errorMessage = extractApiErrorMessage(error);
- const wrappedPrefix = m.upgrade_failed({ error: '' });
- toast.error(errorMessage.startsWith(wrappedPrefix) ? errorMessage : m.upgrade_failed({ error: errorMessage }));
- upgrading = false;
- }
- }));
-
- function openDialog() {
- showConfirmDialog = true;
- }
-
- function handleConfirmUpgrade() {
- triggerUpgradeMutation.mutate();
- }
-
- const shouldShowBanner = $derived(versionInformation?.updateAvailable || debug);
</script>
<UpdateCenterDialog
- bind:open={showConfirmDialog}
- bind:upgrading
+ bind:open={upgradeCheck.showConfirmDialog}
+ bind:upgrading={upgradeCheck.upgrading}
{versionInformation}
- canInstall={shouldShowUpgrade}
+ canInstall={upgradeCheck.shouldShowUpgrade}
{debug}
- onConfirm={handleConfirmUpgrade}
+ onConfirm={upgradeCheck.confirmUpgrade}
/>
-{#if shouldShowBanner}
+{#if upgradeCheck.shouldShowBanner}
<div class={cn('pb-2', isCollapsed ? 'px-1' : 'px-3')}>
<Separator.Root class="mb-2 opacity-30" />
{#if !isCollapsed}
<button
type="button"
- onclick={openDialog}
- disabled={upgrading || checkingUpgrade}
+ onclick={upgradeCheck.openDialog}
+ disabled={upgradeCheck.upgrading || upgradeCheck.checkingUpgrade}
class="group hover:bg-muted/50 focus-visible:ring-primary/40 flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left transition-colors focus-visible:ring-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60"
>
<span class="relative flex size-2 shrink-0 items-center justify-center">
@@ -116,9 +60,9 @@
<span class="text-foreground flex-1 text-sm font-medium">
{m.sidebar_update_available()}
</span>
- {#if versionChip}
+ {#if upgradeCheck.versionChip}
<span class="bg-muted text-muted-foreground rounded-md px-1.5 py-0.5 font-mono text-[11px]">
- {versionChip}
+ {upgradeCheck.versionChip}
</span>
{/if}
</button>
@@ -127,8 +71,8 @@
<Tooltip.Trigger>
{#snippet child({ props })}
<button
- onclick={openDialog}
- disabled={upgrading || checkingUpgrade}
+ onclick={upgradeCheck.openDialog}
+ disabled={upgradeCheck.upgrading || upgradeCheck.checkingUpgrade}
class="hover:bg-muted/60 focus-visible:ring-primary/40 relative mx-auto flex size-8 items-center justify-center rounded-lg transition-colors focus-visible:ring-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60"
{...props}
>
diff --git a/frontend/src/lib/components/swarm/swarm-kv-page.svelte b/frontend/src/lib/components/swarm/swarm-kv-page.svelte
new file mode 100644
index 000000000..94f75e4a3
--- /dev/null
+++ b/frontend/src/lib/components/swarm/swarm-kv-page.svelte
@@ -0,0 +1,275 @@
+<script lang="ts">
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
+ import { CopyButton } from '$lib/components/ui/copy-button';
+ import * as Card from '$lib/components/ui/card';
+ import { Input } from '$lib/components/ui/input/index.js';
+ import { Textarea } from '$lib/components/ui/textarea/index.js';
+ import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';
+ import { TrashIcon } from '$lib/icons';
+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
+ import { m } from '$lib/paraglide/messages';
+ import { handleApiResultWithCallbacks, tryCatch } from '$lib/utils/api';
+ import { decodeBase64ToText, encodeTextToBase64, formatSwarmTimestamp, getSwarmSpecName } from '$lib/utils/swarm-kv';
+ import { onMount, type Component } from 'svelte';
+ import { toast } from 'svelte-sonner';
+
+ export type SwarmKvItem = {
+ id: string;
+ spec?: Record<string, unknown> | null;
+ updatedAt: string;
+ };
+ type LoadingState = {
+ refresh: boolean;
+ create: boolean;
+ delete: boolean;
+ };
+ type SwarmKvMessages = {
+ pageTitle: string;
+ pageSubtitle: string;
+ statTitle: string;
+ createTitle: string;
+ createSubtitle: string;
+ namePlaceholder: string;
+ dataPlaceholder: string;
+ createButton: string;
+ listTitle: string;
+ listSubtitle: string;
+ empty: string;
+ immutableNotice: string;
+ deleteButton: string;
+ nameRequired: string;
+ createFailed: string;
+ createSuccess: (name: string) => string;
+ deleteConfirm: (name: string) => string;
+ deleteFailed: (name: string) => string;
+ deleteSuccess: (name: string) => string;
+ };
+
+ let {
+ icon,
+ permission,
+ resourceLabel,
+ canManage,
+ messages,
+ loadItems,
+ createItem,
+ removeItem
+ }: {
+ icon: Component;
+ permission: string;
+ resourceLabel: string;
+ canManage: boolean;
+ messages: SwarmKvMessages;
+ loadItems: () => Promise<SwarmKvItem[]>;
+ createItem: (spec: Record<string, unknown>) => Promise<SwarmKvItem>;
+ removeItem: (id: string) => Promise<unknown>;
+ } = $props();
+
+ let items = $state<SwarmKvItem[]>([]);
+ let selectedId = $state('');
+ let createName = $state('');
+ let createData = $state('');
+ let editName = $state('');
+ let editData = $state('');
+ let isLoading = $state<LoadingState>({
+ refresh: false,
+ create: false,
+ delete: false
+ });
+
+ function selectItem(item: SwarmKvItem) {
+ selectedId = item.id;
+ const spec = (item.spec ?? {}) as Record<string, unknown>;
+ editName = typeof spec['Name'] === 'string' ? spec['Name'] : '';
+ editData = typeof spec['Data'] === 'string' ? decodeBase64ToText(spec['Data']) : '';
+ }
+
+ function clearSelectedItem() {
+ selectedId = '';
+ editName = '';
+ editData = '';
+ }
+
+ function toggleItem(item: SwarmKvItem) {
+ if (selectedId === item.id) {
+ clearSelectedItem();
+ return;
+ }
+
+ selectItem(item);
+ }
+
+ async function refresh() {
+ isLoading.refresh = true;
+ try {
+ items = await loadItems();
+ if (selectedId && !items.some((item) => item.id === selectedId)) {
+ clearSelectedItem();
+ }
+ } finally {
+ isLoading.refresh = false;
+ }
+ }
+
+ useEnvironmentRefresh(refresh);
+
+ onMount(() => {
+ void refresh();
+ });
+
+ async function handleCreate() {
+ const name = createName.trim();
+ if (!name) {
+ toast.error(messages.nameRequired);
+ return;
+ }
+ const spec: Record<string, unknown> = {
+ Name: name,
+ Data: encodeTextToBase64(createData)
+ };
+
+ handleApiResultWithCallbacks({
+ result: await tryCatch(createItem(spec)),
+ message: messages.createFailed,
+ setLoadingState: (value) => (isLoading.create = value),
+ onSuccess: async (created) => {
+ toast.success(messages.createSuccess(getSwarmSpecName(created.spec, created.id)));
+ createName = '';
+ createData = '';
+ await refresh();
+ selectItem(created);
+ }
+ });
+ }
+
+ function handleRemove(item: SwarmKvItem) {
+ const name = getSwarmSpecName(item.spec, item.id);
+ openConfirmDialog({
+ title: m.common_delete_title({ resource: resourceLabel }),
+ message: messages.deleteConfirm(name),
+ confirm: {
+ label: m.common_delete(),
+ destructive: true,
+ action: async () => {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(removeItem(item.id)),
+ message: messages.deleteFailed(name),
+ setLoadingState: (value) => (isLoading.delete = value),
+ onSuccess: async () => {
+ toast.success(messages.deleteSuccess(name));
+ await refresh();
+ }
+ });
+ }
+ }
+ });
+ }
+
+ const actionButtons: ActionButton[] = $derived([
+ {
+ id: 'refresh',
+ action: 'restart',
+ label: m.common_refresh(),
+ onclick: refresh,
+ loading: isLoading.refresh,
+ disabled: isLoading.refresh
+ }
+ ]);
+
+ const statCards: StatCardConfig[] = $derived([
+ {
+ title: messages.statTitle,
+ value: items.length,
+ icon,
+ iconColor: 'text-blue-500'
+ }
+ ]);
+</script>
+
+<ResourcePageLayout title={messages.pageTitle} subtitle={messages.pageSubtitle} {icon} {actionButtons} {statCards}>
+ {#snippet mainContent()}
+ <div class="grid gap-4 lg:grid-cols-[1fr,1.1fr]">
+ <Card.Root class="pt-0">
+ <Card.Header>
+ <Card.Title>{messages.createTitle}</Card.Title>
+ <Card.Description>{messages.createSubtitle}</Card.Description>
+ </Card.Header>
+ <Card.Content class="space-y-3 pb-6">
+ <Input placeholder={messages.namePlaceholder} bind:value={createName} />
+ <Textarea rows={10} bind:value={createData} placeholder={messages.dataPlaceholder} class="font-mono text-xs" />
+ <IfPermitted perm={permission}>
+ <ArcaneButton
+ action="create"
+ customLabel={messages.createButton}
+ onclick={handleCreate}
+ disabled={!canManage || isLoading.create}
+ loading={isLoading.create}
+ />
+ </IfPermitted>
+ </Card.Content>
+ </Card.Root>
+
+ <div class="space-y-4">
+ <Card.Root class="pt-0">
+ <Card.Header>
+ <Card.Title>{messages.listTitle}</Card.Title>
+ <Card.Description>{messages.listSubtitle}</Card.Description>
+ </Card.Header>
+ <Card.Content class="space-y-3 pb-6">
+ {#if items.length === 0}
+ <div class="text-muted-foreground py-8 text-center text-sm">{messages.empty}</div>
+ {:else}
+ {#each items as item (item.id)}
+ <Card.Root class="overflow-hidden border py-0">
+ <button
+ type="button"
+ class={`w-full px-4 py-3 text-left transition-colors ${selectedId === item.id ? 'bg-muted/50' : 'hover:bg-muted/40'}`}
+ onclick={() => toggleItem(item)}
+ >
+ <div class="flex items-center justify-between gap-2">
+ <div class="min-w-0">
+ <div class="truncate font-medium">{getSwarmSpecName(item.spec, item.id)}</div>
+ <div class="text-muted-foreground font-mono text-xs">{item.id}</div>
+ </div>
+ <div class="text-muted-foreground shrink-0 text-xs">{formatSwarmTimestamp(item.updatedAt)}</div>
+ </div>
+ </button>
+
+ {#if selectedId === item.id}
+ <div class="space-y-3 border-t px-4 pt-4 pb-5">
+ <div class="flex items-center gap-2">
+ <div class="text-muted-foreground font-mono text-xs">{item.id}</div>
+ <CopyButton text={item.id} />
+ </div>
+ <p class="text-muted-foreground text-sm">{messages.immutableNotice}</p>
+ <Input placeholder={messages.namePlaceholder} bind:value={editName} readonly />
+ <Textarea
+ rows={12}
+ bind:value={editData}
+ placeholder={messages.dataPlaceholder}
+ class="font-mono text-xs"
+ readonly
+ />
+ <div class="flex flex-wrap items-center gap-2 pt-1">
+ <ArcaneButton
+ action="remove"
+ customLabel={messages.deleteButton}
+ icon={TrashIcon}
+ onclick={() => handleRemove(item)}
+ disabled={!canManage || isLoading.delete}
+ loading={isLoading.delete}
+ />
+ </div>
+ </div>
+ {/if}
+ </Card.Root>
+ {/each}
+ {/if}
+ </Card.Content>
+ </Card.Root>
+ </div>
+ </div>
+ {/snippet}
+</ResourcePageLayout>
diff --git a/frontend/src/lib/components/ui/calendar/calendar.svelte b/frontend/src/lib/components/ui/calendar/calendar.svelte
index 482e52900..c75a8799a 100644
--- a/frontend/src/lib/components/ui/calendar/calendar.svelte
+++ b/frontend/src/lib/components/ui/calendar/calendar.svelte
@@ -1,6 +1,19 @@
<script lang="ts">
import { Calendar as CalendarPrimitive } from 'bits-ui';
- import * as Calendar from './index.js';
+ import Cell from './calendar-cell.svelte';
+ import Day from './calendar-day.svelte';
+ import Grid from './calendar-grid.svelte';
+ import Header from './calendar-header.svelte';
+ import Months from './calendar-months.svelte';
+ import GridRow from './calendar-grid-row.svelte';
+ import GridBody from './calendar-grid-body.svelte';
+ import GridHead from './calendar-grid-head.svelte';
+ import HeadCell from './calendar-head-cell.svelte';
+ import NextButton from './calendar-next-button.svelte';
+ import PrevButton from './calendar-prev-button.svelte';
+ import Month from './calendar-month.svelte';
+ import Nav from './calendar-nav.svelte';
+ import Caption from './calendar-caption.svelte';
import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';
import type { ButtonVariant } from '../button/button.svelte';
import { isEqualMonth, type DateValue } from '@internationalized/date';
@@ -59,15 +72,15 @@ get along, so we shut typescript up by casting `value` to `never`.
{...restProps}
>
{#snippet children({ months, weekdays })}
- <Calendar.Months>
- <Calendar.Nav>
- <Calendar.PrevButton variant={buttonVariant} />
- <Calendar.NextButton variant={buttonVariant} />
- </Calendar.Nav>
+ <Months>
+ <Nav>
+ <PrevButton variant={buttonVariant} />
+ <NextButton variant={buttonVariant} />
+ </Nav>
{#each months as month, monthIndex (month)}
- <Calendar.Month>
- <Calendar.Header>
- <Calendar.Caption
+ <Month>
+ <Header>
+ <Caption
{captionLayout}
months={monthsProp}
{monthFormat}
@@ -78,38 +91,38 @@ get along, so we shut typescript up by casting `value` to `never`.
{locale}
{monthIndex}
/>
- </Calendar.Header>
- <Calendar.Grid>
- <Calendar.GridHead>
- <Calendar.GridRow class="select-none">
+ </Header>
+ <Grid>
+ <GridHead>
+ <GridRow class="select-none">
{#each weekdays as weekday (weekday)}
- <Calendar.HeadCell>
+ <HeadCell>
{weekday.slice(0, 2)}
- </Calendar.HeadCell>
+ </HeadCell>
{/each}
- </Calendar.GridRow>
- </Calendar.GridHead>
- <Calendar.GridBody>
+ </GridRow>
+ </GridHead>
+ <GridBody>
{#each month.weeks as weekDates (weekDates)}
- <Calendar.GridRow class="mt-2 w-full">
+ <GridRow class="mt-2 w-full">
{#each weekDates as date (date)}
- <Calendar.Cell {date} month={month.value}>
+ <Cell {date} month={month.value}>
{#if day}
{@render day({
day: date,
outsideMonth: !isEqualMonth(date, month.value)
})}
{:else}
- <Calendar.Day />
+ <Day />
{/if}
- </Calendar.Cell>
+ </Cell>
{/each}
- </Calendar.GridRow>
+ </GridRow>
{/each}
- </Calendar.GridBody>
- </Calendar.Grid>
- </Calendar.Month>
+ </GridBody>
+ </Grid>
+ </Month>
{/each}
- </Calendar.Months>
+ </Months>
{/snippet}
</CalendarPrimitive.Root>
diff --git a/frontend/src/lib/components/ui/carousel/carousel-control.svelte b/frontend/src/lib/components/ui/carousel/carousel-control.svelte
new file mode 100644
index 000000000..7086a4ee3
--- /dev/null
+++ b/frontend/src/lib/components/ui/carousel/carousel-control.svelte
@@ -0,0 +1,48 @@
+<script lang="ts">
+ import type { Component } from 'svelte';
+ import type { WithoutChildren } from 'bits-ui';
+ import { getEmblaContext } from './context.js';
+ import { cn } from '$lib/utils.js';
+ import { Button, type Props } from '$lib/components/ui/button/index.js';
+
+ let {
+ ref = $bindable(null),
+ class: className,
+ variant = 'outline',
+ size = 'icon',
+ direction,
+ icon: Icon,
+ label,
+ ...restProps
+ }: WithoutChildren<Props> & {
+ direction: 'previous' | 'next';
+ icon: Component;
+ label: string;
+ } = $props();
+
+ // svelte-ignore state_referenced_locally -- direction is fixed per wrapper component.
+ const emblaCtx = getEmblaContext(direction === 'next' ? '<Carousel.Next/>' : '<Carousel.Previous/>');
+ const isNext = $derived(direction === 'next');
+ const canScroll = $derived(isNext ? emblaCtx.canScrollNext : emblaCtx.canScrollPrev);
+ const positionClass = $derived(
+ emblaCtx.orientation === 'horizontal'
+ ? `${isNext ? '-end-12' : '-start-12'} top-1/2 -translate-y-1/2`
+ : `start-1/2 ${isNext ? '-bottom-12' : '-top-12'} -translate-x-1/2 rotate-90`
+ );
+</script>
+
+<Button
+ data-slot={`carousel-${direction}`}
+ {variant}
+ {size}
+ aria-disabled={!canScroll}
+ disabled={!canScroll}
+ class={cn('absolute size-8 touch-manipulation rounded-full', positionClass, className)}
+ onclick={isNext ? emblaCtx.scrollNext : emblaCtx.scrollPrev}
+ onkeydown={emblaCtx.handleKeyDown}
+ bind:ref
+ {...restProps}
+>
+ <Icon class="size-4" />
+ <span class="sr-only">{label}</span>
+</Button>
diff --git a/frontend/src/lib/components/ui/carousel/carousel-next.svelte b/frontend/src/lib/components/ui/carousel/carousel-next.svelte
index 67c59d9e2..a1788b89d 100644
--- a/frontend/src/lib/components/ui/carousel/carousel-next.svelte
+++ b/frontend/src/lib/components/ui/carousel/carousel-next.svelte
@@ -1,39 +1,10 @@
<script lang="ts">
import type { WithoutChildren } from 'bits-ui';
import { ArrowRightIcon } from '$lib/icons';
- import { getEmblaContext } from './context.js';
- import { cn } from '$lib/utils.js';
- import { Button, type Props } from '$lib/components/ui/button/index.js';
+ import type { Props } from '$lib/components/ui/button/index.js';
+ import CarouselControl from './carousel-control.svelte';
- let {
- ref = $bindable(null),
- class: className,
- variant = 'outline',
- size = 'icon',
- ...restProps
- }: WithoutChildren<Props> = $props();
-
- const emblaCtx = getEmblaContext('<Carousel.Next/>');
+ let { ref = $bindable(null), ...restProps }: WithoutChildren<Props> = $props();
</script>
-<Button
- data-slot="carousel-next"
- {variant}
- {size}
- aria-disabled={!emblaCtx.canScrollNext}
- disabled={!emblaCtx.canScrollNext}
- class={cn(
- 'absolute size-8 touch-manipulation rounded-full',
- emblaCtx.orientation === 'horizontal'
- ? '-end-12 top-1/2 -translate-y-1/2'
- : 'start-1/2 -bottom-12 -translate-x-1/2 rotate-90',
- className
- )}
- onclick={emblaCtx.scrollNext}
- onkeydown={emblaCtx.handleKeyDown}
- bind:ref
- {...restProps}
->
- <ArrowRightIcon class="size-4" />
- <span class="sr-only">Next slide</span>
-</Button>
+<CarouselControl bind:ref direction="next" icon={ArrowRightIcon} label="Next slide" {...restProps} />
diff --git a/frontend/src/lib/components/ui/carousel/carousel-previous.svelte b/frontend/src/lib/components/ui/carousel/carousel-previous.svelte
index 4af3304d0..507d8b906 100644
--- a/frontend/src/lib/components/ui/carousel/carousel-previous.svelte
+++ b/frontend/src/lib/components/ui/carousel/carousel-previous.svelte
@@ -1,37 +1,10 @@
<script lang="ts">
import type { WithoutChildren } from 'bits-ui';
import { ArrowLeftIcon } from '$lib/icons';
- import { getEmblaContext } from './context.js';
- import { cn } from '$lib/utils.js';
- import { Button, type Props } from '$lib/components/ui/button/index.js';
+ import type { Props } from '$lib/components/ui/button/index.js';
+ import CarouselControl from './carousel-control.svelte';
- let {
- ref = $bindable(null),
- class: className,
- variant = 'outline',
- size = 'icon',
- ...restProps
- }: WithoutChildren<Props> = $props();
-
- const emblaCtx = getEmblaContext('<Carousel.Previous/>');
+ let { ref = $bindable(null), ...restProps }: WithoutChildren<Props> = $props();
</script>
-<Button
- data-slot="carousel-previous"
- {variant}
- {size}
- aria-disabled={!emblaCtx.canScrollPrev}
- disabled={!emblaCtx.canScrollPrev}
- class={cn(
- 'absolute size-8 touch-manipulation rounded-full',
- emblaCtx.orientation === 'horizontal' ? '-start-12 top-1/2 -translate-y-1/2' : 'start-1/2 -top-12 -translate-x-1/2 rotate-90',
- className
- )}
- onclick={emblaCtx.scrollPrev}
- onkeydown={emblaCtx.handleKeyDown}
- {...restProps}
- bind:ref
->
- <ArrowLeftIcon class="size-4" />
- <span class="sr-only">Previous slide</span>
-</Button>
+<CarouselControl bind:ref direction="previous" icon={ArrowLeftIcon} label="Previous slide" {...restProps} />
diff --git a/frontend/src/lib/components/ui/dialog/dialog-content.svelte b/frontend/src/lib/components/ui/dialog/dialog-content.svelte
index e2752e403..bef718b56 100644
--- a/frontend/src/lib/components/ui/dialog/dialog-content.svelte
+++ b/frontend/src/lib/components/ui/dialog/dialog-content.svelte
@@ -2,7 +2,7 @@
import { Dialog as DialogPrimitive } from 'bits-ui';
import { CloseIcon } from '$lib/icons';
import type { Snippet } from 'svelte';
- import * as Dialog from './index.js';
+ import Overlay from './dialog-overlay.svelte';
import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';
let {
@@ -21,8 +21,8 @@
} = $props();
</script>
-<Dialog.Portal {...portalProps}>
- <Dialog.Overlay class={overlayClass} />
+<DialogPrimitive.Portal {...portalProps}>
+ <Overlay class={overlayClass} />
<DialogPrimitive.Content
bind:ref
data-slot="dialog-content"
@@ -42,4 +42,4 @@
</DialogPrimitive.Close>
{/if}
</DialogPrimitive.Content>
-</Dialog.Portal>
+</DialogPrimitive.Portal>
diff --git a/frontend/src/lib/components/ui/field-set/field-set.svelte b/frontend/src/lib/components/ui/field-set/field-set.svelte
index 28eff61a2..b9ac02d78 100644
--- a/frontend/src/lib/components/ui/field-set/field-set.svelte
+++ b/frontend/src/lib/components/ui/field-set/field-set.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import { cn } from '$lib/utils';
- import { fieldSetVariants } from '.';
+ import { fieldSetVariants } from './variants';
import type { FieldSetRootProps } from './types';
let { ref = $bindable(null), variant = 'default', children, class: className, ...rest }: FieldSetRootProps = $props();
diff --git a/frontend/src/lib/components/ui/field-set/index.ts b/frontend/src/lib/components/ui/field-set/index.ts
index c440a00f8..c0518a026 100644
--- a/frontend/src/lib/components/ui/field-set/index.ts
+++ b/frontend/src/lib/components/ui/field-set/index.ts
@@ -3,19 +3,7 @@ import Content from './field-set-content.svelte';
import Footer from './field-set-footer.svelte';
import Title from './field-set-title.svelte';
import type { FieldSetRootProps, FieldSetTitleProps, FieldSetContentProps, FieldSetFooterProps } from './types';
-import { tv, type VariantProps } from 'tailwind-variants';
-
-export const fieldSetVariants = tv({
- base: 'border-border flex h-fit w-full flex-col rounded-lg border',
- variants: {
- variant: {
- default: 'border-border bg-card',
- destructive: 'border-destructive'
- }
- }
-});
-
-export type Variant = VariantProps<typeof fieldSetVariants>['variant'];
+export { fieldSetVariants, type Variant } from './variants';
export {
Root,
diff --git a/frontend/src/lib/components/ui/field-set/variants.ts b/frontend/src/lib/components/ui/field-set/variants.ts
new file mode 100644
index 000000000..06b3187f7
--- /dev/null
+++ b/frontend/src/lib/components/ui/field-set/variants.ts
@@ -0,0 +1,13 @@
+import { tv, type VariantProps } from 'tailwind-variants';
+
+export const fieldSetVariants = tv({
+ base: 'border-border flex h-fit w-full flex-col rounded-lg border',
+ variants: {
+ variant: {
+ default: 'border-border bg-card',
+ destructive: 'border-destructive'
+ }
+ }
+});
+
+export type Variant = VariantProps<typeof fieldSetVariants>['variant'];
diff --git a/frontend/src/lib/components/ui/file-drop-zone/display-size.ts b/frontend/src/lib/components/ui/file-drop-zone/display-size.ts
new file mode 100644
index 000000000..0dda79eff
--- /dev/null
+++ b/frontend/src/lib/components/ui/file-drop-zone/display-size.ts
@@ -0,0 +1,14 @@
+export const BYTE = 1;
+export const KILOBYTE = 1024;
+export const MEGABYTE = 1024 * KILOBYTE;
+export const GIGABYTE = 1024 * MEGABYTE;
+
+export const displaySize = (bytes: number): string => {
+ if (bytes < KILOBYTE) return `${bytes.toFixed(0)} B`;
+
+ if (bytes < MEGABYTE) return `${(bytes / KILOBYTE).toFixed(0)} KB`;
+
+ if (bytes < GIGABYTE) return `${(bytes / MEGABYTE).toFixed(0)} MB`;
+
+ return `${(bytes / GIGABYTE).toFixed(0)} GB`;
+};
diff --git a/frontend/src/lib/components/ui/file-drop-zone/file-drop-zone.svelte b/frontend/src/lib/components/ui/file-drop-zone/file-drop-zone.svelte
index 2d638acbd..b32479529 100644
--- a/frontend/src/lib/components/ui/file-drop-zone/file-drop-zone.svelte
+++ b/frontend/src/lib/components/ui/file-drop-zone/file-drop-zone.svelte
@@ -1,7 +1,7 @@
<script lang="ts">
import { cn } from '$lib/utils';
import { UpdateIcon } from '$lib/icons';
- import { displaySize } from '.';
+ import { displaySize } from './display-size';
import { useId } from 'bits-ui';
import type { FileDropZoneProps, FileRejectedReason } from './types';
import { m } from '$lib/paraglide/messages';
diff --git a/frontend/src/lib/components/ui/file-drop-zone/index.ts b/frontend/src/lib/components/ui/file-drop-zone/index.ts
index 938586870..da82c7095 100644
--- a/frontend/src/lib/components/ui/file-drop-zone/index.ts
+++ b/frontend/src/lib/components/ui/file-drop-zone/index.ts
@@ -1,21 +1,6 @@
import FileDropZone from './file-drop-zone.svelte';
import { type FileRejectedReason, type FileDropZoneProps } from './types';
-
-export const displaySize = (bytes: number): string => {
- if (bytes < KILOBYTE) return `${bytes.toFixed(0)} B`;
-
- if (bytes < MEGABYTE) return `${(bytes / KILOBYTE).toFixed(0)} KB`;
-
- if (bytes < GIGABYTE) return `${(bytes / MEGABYTE).toFixed(0)} MB`;
-
- return `${(bytes / GIGABYTE).toFixed(0)} GB`;
-};
-
-// Utilities for working with file sizes
-export const BYTE = 1;
-export const KILOBYTE = 1024;
-export const MEGABYTE = 1024 * KILOBYTE;
-export const GIGABYTE = 1024 * MEGABYTE;
+export { BYTE, KILOBYTE, MEGABYTE, GIGABYTE, displaySize } from './display-size';
// utilities for limiting accepted files
export const ACCEPT_IMAGE = 'image/*';
diff --git a/frontend/src/lib/components/ui/scroll-area/scroll-area.svelte b/frontend/src/lib/components/ui/scroll-area/scroll-area.svelte
index b96f2a9dc..d721ad903 100644
--- a/frontend/src/lib/components/ui/scroll-area/scroll-area.svelte
+++ b/frontend/src/lib/components/ui/scroll-area/scroll-area.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import { ScrollArea as ScrollAreaPrimitive } from 'bits-ui';
- import { Scrollbar } from './index.js';
+ import Scrollbar from './scroll-area-scrollbar.svelte';
import { cn, type WithoutChild } from '$lib/utils.js';
let {
diff --git a/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte b/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
index b98932657..da671b2a1 100644
--- a/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
+++ b/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
@@ -9,12 +9,12 @@
import { formatTime } from '$lib/utils/formatting';
import { queryKeys } from '$lib/query/query-keys';
import { vulnerabilityService } from '$lib/services/vulnerability-service';
- import { activityToastOptions, extractActivityId } from '$lib/utils/activity-toast';
import {
startVulnerabilityScanPolling,
stabilizeFailedVulnerabilitySummary,
isVulnerabilityScanInProgress
} from '$lib/utils/docker';
+ import { toastVulnerabilityScanStatus } from '$lib/utils/vulnerability';
import { ShieldCheckIcon, ShieldAlertIcon, ScanIcon, ShieldXIcon } from '$lib/icons';
import { createMutation, useQueryClient } from '@tanstack/svelte-query';
@@ -142,13 +142,11 @@
};
scanSummary = summary;
onScanned?.(summary);
- if (result.status === 'completed') {
- toast.success(m.vuln_scan_completed(), activityToastOptions(result.activityId));
- } else if (result.status === 'failed') {
- toast.error(result.error || m.vuln_scan_failed(), activityToastOptions(result.activityId));
- } else if (pollingEnabled) {
- toast.info(m.vuln_scan_started(), activityToastOptions(result.activityId));
+ if (isVulnerabilityScanInProgress(result.status) && pollingEnabled) {
+ toastVulnerabilityScanStatus(result, { includeStarted: true });
beginPolling(true);
+ } else {
+ toastVulnerabilityScanStatus(result);
}
}
} catch (error) {
@@ -210,12 +208,7 @@
stopScanPolling();
if (showToast) {
- const toastOptions = activityToastOptions(extractActivityId(resolvedSummary));
- if (resolvedSummary.status === 'completed') {
- toast.success(m.vuln_scan_completed(), toastOptions);
- } else {
- toast.error(resolvedSummary.error || m.vuln_scan_failed(), toastOptions);
- }
+ toastVulnerabilityScanStatus(resolvedSummary);
}
},
onError: () => {}
diff --git a/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte b/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte
index 92c65da01..3c4160439 100644
--- a/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte
+++ b/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte
@@ -9,10 +9,16 @@
import { m } from '$lib/paraglide/messages';
import { vulnerabilityService } from '$lib/services/vulnerability-service.js';
import type { ColumnSpec } from '$lib/components/arcane-table/arcane-table.types.svelte';
- import type { VulnerabilityScanResult, Vulnerability as VulnType, SeveritySummary } from '$lib/types/environment';
+ import type { VulnerabilityScanResult, Vulnerability as VulnType } from '$lib/types/environment';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import { ShieldCheckIcon, ShieldAlertIcon, ShieldXIcon, ScanIcon, CodeIcon, CheckIcon } from '$lib/icons';
import { formatDateTime } from '$lib/utils/formatting';
+ import {
+ buildSeveritySummary,
+ getSeverityBadgeVariant,
+ getSeverityIconVariant,
+ getSeverityLabel
+ } from '$lib/utils/vulnerability';
import { useQueryClient } from '@tanstack/svelte-query';
interface Props {
@@ -28,39 +34,6 @@
type VulnerabilityRow = VulnType & { id: string };
- function buildSeveritySummary(vulns: VulnType[]): SeveritySummary {
- const summary: SeveritySummary = {
- critical: 0,
- high: 0,
- medium: 0,
- low: 0,
- unknown: 0,
- total: 0
- };
-
- for (const vuln of vulns) {
- switch (vuln.severity) {
- case 'CRITICAL':
- summary.critical++;
- break;
- case 'HIGH':
- summary.high++;
- break;
- case 'MEDIUM':
- summary.medium++;
- break;
- case 'LOW':
- summary.low++;
- break;
- default:
- summary.unknown++;
- }
- summary.total++;
- }
-
- return summary;
- }
-
const resolvedSummary = $derived.by(() => {
if (scan?.summary) return scan.summary;
if (scan?.vulnerabilities?.length) {
@@ -191,51 +164,6 @@
const isWorking = $derived.by(() => isScanning || scan?.status === 'scanning');
const hasError = $derived.by(() => scan?.status === 'failed' || !!scan?.error);
- function getSeverityLabel(severity: string): string {
- switch (severity) {
- case 'CRITICAL':
- return m.vuln_severity_critical();
- case 'HIGH':
- return m.vuln_severity_high();
- case 'MEDIUM':
- return m.vuln_severity_medium();
- case 'LOW':
- return m.vuln_severity_low();
- default:
- return m.vuln_severity_unknown();
- }
- }
-
- function getSeverityBadgeVariant(severity: string): 'red' | 'orange' | 'amber' | 'green' | 'gray' {
- switch (severity) {
- case 'CRITICAL':
- return 'red';
- case 'HIGH':
- return 'orange';
- case 'MEDIUM':
- return 'amber';
- case 'LOW':
- return 'green';
- default:
- return 'gray';
- }
- }
-
- function getSeverityIconVariant(severity: string): 'red' | 'orange' | 'amber' | 'emerald' | 'gray' {
- switch (severity) {
- case 'CRITICAL':
- return 'red';
- case 'HIGH':
- return 'orange';
- case 'MEDIUM':
- return 'amber';
- case 'LOW':
- return 'emerald';
- default:
- return 'gray';
- }
- }
-
function getVulnerabilityKey(vuln: VulnType, index: number): string {
return [vuln.vulnerabilityId, vuln.pkgName, vuln.installedVersion ?? '', vuln.fixedVersion ?? '', String(index)].join('-');
}
diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.ts
index a1c542f64..1ca9250ec 100644
--- a/frontend/src/lib/config/navigation-config.ts
+++ b/frontend/src/lib/config/navigation-config.ts
@@ -336,7 +336,7 @@ export function getCustomizeSubpageUrlsInNavOrder(): string[] {
return entry?.items?.map((item) => item.url) ?? [];
}
-export const defaultMobilePinnedItems: NavigationItem[] = [
+const defaultMobilePinnedItems: NavigationItem[] = [
navigationItems.managementItems[0]!,
navigationItems.managementItems[1]!,
navigationItems.resourceItems[0]!,
diff --git a/frontend/src/lib/hooks/index.ts b/frontend/src/lib/hooks/index.ts
deleted file mode 100644
index 2ad4ae524..000000000
--- a/frontend/src/lib/hooks/index.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export { IsMobile } from './is-mobile.svelte';
-export { IsTablet } from './is-tablet.svelte';
-export { IsTouchDevice } from './is-touch-device.svelte';
-export { UseClipboard } from './use-clipboard.svelte';
-export { useEnvironmentRefresh } from './use-environment-refresh.svelte';
-export { ScrollDirectionDetector, type ScrollDirection } from './use-scroll-direction.svelte';
-export { UseSettingsForm } from './use-settings-form.svelte';
diff --git a/frontend/src/lib/hooks/use-category-search.svelte.ts b/frontend/src/lib/hooks/use-category-search.svelte.ts
new file mode 100644
index 000000000..5111f2c52
--- /dev/null
+++ b/frontend/src/lib/hooks/use-category-search.svelte.ts
@@ -0,0 +1,83 @@
+import { debounced } from '$lib/utils/ws';
+
+type CategorySearchResponse<T> = {
+ results?: T[];
+};
+
+type UseCategorySearchOptions<T> = {
+ search: (query: string) => Promise<CategorySearchResponse<T>>;
+ filter: (category: T) => boolean;
+ onError?: (error: unknown) => void;
+};
+
+export function useCategorySearch<T>({ search, filter, onError }: UseCategorySearchOptions<T>) {
+ let searchQuery = $state('');
+ let showSearchResults = $state(false);
+ let searchResults = $state<T[]>([]);
+ let isSearching = $state(false);
+ let currentSearchRequest = 0;
+
+ async function performSearch(query: string) {
+ const trimmedQuery = query.trim();
+
+ if (!trimmedQuery) {
+ searchResults = [];
+ showSearchResults = false;
+ isSearching = false;
+ currentSearchRequest++;
+ return;
+ }
+
+ currentSearchRequest++;
+ const requestId = currentSearchRequest;
+ isSearching = true;
+ showSearchResults = true;
+
+ try {
+ const response = await search(trimmedQuery);
+ if (requestId === currentSearchRequest) {
+ searchResults = (response.results || []).filter(filter);
+ isSearching = false;
+ }
+ } catch (error) {
+ onError?.(error);
+ if (requestId === currentSearchRequest) {
+ searchResults = [];
+ isSearching = false;
+ }
+ }
+ }
+
+ const debouncedSearch = debounced((query: string) => {
+ void performSearch(query);
+ }, 300);
+
+ function clearSearch() {
+ searchQuery = '';
+ showSearchResults = false;
+ isSearching = false;
+ searchResults = [];
+ currentSearchRequest++;
+ }
+
+ return {
+ get searchQuery() {
+ return searchQuery;
+ },
+ set searchQuery(value: string) {
+ searchQuery = value;
+ },
+ get showSearchResults() {
+ return showSearchResults;
+ },
+ get searchResults() {
+ return searchResults;
+ },
+ get isSearching() {
+ return isSearching;
+ },
+ performSearch,
+ debouncedSearch,
+ clearSearch
+ };
+}
diff --git a/frontend/src/lib/hooks/use-clipboard.svelte.ts b/frontend/src/lib/hooks/use-clipboard.svelte.ts
index 01c12ead2..8220ac326 100644
--- a/frontend/src/lib/hooks/use-clipboard.svelte.ts
+++ b/frontend/src/lib/hooks/use-clipboard.svelte.ts
@@ -18,9 +18,9 @@ type Options = {
* </script>
*
* <button onclick={clipboard.copy('Hello, World!')}>
- * {#if clipboard.copied === 'success'}
+ * {#if clipboard.status === 'success'}
* Copied!
- * {:else if clipboard.copied === 'failure'}
+ * {:else if clipboard.status === 'failure'}
* Failed to copy!
* {:else}
* Copy
@@ -74,11 +74,6 @@ export class UseClipboard {
return this.#copiedStatus;
}
- /** true when the user has just copied to the clipboard. */
- get copied() {
- return this.#copiedStatus === 'success';
- }
-
/** Indicates whether a copy has occurred
* and gives a status of either `success` or `failure`. */
get status() {
diff --git a/frontend/src/lib/hooks/use-mobile-nav-interactions.ts b/frontend/src/lib/hooks/use-mobile-nav-interactions.ts
deleted file mode 100644
index 0d8894e3d..000000000
--- a/frontend/src/lib/hooks/use-mobile-nav-interactions.ts
+++ /dev/null
@@ -1,272 +0,0 @@
-import { ScrollDirectionDetector } from './use-scroll-direction.svelte';
-import { SwipeGestureDetector, type SwipeDirection } from './use-swipe-gesture.svelte';
-
-export interface MobileNavInteractionOptions {
- // Scroll detection options
- scrollThreshold?: number;
- scrollMinDistance?: number;
- scrollTopThreshold?: number;
- scrollChangeThreshold?: number;
-
- // Tap detection options
- tapDebounceTimeout?: number;
-
- // Swipe detection options
- swipeThreshold?: number;
- swipeVelocity?: number;
- swipeTimeLimit?: number;
-
- // Touch handling options
- touchEndDelay?: number;
- menuOpenRestoreDelay?: number;
- overlayFadeOutDelay?: number;
- wheelThreshold?: number;
-}
-
-export interface MobileNavInteractionCallbacks {
- onVisibilityChange: (visible: boolean) => void;
- onMenuOpen: () => void;
- onScrollDirectionChange?: (direction: string, scrollY: number) => void;
- shouldPreventTouch?: (menuOpen: boolean) => boolean;
-}
-
-export interface MobileNavInteractionState {
- menuOpen: boolean;
- scrollToHideEnabled: boolean;
- visible: boolean;
-}
-
-export class MobileNavInteractionManager {
- private readonly scrollDetector: ScrollDirectionDetector;
- private readonly swipeDetector: SwipeGestureDetector;
-
- private readonly options: Required<MobileNavInteractionOptions>;
- private readonly callbacks: MobileNavInteractionCallbacks;
- private state: MobileNavInteractionState;
-
- private navElement: HTMLElement | null = null;
- private lastScrollDirection: string | null = null;
- private lastScrollY = 0;
-
- // Touch handling state
- private touchStartTarget: HTMLElement | null = null;
- private isInteractiveTouch = false;
-
- // Cleanup functions
- private cleanupFunctions: (() => void)[] = [];
-
- constructor(callbacks: MobileNavInteractionCallbacks, options: MobileNavInteractionOptions = {}) {
- this.callbacks = callbacks;
- this.options = {
- scrollThreshold: options.scrollThreshold ?? 15,
- scrollMinDistance: options.scrollMinDistance ?? 100,
- scrollTopThreshold: options.scrollTopThreshold ?? 100,
- scrollChangeThreshold: options.scrollChangeThreshold ?? 50,
- tapDebounceTimeout: options.tapDebounceTimeout ?? 300,
- swipeThreshold: options.swipeThreshold ?? 20,
- swipeVelocity: options.swipeVelocity ?? 0.1,
- swipeTimeLimit: options.swipeTimeLimit ?? 1000,
- touchEndDelay: options.touchEndDelay ?? 150,
- menuOpenRestoreDelay: options.menuOpenRestoreDelay ?? 50,
- overlayFadeOutDelay: options.overlayFadeOutDelay ?? 200,
- wheelThreshold: options.wheelThreshold ?? 10
- };
-
- this.state = {
- menuOpen: false,
- scrollToHideEnabled: false,
- visible: true
- };
-
- // Initialize detectors directly in constructor
- this.scrollDetector = new ScrollDirectionDetector(this.options.scrollThreshold);
-
- this.swipeDetector = new SwipeGestureDetector(
- (direction: SwipeDirection) => {
- if (direction === 'up') {
- this.callbacks.onMenuOpen();
- }
- },
- {
- threshold: this.options.swipeThreshold,
- velocity: this.options.swipeVelocity,
- timeLimit: this.options.swipeTimeLimit
- }
- );
- }
-
- public updateState(newState: Partial<MobileNavInteractionState>) {
- this.state = { ...this.state, ...newState };
- }
-
- public resetVisibility() {
- this.state.visible = true;
- this.callbacks.onVisibilityChange(true);
- }
-
- public setupElement(element: HTMLElement | null) {
- // Cleanup previous setup
- this.cleanup();
-
- this.navElement = element;
-
- if (!element) return;
-
- // Setup swipe detection target
- this.swipeDetector.setElement(element);
-
- // Setup touch event handlers
- this.setupTouchHandlers(element);
-
- // Setup mouse event handlers for desktop/pointer devices
- this.setupMouseHandlers(element);
- }
-
- private setupTouchHandlers(element: HTMLElement) {
- const handleTouchStart = (e: TouchEvent) => {
- const shouldPreventTouch = this.callbacks.shouldPreventTouch?.(this.state.menuOpen);
- if (shouldPreventTouch) return;
-
- // Store touch start target and check if it's interactive
- this.touchStartTarget = e.target as HTMLElement;
- this.isInteractiveTouch = !!this.touchStartTarget.closest('button, a, [role="button"], input, select, textarea');
-
- // Don't prevent default or lock scrolling - let native behavior work
- // The CSS touch-action: pan-y will handle this properly
- };
-
- const handleTouchMove = (e: TouchEvent) => {
- const shouldPreventTouch = this.callbacks.shouldPreventTouch?.(this.state.menuOpen);
- if (shouldPreventTouch) return;
-
- // Don't prevent default - let native scrolling work
- // Only track if we moved off an interactive element
- if (this.isInteractiveTouch) {
- const touch = e.touches[0];
- if (!touch) return;
-
- const target = document.elementFromPoint(touch.clientX, touch.clientY) as HTMLElement;
- const stillOnInteractive = target && target.closest('button, a, [role="button"], input, select, textarea');
-
- if (!stillOnInteractive) {
- // Moved off interactive element, treat as gesture
- this.isInteractiveTouch = false;
- }
- }
- };
-
- const handleTouchEnd = () => {
- // Reset touch state
- this.touchStartTarget = null;
- this.isInteractiveTouch = false;
- };
-
- element.addEventListener('touchstart', handleTouchStart, { passive: true, capture: false });
- element.addEventListener('touchmove', handleTouchMove, { passive: true, capture: false });
- element.addEventListener('touchend', handleTouchEnd, { passive: true, capture: false });
-
- // Store cleanup functions
- this.cleanupFunctions.push(() => {
- element.removeEventListener('touchstart', handleTouchStart);
- element.removeEventListener('touchmove', handleTouchMove);
- element.removeEventListener('touchend', handleTouchEnd);
- });
- }
-
- private setupMouseHandlers(element: HTMLElement) {
- const handleWheel = (e: WheelEvent) => {
- // Don't prevent default - let page scroll naturally
- // Only respond to downward gestures on the navbar itself to open menu
- if (e.deltaY > this.options.wheelThreshold) {
- this.callbacks.onMenuOpen();
- }
- };
-
- const handleMouseEnter = () => {
- // Don't lock scrolling or manipulate pointer events
- // Just listen for wheel events on the navbar
- element.addEventListener('wheel', handleWheel, { passive: true });
- };
-
- const handleMouseLeave = () => {
- // Clean up wheel listener
- element.removeEventListener('wheel', handleWheel);
- };
-
- element.addEventListener('mouseenter', handleMouseEnter);
- element.addEventListener('mouseleave', handleMouseLeave);
-
- // Store cleanup functions
- this.cleanupFunctions.push(() => {
- element.removeEventListener('mouseenter', handleMouseEnter);
- element.removeEventListener('mouseleave', handleMouseLeave);
- element.removeEventListener('wheel', handleWheel);
- });
- }
-
- public handleScrollEffect(direction: string, scrollY: number) {
- // Only update when scroll direction or position changes significantly
- if (
- (direction !== this.lastScrollDirection || Math.abs(scrollY - this.lastScrollY) > this.options.scrollChangeThreshold) &&
- this.state.scrollToHideEnabled
- ) {
- this.lastScrollDirection = direction;
- this.lastScrollY = scrollY;
-
- // Call optional callback
- this.callbacks.onScrollDirectionChange?.(direction, scrollY);
-
- // Update visibility state based on scroll behavior
- if (direction === 'down' && scrollY > this.options.scrollMinDistance) {
- this.state.visible = false;
- this.callbacks.onVisibilityChange(false);
- } else if (direction === 'up') {
- this.state.visible = true;
- this.callbacks.onVisibilityChange(true);
- } else if (direction === 'idle' && scrollY <= this.options.scrollTopThreshold) {
- this.state.visible = true;
- this.callbacks.onVisibilityChange(true);
- }
- }
- }
-
- public handleMenuStateChange(previousMenuOpen: boolean, currentMenuOpen: boolean) {
- // If menu was open and is now closed, make navigation bar visible
- if (previousMenuOpen && !currentMenuOpen) {
- this.state.visible = true;
- this.callbacks.onVisibilityChange(true);
- }
- }
-
- public cleanup() {
- // Cleanup all event listeners
- this.cleanupFunctions.forEach((fn) => fn());
- this.cleanupFunctions = [];
-
- // Cleanup scroll detector
- this.scrollDetector.cleanup();
-
- // Clean up any remaining styles
- if (document.body) {
- document.body.style.pointerEvents = '';
- }
-
- if (this.navElement) {
- this.navElement.style.pointerEvents = '';
- }
- }
-
- // Getters for accessing detectors
- public get scrollDirection() {
- return this.scrollDetector.direction;
- }
-
- public get scrollY() {
- return this.scrollDetector.scrollY;
- }
-}
-
-// Convenience function for Svelte components
-export function createMobileNavInteractions(callbacks: MobileNavInteractionCallbacks, options: MobileNavInteractionOptions = {}) {
- return new MobileNavInteractionManager(callbacks, options);
-}
diff --git a/frontend/src/lib/hooks/use-responsive-table-limit.svelte.ts b/frontend/src/lib/hooks/use-responsive-table-limit.svelte.ts
new file mode 100644
index 000000000..deb5bfb19
--- /dev/null
+++ b/frontend/src/lib/hooks/use-responsive-table-limit.svelte.ts
@@ -0,0 +1,79 @@
+import type { SearchPaginationSortRequest } from '$lib/types/shared';
+import { IsMobile } from './is-mobile.svelte';
+
+const MOBILE_ROWS = 4;
+const ROW_HEIGHT = 57;
+const HEADER_HEIGHT = 145;
+const FOOTER_HEIGHT = 48;
+const MIN_ROWS = 3;
+const MAX_ROWS = 50;
+const DEFAULT_ROWS = 5;
+
+type ResponsiveTableLimitOptions = {
+ initialLimit?: number;
+ sort: NonNullable<SearchPaginationSortRequest['sort']>;
+ getTotalItems: () => number;
+};
+
+export function useResponsiveTableLimit({ initialLimit = DEFAULT_ROWS, sort, getTotalItems }: ResponsiveTableLimitOptions) {
+ const isMobile = new IsMobile();
+ let measuredHeight = $state(0);
+ let baseRequestOptions = $state<SearchPaginationSortRequest>({
+ pagination: { page: 1, limit: initialLimit },
+ sort
+ });
+
+ function shouldReserveFooter(limit: number) {
+ return getTotalItems() > limit;
+ }
+
+ function calculateLimitForHeight(height: number) {
+ if (isMobile.current) return MOBILE_ROWS;
+ if (height <= 0) return DEFAULT_ROWS;
+
+ let availableHeight = height - HEADER_HEIGHT;
+ const initialRows = Math.floor(Math.max(0, availableHeight) / ROW_HEIGHT);
+ const footerLimit = Math.max(MIN_ROWS, Math.min(MAX_ROWS, initialRows));
+ if (shouldReserveFooter(footerLimit)) {
+ availableHeight -= FOOTER_HEIGHT;
+ }
+
+ const rows = Math.floor(Math.max(0, availableHeight) / ROW_HEIGHT);
+ return Math.max(MIN_ROWS, Math.min(MAX_ROWS, rows));
+ }
+
+ const displayLimit = $derived(calculateLimitForHeight(measuredHeight));
+ const requestOptions = $derived.by(() => {
+ const limit = displayLimit;
+ if (baseRequestOptions.pagination?.limit === limit) return baseRequestOptions;
+
+ return {
+ ...baseRequestOptions,
+ pagination: {
+ page: baseRequestOptions.pagination?.page ?? 1,
+ limit
+ }
+ };
+ });
+
+ return {
+ get displayLimit() {
+ return displayLimit;
+ },
+ get measuredHeight() {
+ return measuredHeight;
+ },
+ set measuredHeight(value: number) {
+ measuredHeight = value;
+ },
+ get requestOptions() {
+ return requestOptions;
+ },
+ set requestOptions(value: SearchPaginationSortRequest) {
+ baseRequestOptions = value;
+ },
+ shouldShowFooter(dataLength: number) {
+ return dataLength >= displayLimit && getTotalItems() > displayLimit;
+ }
+ };
+}
diff --git a/frontend/src/lib/hooks/use-scroll-direction.svelte.ts b/frontend/src/lib/hooks/use-scroll-direction.svelte.ts
deleted file mode 100644
index 1b7a47d94..000000000
--- a/frontend/src/lib/hooks/use-scroll-direction.svelte.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { untrack } from 'svelte';
-
-export type ScrollDirection = 'up' | 'down' | 'idle';
-
-export class ScrollDirectionDetector {
- private _lastScrollY = $state(0);
- private _scrollDirection = $state<ScrollDirection>('idle');
- private _isScrolling = $state(false);
- private scrollThreshold: number;
- private scrollTimeout: ReturnType<typeof setTimeout> | null = null;
- private cleanupFn: (() => void) | null = null;
- private initialized = false;
-
- constructor(threshold = 10) {
- this.scrollThreshold = threshold;
- }
-
- private init() {
- if (this.initialized || typeof window === 'undefined') return;
- this.initialized = true;
-
- this._lastScrollY = window.scrollY;
-
- const handleScroll = () => {
- const currentScrollY = window.scrollY;
- const scrollDiff = currentScrollY - untrack(() => this._lastScrollY);
-
- if (Math.abs(scrollDiff) > this.scrollThreshold) {
- const newDirection: ScrollDirection = scrollDiff > 0 ? 'down' : 'up';
-
- if (untrack(() => this._scrollDirection) !== newDirection) {
- this._scrollDirection = newDirection;
- }
- this._lastScrollY = currentScrollY;
- }
-
- this._isScrolling = true;
-
- if (this.scrollTimeout) {
- clearTimeout(this.scrollTimeout);
- }
-
- this.scrollTimeout = setTimeout(() => {
- this._scrollDirection = 'idle';
- this._isScrolling = false;
- }, 150);
- };
-
- window.addEventListener('scroll', handleScroll, { passive: true });
-
- this.cleanupFn = () => {
- window.removeEventListener('scroll', handleScroll);
- if (this.scrollTimeout) {
- clearTimeout(this.scrollTimeout);
- }
- };
- }
-
- cleanup() {
- if (this.cleanupFn) {
- this.cleanupFn();
- this.cleanupFn = null;
- }
- this.initialized = false;
- }
-
- get direction() {
- this.init();
- return this._scrollDirection;
- }
-
- get scrolling() {
- this.init();
- return this._isScrolling;
- }
-
- get scrollY() {
- this.init();
- return this._lastScrollY;
- }
-}
diff --git a/frontend/src/lib/hooks/use-settings-form.svelte.ts b/frontend/src/lib/hooks/use-settings-form.svelte.ts
index 4d4467b1e..19870a8b0 100644
--- a/frontend/src/lib/hooks/use-settings-form.svelte.ts
+++ b/frontend/src/lib/hooks/use-settings-form.svelte.ts
@@ -55,7 +55,7 @@ export class UseSettingsForm<
// Sync to external context (side effect)
if (this.formState) {
this.formState.hasChanges = this.hasChanges;
- this.formState.isLoading = this.#isLoading;
+ this.formState.isLoading = this.isLoading;
if (this.#saveFunction) this.formState.saveFunction = this.#saveFunction;
if (this.#resetFunction) this.formState.resetFunction = this.#resetFunction;
}
diff --git a/frontend/src/lib/hooks/use-upgrade-check.svelte.ts b/frontend/src/lib/hooks/use-upgrade-check.svelte.ts
new file mode 100644
index 000000000..41c2d0009
--- /dev/null
+++ b/frontend/src/lib/hooks/use-upgrade-check.svelte.ts
@@ -0,0 +1,105 @@
+import { m } from '$lib/paraglide/messages';
+import { queryKeys } from '$lib/query/query-keys';
+import systemUpgradeService from '$lib/services/api/system-upgrade-service';
+import type { AppVersionInformation } from '$lib/types/settings';
+import { extractApiErrorMessage } from '$lib/utils/api';
+import { hasPermission } from '$lib/utils/auth';
+import { createMutation, createQuery } from '@tanstack/svelte-query';
+import { toast } from 'svelte-sonner';
+
+type UseUpgradeCheckOptions = {
+ queryScope: 'mobile-nav' | 'sidebar';
+ getVersionInformation: () => AppVersionInformation | undefined;
+ getDebug?: () => boolean;
+};
+
+export function useUpgradeCheck({ queryScope, getVersionInformation, getDebug = () => false }: UseUpgradeCheckOptions) {
+ let upgrading = $state(false);
+ let showConfirmDialog = $state(false);
+
+ const canInstallUpdates = $derived(hasPermission('environments:update'));
+ const shouldCheckUpgrade = $derived(!!(getVersionInformation()?.updateAvailable && canInstallUpdates && !getDebug()));
+ const upgradeAvailabilityQuery = createQuery(() => ({
+ queryKey: queryKeys.system.upgradeAvailable(queryScope),
+ queryFn: () => systemUpgradeService.checkUpgradeAvailable(),
+ enabled: shouldCheckUpgrade,
+ staleTime: 0
+ }));
+
+ const canUpgrade = $derived.by(() => {
+ if (getDebug()) return true;
+ const result = upgradeAvailabilityQuery.data;
+ return !!result?.canUpgrade && !result?.error;
+ });
+ const checkingUpgrade = $derived(
+ !!(shouldCheckUpgrade && (upgradeAvailabilityQuery.isPending || upgradeAvailabilityQuery.isFetching))
+ );
+ const shouldShowUpgrade = $derived((canUpgrade && canInstallUpdates) || getDebug());
+
+ const updateType = $derived.by(() => {
+ const versionInformation = getVersionInformation();
+ if (!versionInformation) return 'none';
+ if (versionInformation.isSemverVersion) return 'semver';
+ if (versionInformation.currentTag && versionInformation.newestDigest) return 'digest';
+ return 'none';
+ });
+
+ const versionChip = $derived.by(() => {
+ const versionInformation = getVersionInformation();
+ if (!versionInformation) return '';
+ if (updateType === 'semver') return versionInformation.newestVersion ?? '';
+ if (updateType === 'digest') return versionInformation.currentTag ?? '';
+ return '';
+ });
+
+ const shouldShowBanner = $derived(getVersionInformation()?.updateAvailable || getDebug());
+ const triggerUpgradeMutation = createMutation(() => ({
+ mutationFn: () => systemUpgradeService.triggerUpgrade(),
+ onError: (error: unknown) => {
+ const errorMessage = extractApiErrorMessage(error);
+ const wrappedPrefix = m.upgrade_failed({ error: '' });
+ toast.error(errorMessage.startsWith(wrappedPrefix) ? errorMessage : m.upgrade_failed({ error: errorMessage }));
+ upgrading = false;
+ }
+ }));
+
+ function openDialog() {
+ showConfirmDialog = true;
+ }
+
+ function confirmUpgrade() {
+ triggerUpgradeMutation.mutate();
+ }
+
+ return {
+ get upgrading() {
+ return upgrading;
+ },
+ set upgrading(value: boolean) {
+ upgrading = value;
+ },
+ get showConfirmDialog() {
+ return showConfirmDialog;
+ },
+ set showConfirmDialog(value: boolean) {
+ showConfirmDialog = value;
+ },
+ get canInstallUpdates() {
+ return canInstallUpdates;
+ },
+ get checkingUpgrade() {
+ return checkingUpgrade;
+ },
+ get shouldShowUpgrade() {
+ return shouldShowUpgrade;
+ },
+ get versionChip() {
+ return versionChip;
+ },
+ get shouldShowBanner() {
+ return shouldShowBanner;
+ },
+ openDialog,
+ confirmUpgrade
+ };
+}
diff --git a/frontend/src/lib/icons/index.ts b/frontend/src/lib/icons/index.ts
index d651c81d9..fa041834e 100644
--- a/frontend/src/lib/icons/index.ts
+++ b/frontend/src/lib/icons/index.ts
@@ -95,7 +95,6 @@ export { default as ConnectionIcon } from 'virtual:icons/gravity-ui/plug-connect
export { default as LayersIcon } from 'virtual:icons/solar/layers-minimalistic-linear';
export { default as HashIcon } from 'virtual:icons/gravity-ui/hashtag';
export { default as LocalFolderComputerIcon } from 'virtual:icons/streamline/local-storage-folder-remix';
-export { default as MinusIcon } from 'virtual:icons/solar/minus-circle-linear';
export { default as SendEmailIcon } from 'virtual:icons/solar/plain-2-linear';
export { default as VolumeUnusedIcon } from 'virtual:icons/clarity/hard-disk-solid-alerted';
export { default as OpenIdIcon } from 'virtual:icons/simple-icons/openid';
diff --git a/frontend/src/lib/layouts/index.ts b/frontend/src/lib/layouts/index.ts
index 244ada5d1..ff309a468 100644
--- a/frontend/src/lib/layouts/index.ts
+++ b/frontend/src/lib/layouts/index.ts
@@ -1,5 +1,4 @@
export { default as ResourcePageLayout, type ActionButton, type StatCardConfig } from './resource-page-layout.svelte';
-export { default as TabbedPageLayout } from './tabbed-page-layout.svelte';
export { default as SettingsPageLayout } from './settings-page-layout.svelte';
-export type { SettingsActionButton, SettingsStatCard, SettingsPageType, DetailAction } from './types.js';
+export type { SettingsActionButton, DetailAction } from './types.js';
export { default as ResourceDetailLayout } from './resource-detail-layout.svelte';
diff --git a/frontend/src/lib/services/activity-service.ts b/frontend/src/lib/services/activity-service.ts
index 1fd9bad51..b03f8eec2 100644
--- a/frontend/src/lib/services/activity-service.ts
+++ b/frontend/src/lib/services/activity-service.ts
@@ -4,7 +4,7 @@ import type { Activity, ActivityClearHistoryResult, ActivityDetail } from '$lib/
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import { transformPaginationParams } from '$lib/utils/tables';
-export class ActivityService extends BaseAPIService {
+class ActivityService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
}
diff --git a/frontend/src/lib/services/api-key-service.ts b/frontend/src/lib/services/api-key-service.ts
index 1ec737ab8..f24ed1db6 100644
--- a/frontend/src/lib/services/api-key-service.ts
+++ b/frontend/src/lib/services/api-key-service.ts
@@ -3,7 +3,7 @@ import type { ApiKey, ApiKeyCreated, CreateApiKey, UpdateApiKey } from '$lib/typ
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import { transformPaginationParams } from '$lib/utils/tables';
-export default class ApiKeyAPIService extends BaseAPIService {
+class ApiKeyAPIService extends BaseAPIService {
async getApiKeys(options?: SearchPaginationSortRequest): Promise<Paginated<ApiKey>> {
const params = transformPaginationParams(options);
const res = await this.api.get('/api-keys', { params });
diff --git a/frontend/src/lib/services/auth-service.ts b/frontend/src/lib/services/auth-service.ts
index 98a257a41..18335e5bb 100644
--- a/frontend/src/lib/services/auth-service.ts
+++ b/frontend/src/lib/services/auth-service.ts
@@ -9,7 +9,7 @@ const REFRESH_TOKEN_KEY = 'arcane_refresh_token';
const TOKEN_EXPIRY_KEY = 'arcane_token_expiry';
const REFRESH_BUFFER_MS = 5 * 60 * 1000; // Refresh 5 minutes before expiry
-export class AuthService extends BaseAPIService {
+class AuthService extends BaseAPIService {
private refreshTimer: ReturnType<typeof setTimeout> | null = null;
private isRefreshing = false;
private refreshSubscribers: Array<(token: string | null, error?: Error) => void> = [];
diff --git a/frontend/src/lib/services/build-workspace-service.ts b/frontend/src/lib/services/build-workspace-service.ts
index 5e7d03ee5..32ed8c03c 100644
--- a/frontend/src/lib/services/build-workspace-service.ts
+++ b/frontend/src/lib/services/build-workspace-service.ts
@@ -1,8 +1,9 @@
import BaseAPIService from './api-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { FileEntry, FileContentResponse } from '$lib/types/shared';
+import { downloadBlob, filenameFromPath } from '$lib/utils/browser-download';
-export class BuildWorkspaceService extends BaseAPIService {
+class BuildWorkspaceService extends BaseAPIService {
async listDirectory(path: string = '/'): Promise<FileEntry[]> {
const envId = await environmentStore.getCurrentEnvironmentId();
const res = await this.api.get(`/environments/${envId}/builds/browse`, {
@@ -26,14 +27,7 @@ export class BuildWorkspaceService extends BaseAPIService {
responseType: 'blob'
});
- const url = window.URL.createObjectURL(new Blob([res.data]));
- const link = document.createElement('a');
- link.href = url;
- const fileName = path.split('/').pop() || 'download';
- link.setAttribute('download', fileName);
- document.body.appendChild(link);
- link.click();
- link.remove();
+ downloadBlob(res.data, filenameFromPath(path));
}
async uploadFile(path: string, file: File): Promise<void> {
diff --git a/frontend/src/lib/services/container-registry-service.ts b/frontend/src/lib/services/container-registry-service.ts
index 5542f3e88..31cf776f1 100644
--- a/frontend/src/lib/services/container-registry-service.ts
+++ b/frontend/src/lib/services/container-registry-service.ts
@@ -8,7 +8,7 @@ import type { ContainerRegistry } from '$lib/types/docker';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import { transformPaginationParams } from '$lib/utils/tables';
-export default class ContainerRegistryService extends BaseAPIService {
+class ContainerRegistryService extends BaseAPIService {
async getRegistries(options?: SearchPaginationSortRequest): Promise<Paginated<ContainerRegistry>> {
const params = transformPaginationParams(options);
const res = await this.api.get('/container-registries', { params });
diff --git a/frontend/src/lib/services/container-service.ts b/frontend/src/lib/services/container-service.ts
index e4f622778..09c774493 100644
--- a/frontend/src/lib/services/container-service.ts
+++ b/frontend/src/lib/services/container-service.ts
@@ -22,7 +22,7 @@ export interface ContainerDetailsResponse {
data: ContainerDetailsDto;
}
-export class ContainerService extends BaseAPIService {
+class ContainerService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
}
diff --git a/frontend/src/lib/services/customize-search.ts b/frontend/src/lib/services/customize-search.ts
index 98bae77e6..317d252d8 100644
--- a/frontend/src/lib/services/customize-search.ts
+++ b/frontend/src/lib/services/customize-search.ts
@@ -1,7 +1,7 @@
import { apiClient } from './api-service';
import type { CustomizeSearchResponse, CustomizeCategory } from '$lib/types/shared';
-export class CustomizeSearchService {
+class CustomizeSearchService {
private baseUrl = '/customize';
async search(query: string): Promise<CustomizeSearchResponse> {
diff --git a/frontend/src/lib/services/dashboard-service.ts b/frontend/src/lib/services/dashboard-service.ts
index 9dad8f0cd..fe38c5c69 100644
--- a/frontend/src/lib/services/dashboard-service.ts
+++ b/frontend/src/lib/services/dashboard-service.ts
@@ -5,7 +5,7 @@ interface GetDashboardOptions {
debugAllGood?: boolean;
}
-export class DashboardService extends BaseAPIService {
+class DashboardService extends BaseAPIService {
async getDashboardForEnvironment(environmentId: string, options?: GetDashboardOptions): Promise<DashboardSnapshot> {
const params = options?.debugAllGood ? { debugAllGood: 'true' } : undefined;
return this.handleResponse(this.api.get(`/environments/${environmentId}/dashboard`, { params }));
diff --git a/frontend/src/lib/services/diagnostics-service.ts b/frontend/src/lib/services/diagnostics-service.ts
index 81f05306c..3d0efabdf 100644
--- a/frontend/src/lib/services/diagnostics-service.ts
+++ b/frontend/src/lib/services/diagnostics-service.ts
@@ -1,7 +1,7 @@
import BaseAPIService from './api-service';
import type { Diagnostics, LogEntry, PprofProfile } from '$lib/types/diagnostics';
-export default class DiagnosticsAPIService extends BaseAPIService {
+class DiagnosticsAPIService extends BaseAPIService {
/** One-shot runtime/memory/GC + WebSocket snapshot (used for initial paint). */
async getDiagnostics(): Promise<Diagnostics> {
const res = await this.api.get('/diagnostics');
diff --git a/frontend/src/lib/services/env-mgmt-service.ts b/frontend/src/lib/services/env-mgmt-service.ts
index 97e197e2a..4d6a7aba0 100644
--- a/frontend/src/lib/services/env-mgmt-service.ts
+++ b/frontend/src/lib/services/env-mgmt-service.ts
@@ -4,7 +4,7 @@ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import type { AppVersionInformation } from '$lib/types/settings';
import { transformPaginationParams } from '$lib/utils/tables';
-export default class EnvironmentManagementService extends BaseAPIService {
+class EnvironmentManagementService extends BaseAPIService {
async create(dto: CreateEnvironmentDTO): Promise<Environment> {
const res = await this.api.post('/environments', dto);
return res.data.data as Environment;
diff --git a/frontend/src/lib/services/event-service.ts b/frontend/src/lib/services/event-service.ts
index 9f8c01b14..7df9b01fe 100644
--- a/frontend/src/lib/services/event-service.ts
+++ b/frontend/src/lib/services/event-service.ts
@@ -3,7 +3,7 @@ import type { SearchPaginationSortRequest, Paginated } from '$lib/types/shared';
import type { Event } from '$lib/types/shared';
import { transformPaginationParams } from '$lib/utils/tables';
-export default class EventService extends BaseAPIService {
+class EventService extends BaseAPIService {
async getEvents(options?: SearchPaginationSortRequest): Promise<Paginated<Event>> {
const params = transformPaginationParams(options);
const res = await this.api.get('/events', { params });
diff --git a/frontend/src/lib/services/federated-credential-service.ts b/frontend/src/lib/services/federated-credential-service.ts
index 0fb0e3030..7baa1dc2b 100644
--- a/frontend/src/lib/services/federated-credential-service.ts
+++ b/frontend/src/lib/services/federated-credential-service.ts
@@ -3,7 +3,7 @@ import type { CreateFederatedCredential, FederatedCredential, UpdateFederatedCre
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import { transformPaginationParams } from '$lib/utils/tables';
-export default class FederatedCredentialAPIService extends BaseAPIService {
+class FederatedCredentialAPIService extends BaseAPIService {
async list(options?: SearchPaginationSortRequest): Promise<Paginated<FederatedCredential>> {
const params = transformPaginationParams(options);
const res = await this.api.get('/federated-credentials', { params });
diff --git a/frontend/src/lib/services/git-repository-service.ts b/frontend/src/lib/services/git-repository-service.ts
index a655965d4..d779cbd2b 100644
--- a/frontend/src/lib/services/git-repository-service.ts
+++ b/frontend/src/lib/services/git-repository-service.ts
@@ -10,7 +10,7 @@ import type {
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import { transformPaginationParams } from '$lib/utils/tables';
-export default class GitRepositoryService extends BaseAPIService {
+class GitRepositoryService extends BaseAPIService {
async getRepositories(options?: SearchPaginationSortRequest): Promise<Paginated<GitRepository>> {
const params = transformPaginationParams(options);
const res = await this.api.get('/customize/git-repositories', { params });
diff --git a/frontend/src/lib/services/gitops-sync-service.ts b/frontend/src/lib/services/gitops-sync-service.ts
index a80068482..f37f894a2 100644
--- a/frontend/src/lib/services/gitops-sync-service.ts
+++ b/frontend/src/lib/services/gitops-sync-service.ts
@@ -13,7 +13,7 @@ import type {
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import { transformPaginationParams } from '$lib/utils/tables';
-export default class GitOpsSyncService extends BaseAPIService {
+class GitOpsSyncService extends BaseAPIService {
async getSyncs(environmentId: string, options?: SearchPaginationSortRequest): Promise<Paginated<GitOpsSync, GitOpsSyncCounts>> {
const params = transformPaginationParams(options);
const res = await this.api.get(`/environments/${environmentId}/gitops-syncs`, { params });
diff --git a/frontend/src/lib/services/image-service.ts b/frontend/src/lib/services/image-service.ts
index f62be729d..7c6facc89 100644
--- a/frontend/src/lib/services/image-service.ts
+++ b/frontend/src/lib/services/image-service.ts
@@ -6,7 +6,7 @@ import type { AutoUpdateCheck, AutoUpdateResult } from '$lib/types/automation';
import type { PruneImagesOptions } from '$lib/types/automation';
import { transformPaginationParams } from '$lib/utils/tables';
-export class ImageService extends BaseAPIService {
+class ImageService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
}
diff --git a/frontend/src/lib/services/job-schedule-service.ts b/frontend/src/lib/services/job-schedule-service.ts
index 3e17d3fd3..4ed6e318f 100644
--- a/frontend/src/lib/services/job-schedule-service.ts
+++ b/frontend/src/lib/services/job-schedule-service.ts
@@ -20,4 +20,3 @@ class JobScheduleService extends BaseAPIService {
}
export const jobScheduleService = new JobScheduleService();
-export default JobScheduleService;
diff --git a/frontend/src/lib/services/network-service.ts b/frontend/src/lib/services/network-service.ts
index ff14fd691..9cdfec142 100644
--- a/frontend/src/lib/services/network-service.ts
+++ b/frontend/src/lib/services/network-service.ts
@@ -13,7 +13,7 @@ import { transformPaginationParams } from '$lib/utils/tables';
export type NetworksPaginatedResponse = Paginated<NetworkSummaryDto, NetworkUsageCounts>;
-export class NetworkService extends BaseAPIService {
+class NetworkService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
}
diff --git a/frontend/src/lib/services/notification-service.ts b/frontend/src/lib/services/notification-service.ts
index 15b767200..5a7f86d4d 100644
--- a/frontend/src/lib/services/notification-service.ts
+++ b/frontend/src/lib/services/notification-service.ts
@@ -2,7 +2,7 @@ import BaseAPIService from './api-service';
import type { NotificationSettings, TestNotificationResponse } from '$lib/types/notifications';
import { environmentStore } from '$lib/stores/environment.store.svelte';
-export default class NotificationService extends BaseAPIService {
+class NotificationService extends BaseAPIService {
async getSettings(environmentId?: string): Promise<NotificationSettings[]> {
const envId = environmentId || (await environmentStore.getCurrentEnvironmentId());
const res = await this.api.get(`/environments/${envId}/notifications/settings`);
diff --git a/frontend/src/lib/services/oidc-mapping-service.ts b/frontend/src/lib/services/oidc-mapping-service.ts
index 74a86b73e..c86948074 100644
--- a/frontend/src/lib/services/oidc-mapping-service.ts
+++ b/frontend/src/lib/services/oidc-mapping-service.ts
@@ -1,7 +1,7 @@
import BaseAPIService from './api-service';
import type { OidcRoleMapping, CreateOidcRoleMapping, UpdateOidcRoleMapping } from '$lib/types/auth';
-export default class OidcMappingAPIService extends BaseAPIService {
+class OidcMappingAPIService extends BaseAPIService {
async list(): Promise<OidcRoleMapping[]> {
return this.handleResponse(this.api.get('/oidc/role-mappings')) as Promise<OidcRoleMapping[]>;
}
diff --git a/frontend/src/lib/services/port-service.ts b/frontend/src/lib/services/port-service.ts
index 3c3df8445..a98fa046b 100644
--- a/frontend/src/lib/services/port-service.ts
+++ b/frontend/src/lib/services/port-service.ts
@@ -6,7 +6,7 @@ import { transformPaginationParams } from '$lib/utils/tables';
export type PortsPaginatedResponse = Paginated<PortMappingDto>;
-export class PortService extends BaseAPIService {
+class PortService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
}
diff --git a/frontend/src/lib/services/project-service.ts b/frontend/src/lib/services/project-service.ts
index 67a213529..f7a77c94c 100644
--- a/frontend/src/lib/services/project-service.ts
+++ b/frontend/src/lib/services/project-service.ts
@@ -2,6 +2,7 @@ import { m } from '$lib/paraglide/messages';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import type { IncludeFile, Project, ProjectStatusCounts } from '$lib/types/swarm';
+import { readNdjsonStream } from '$lib/utils/streaming';
import { transformPaginationParams } from '$lib/utils/tables';
import BaseAPIService from './api-service';
@@ -10,7 +11,7 @@ export type DeployProjectOptions = {
forceRecreate?: boolean;
};
-export class ProjectService extends BaseAPIService {
+class ProjectService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
}
@@ -50,34 +51,11 @@ export class ProjectService extends BaseAPIService {
throw new Error(m.progress_deploy_failed_to_start({ status }));
}
- const reader = res.body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
-
- while (true) {
- const { value, done } = await reader.read();
- if (done) break;
-
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split('\n');
- buffer = lines.pop() || '';
-
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- let obj: any;
- try {
- obj = JSON.parse(trimmed);
- } catch {
- continue;
- }
-
- onLine?.(obj);
- if (obj?.error) {
- throw new Error(typeof obj.error === 'string' ? obj.error : obj.error?.message || m.progress_deploy_failed());
- }
+ await this.readProjectStream(res.body, onLine, (obj) => {
+ if (obj?.error) {
+ throw new Error(typeof obj.error === 'string' ? obj.error : obj.error?.message || m.progress_deploy_failed());
}
- }
+ });
// The deploy stream doesn't return the project object; fetch fresh details.
return this.getProject(projectId);
@@ -127,6 +105,14 @@ export class ProjectService extends BaseAPIService {
return 'project' in response && response.project ? response.project : (response as Project);
}
+ private async readProjectStream(
+ body: ReadableStream<Uint8Array>,
+ onLine?: (data: any) => void,
+ onMessage?: (data: any) => void
+ ): Promise<void> {
+ await readNdjsonStream(body, onMessage, onLine);
+ }
+
async getProjectFile(projectId: string, relativePath: string): Promise<IncludeFile> {
const envId = await this.resolveEnvironmentId();
return this.getProjectFileForEnvironment(envId, projectId, relativePath);
@@ -203,29 +189,7 @@ export class ProjectService extends BaseAPIService {
throw new Error(`Failed to start project image pull (${res.status})`);
}
- const reader = res.body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
-
- while (true) {
- const { value, done } = await reader.read();
- if (done) break;
-
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split('\n');
- buffer = lines.pop() || '';
-
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- try {
- const obj = JSON.parse(trimmed);
- onLine?.(obj);
- } catch {
- // ignore malformed line
- }
- }
- }
+ await this.readProjectStream(res.body, onLine);
}
buildProjectImages(
@@ -256,32 +220,11 @@ export class ProjectService extends BaseAPIService {
throw new Error(`Failed to start project build (${res.status})`);
}
- const reader = res.body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
-
- while (true) {
- const { value, done } = await reader.read();
- if (done) break;
-
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split('\n');
- buffer = lines.pop() || '';
-
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- try {
- const obj = JSON.parse(trimmed);
- onLine?.(obj);
- if (obj?.error) {
- throw new Error(typeof obj.error === 'string' ? obj.error : obj.error?.message || m.build_failed());
- }
- } catch (err) {
- if (err instanceof Error) throw err;
- }
+ await this.readProjectStream(res.body, onLine, (obj) => {
+ if (obj?.error) {
+ throw new Error(typeof obj.error === 'string' ? obj.error : obj.error?.message || m.build_failed());
}
- }
+ });
}
pullProjectImages(projectId: string): Promise<void>;
diff --git a/frontend/src/lib/services/role-service.ts b/frontend/src/lib/services/role-service.ts
index 8951cd9e9..6db8516dd 100644
--- a/frontend/src/lib/services/role-service.ts
+++ b/frontend/src/lib/services/role-service.ts
@@ -3,7 +3,7 @@ import type { Role, CreateRole, UpdateRole, RoleAssignment, SetUserAssignments,
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import { transformPaginationParams } from '$lib/utils/tables';
-export default class RoleAPIService extends BaseAPIService {
+class RoleAPIService extends BaseAPIService {
async getRoles(options?: SearchPaginationSortRequest): Promise<Paginated<Role>> {
const params = transformPaginationParams(options);
const res = await this.api.get('/roles', { params });
diff --git a/frontend/src/lib/services/settings-search.ts b/frontend/src/lib/services/settings-search.ts
index 323d9bf77..fbbd743ef 100644
--- a/frontend/src/lib/services/settings-search.ts
+++ b/frontend/src/lib/services/settings-search.ts
@@ -1,7 +1,7 @@
import { apiClient } from './api-service';
import type { SettingsSearchResponse, SettingsCategory } from '$lib/types/shared';
-export class SettingsSearchService {
+class SettingsSearchService {
private baseUrl = '/settings';
async search(query: string): Promise<SettingsSearchResponse> {
diff --git a/frontend/src/lib/services/settings-service.ts b/frontend/src/lib/services/settings-service.ts
index d7e9efc6e..e4d191776 100644
--- a/frontend/src/lib/services/settings-service.ts
+++ b/frontend/src/lib/services/settings-service.ts
@@ -5,7 +5,7 @@ import { isLocalSetting, extractLocalSettings, extractEnvironmentSettings } from
type KeyValuePair = { key: string; value: string };
-export default class SettingsService extends BaseAPIService {
+class SettingsService extends BaseAPIService {
async getSettings(): Promise<Settings> {
// Wait for environment store to be initialized before fetching settings
await environmentStore.ready;
diff --git a/frontend/src/lib/services/swarm-service.ts b/frontend/src/lib/services/swarm-service.ts
index 541a72c02..241f3c837 100644
--- a/frontend/src/lib/services/swarm-service.ts
+++ b/frontend/src/lib/services/swarm-service.ts
@@ -46,7 +46,7 @@ export type SwarmNodesPaginatedResponse = Paginated<SwarmNodeSummary>;
export type SwarmTasksPaginatedResponse = Paginated<SwarmTaskSummary>;
export type SwarmStacksPaginatedResponse = Paginated<SwarmStackSummary>;
-export class SwarmService extends BaseAPIService {
+class SwarmService extends BaseAPIService {
async getServices(options?: SearchPaginationSortRequest): Promise<SwarmServicesPaginatedResponse> {
const envId = await environmentStore.getCurrentEnvironmentId();
const params = transformPaginationParams(options);
diff --git a/frontend/src/lib/services/system-service.ts b/frontend/src/lib/services/system-service.ts
index a6c191b80..e1c4d6a0d 100644
--- a/frontend/src/lib/services/system-service.ts
+++ b/frontend/src/lib/services/system-service.ts
@@ -3,7 +3,13 @@ import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { DockerInfo } from '$lib/types/docker';
import type { SystemPruneRequest } from '$lib/types/automation';
-export class SystemService extends BaseAPIService {
+type ConvertedDockerRun = {
+ dockerCompose: string;
+ envVars: string;
+ serviceName: string;
+};
+
+class SystemService extends BaseAPIService {
async pruneAll(options: SystemPruneRequest) {
const envId = await environmentStore.getCurrentEnvironmentId();
return this.pruneAllForEnvironment(envId, options);
@@ -32,12 +38,13 @@ export class SystemService extends BaseAPIService {
return this.handleResponse(this.api.get(`/environments/${environmentId}/system/docker/info`));
}
- async convert(dockerRunCommand: string) {
+ async convert(dockerRunCommand: string): Promise<ConvertedDockerRun> {
const envId = await environmentStore.getCurrentEnvironmentId();
- const res = await this.api.post(`/environments/${envId}/system/convert`, {
- dockerRunCommand
- });
- return res.data;
+ return this.handleResponse(
+ this.api.post(`/environments/${envId}/system/convert`, {
+ dockerRunCommand
+ })
+ );
}
}
diff --git a/frontend/src/lib/services/template-service.ts b/frontend/src/lib/services/template-service.ts
index 857ae80de..21f117f15 100644
--- a/frontend/src/lib/services/template-service.ts
+++ b/frontend/src/lib/services/template-service.ts
@@ -5,7 +5,7 @@ import type { SearchPaginationSortRequest, Paginated } from '$lib/types/shared';
import { transformPaginationParams } from '$lib/utils/tables';
import { environmentStore } from '$lib/stores/environment.store.svelte';
-export default class TemplateService extends BaseAPIService {
+class TemplateService extends BaseAPIService {
async getTemplates(options?: SearchPaginationSortRequest): Promise<Paginated<Template>> {
const params = transformPaginationParams(options);
const response = await this.api.get('/templates', { params });
diff --git a/frontend/src/lib/services/user-service.ts b/frontend/src/lib/services/user-service.ts
index 9dfea87fb..648db0ca3 100644
--- a/frontend/src/lib/services/user-service.ts
+++ b/frontend/src/lib/services/user-service.ts
@@ -3,7 +3,7 @@ import type { User, CreateUser } from '$lib/types/auth';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import { transformPaginationParams } from '$lib/utils/tables';
-export default class UserAPIService extends BaseAPIService {
+class UserAPIService extends BaseAPIService {
async getUsers(options?: SearchPaginationSortRequest): Promise<Paginated<User>> {
const params = transformPaginationParams(options);
const res = await this.api.get('/users', { params });
diff --git a/frontend/src/lib/services/version-service.ts b/frontend/src/lib/services/version-service.ts
index 02b9afdbf..ad19405c9 100644
--- a/frontend/src/lib/services/version-service.ts
+++ b/frontend/src/lib/services/version-service.ts
@@ -11,24 +11,7 @@ async function getVersionInformation(): Promise<AppVersionInformation> {
const res = await apiClient.get('/app-version', {
timeout: 2000
});
- const data = res.data as {
- currentVersion?: string;
- currentTag?: string;
- currentDigest?: string;
- displayVersion?: string;
- revision?: string;
- shortRevision?: string;
- goVersion?: string;
- enabledFeatures?: string[];
- buildTime?: string;
- isSemverVersion?: boolean;
- newestVersion?: string;
- newestDigest?: string;
- updateAvailable?: boolean;
- releaseUrl?: string;
- releaseNotes?: string;
- releasedAt?: string;
- };
+ const data = res.data as Partial<AppVersionInformation>;
return {
currentVersion: data.currentVersion || getCurrentVersion(),
diff --git a/frontend/src/lib/services/volume-backup-service.ts b/frontend/src/lib/services/volume-backup-service.ts
index b29ca5803..f3ad251a7 100644
--- a/frontend/src/lib/services/volume-backup-service.ts
+++ b/frontend/src/lib/services/volume-backup-service.ts
@@ -6,7 +6,7 @@ import { transformPaginationParams } from '$lib/utils/tables';
export type VolumeBackupListResponse = Paginated<BackupEntry> & { warnings?: string[] };
-export class VolumeBackupService extends BaseAPIService {
+class VolumeBackupService extends BaseAPIService {
async createBackup(volumeName: string): Promise<BackupEntry> {
const envId = await environmentStore.getCurrentEnvironmentId();
const res = await this.api.post(`/environments/${envId}/volumes/${volumeName}/backups`);
diff --git a/frontend/src/lib/services/volume-browser-service.ts b/frontend/src/lib/services/volume-browser-service.ts
index fdc94a1eb..828f7ee0d 100644
--- a/frontend/src/lib/services/volume-browser-service.ts
+++ b/frontend/src/lib/services/volume-browser-service.ts
@@ -1,8 +1,9 @@
import BaseAPIService from './api-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { FileEntry, FileContentResponse } from '$lib/types/shared';
+import { downloadBlob, filenameFromPath } from '$lib/utils/browser-download';
-export class VolumeBrowserService extends BaseAPIService {
+class VolumeBrowserService extends BaseAPIService {
async listDirectory(volumeName: string, path: string = '/'): Promise<FileEntry[]> {
const envId = await environmentStore.getCurrentEnvironmentId();
const res = await this.api.get(`/environments/${envId}/volumes/${volumeName}/browse`, {
@@ -26,15 +27,7 @@ export class VolumeBrowserService extends BaseAPIService {
responseType: 'blob'
});
- const url = window.URL.createObjectURL(new Blob([res.data]));
- const link = document.createElement('a');
- link.href = url;
- // Extract filename from path
- const fileName = path.split('/').pop() || 'download';
- link.setAttribute('download', fileName);
- document.body.appendChild(link);
- link.click();
- link.remove();
+ downloadBlob(res.data, filenameFromPath(path));
}
async uploadFile(volumeName: string, path: string, file: File): Promise<any> {
diff --git a/frontend/src/lib/services/volume-service.ts b/frontend/src/lib/services/volume-service.ts
index 9ef5f5f92..fff5d622f 100644
--- a/frontend/src/lib/services/volume-service.ts
+++ b/frontend/src/lib/services/volume-service.ts
@@ -13,7 +13,7 @@ import { transformPaginationParams } from '$lib/utils/tables';
export type VolumesPaginatedResponse = Paginated<VolumeSummaryDto, VolumeUsageCounts>;
-export class VolumeService extends BaseAPIService {
+class VolumeService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
}
diff --git a/frontend/src/lib/services/vulnerability-service.ts b/frontend/src/lib/services/vulnerability-service.ts
index c24c0aad0..6f72e7d17 100644
--- a/frontend/src/lib/services/vulnerability-service.ts
+++ b/frontend/src/lib/services/vulnerability-service.ts
@@ -15,7 +15,7 @@ import type {
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import { transformPaginationParams } from '$lib/utils/tables';
-export class VulnerabilityService extends BaseAPIService {
+class VulnerabilityService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
}
diff --git a/frontend/src/lib/services/webhook-service.ts b/frontend/src/lib/services/webhook-service.ts
index eed8a640d..f4dc35d12 100644
--- a/frontend/src/lib/services/webhook-service.ts
+++ b/frontend/src/lib/services/webhook-service.ts
@@ -2,7 +2,7 @@ import BaseAPIService from './api-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { Webhook, WebhookCreated, CreateWebhook, UpdateWebhook } from '$lib/types/environment';
-export default class WebhookAPIService extends BaseAPIService {
+class WebhookAPIService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
}
diff --git a/frontend/src/lib/utils/api.ts b/frontend/src/lib/utils/api.ts
index b17e32072..990e0279a 100644
--- a/frontend/src/lib/utils/api.ts
+++ b/frontend/src/lib/utils/api.ts
@@ -106,7 +106,7 @@ export async function handleApiResultWithCallbacks<T>({
// --- Page load error helpers ---
-export function extractApiErrorStatus(err: unknown, fallbackStatus = 500): number {
+function extractApiErrorStatus(err: unknown, fallbackStatus = 500): number {
if (err && typeof err === 'object') {
const maybeResponse = (err as { response?: { status?: unknown } }).response;
const responseStatus = maybeResponse?.status;
diff --git a/frontend/src/lib/utils/auth.ts b/frontend/src/lib/utils/auth.ts
index ee91006d0..ea7b93f9a 100644
--- a/frontend/src/lib/utils/auth.ts
+++ b/frontend/src/lib/utils/auth.ts
@@ -1,4 +1,3 @@
-import { get } from 'svelte/store';
import userStore from '$lib/stores/user-store';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import {
@@ -27,25 +26,10 @@ export function hasAnyPermission(perms: string[], envId?: string): boolean {
return userStore.hasAnyPermission(perms, resolveEnvId(envId));
}
-export function permissions(envId?: string): Set<string> {
- return userStore.permissions(resolveEnvId(envId));
-}
-
export function isGlobalAdmin(): boolean {
return userStore.isGlobalAdmin();
}
-export function hasAnyAccess(user: User | null): boolean {
- if (!user?.permissionsByEnv) return false;
- for (const perms of Object.values(user.permissionsByEnv)) {
- if (perms.length > 0) return true;
- }
- return false;
-}
-
-export { GLOBAL_SCOPE };
-export { get };
-
// --- Load-function helpers (run before stores hydrate) ---
const PROTECTED_PREFIXES = [
diff --git a/frontend/src/lib/utils/browser-download.ts b/frontend/src/lib/utils/browser-download.ts
new file mode 100644
index 000000000..d8b1b4818
--- /dev/null
+++ b/frontend/src/lib/utils/browser-download.ts
@@ -0,0 +1,14 @@
+export function downloadBlob(data: BlobPart, filename: string): void {
+ const url = window.URL.createObjectURL(new Blob([data]));
+ const link = document.createElement('a');
+ link.href = url;
+ link.setAttribute('download', filename);
+ document.body.appendChild(link);
+ link.click();
+ link.remove();
+ window.URL.revokeObjectURL(url);
+}
+
+export function filenameFromPath(path: string, fallback = 'download'): string {
+ return path.split('/').pop() || fallback;
+}
diff --git a/frontend/src/lib/utils/build-provider.ts b/frontend/src/lib/utils/build-provider.ts
new file mode 100644
index 000000000..b8867c155
--- /dev/null
+++ b/frontend/src/lib/utils/build-provider.ts
@@ -0,0 +1,11 @@
+type DepotSettings = {
+ depotConfigured?: boolean;
+ depotProjectId?: unknown;
+ depotToken?: unknown;
+};
+
+export function isDepotBuildAvailable(settings: DepotSettings | null | undefined): boolean {
+ const projectId = String(settings?.depotProjectId ?? '').trim();
+ const token = String(settings?.depotToken ?? '').trim();
+ return Boolean(settings?.depotConfigured) || (Boolean(projectId) && Boolean(token));
+}
diff --git a/frontend/src/lib/utils/bulk-actions.ts b/frontend/src/lib/utils/bulk-actions.ts
index 679bd8bb0..f348c5c00 100644
--- a/frontend/src/lib/utils/bulk-actions.ts
+++ b/frontend/src/lib/utils/bulk-actions.ts
@@ -1,6 +1,6 @@
import { toast } from 'svelte-sonner';
import { openConfirmDialog } from '$lib/components/confirm-dialog';
-import { tryCatch, type Result } from '$lib/utils/api';
+import { handleApiResultWithCallbacks, tryCatch, type Result } from '$lib/utils/api';
import { activityToastOptions, extractActivityId } from '$lib/utils/activity-toast';
/**
@@ -36,6 +36,8 @@ export interface RunBulkOperationOptions<T> {
onComplete?: (result: BulkOperationResult) => void | Promise<unknown>;
/** Clears the table selection after completion. Always called when there were ids. */
clearSelection?: () => void;
+ /** Optional per-item failure side effect, such as an item-specific toast. */
+ onItemFailure?: (id: string) => void;
/** Run operations one at a time instead of concurrently. Defaults to concurrent. */
sequential?: boolean;
}
@@ -45,13 +47,14 @@ export interface RunBulkOperationOptions<T> {
* toast (success / partial / failure), then refreshes and clears the selection.
* The success toast links to the first resulting activity when one is present.
*/
-export async function runBulkOperation<T>({
+async function runBulkOperation<T>({
ids,
run,
messages,
setLoading,
onComplete,
clearSelection,
+ onItemFailure,
sequential = false
}: RunBulkOperationOptions<T>): Promise<BulkOperationResult> {
const total = ids?.length ?? 0;
@@ -59,9 +62,10 @@ export async function runBulkOperation<T>({
if (total === 0) return result;
let firstActivityId: string | undefined;
- const tally = (outcome: Result<T>) => {
+ const tally = (id: string, outcome: Result<T>) => {
if (outcome.error) {
result.failed += 1;
+ onItemFailure?.(id);
} else {
result.success += 1;
if (!firstActivityId) firstActivityId = extractActivityId(outcome.data);
@@ -72,11 +76,11 @@ export async function runBulkOperation<T>({
try {
if (sequential) {
for (const id of ids) {
- tally(await tryCatch(run(id)));
+ tally(id, await tryCatch(run(id)));
}
} else {
- const outcomes = await Promise.all(ids.map((id) => tryCatch(run(id))));
- for (const outcome of outcomes) tally(outcome);
+ const outcomes = await Promise.all(ids.map(async (id) => [id, await tryCatch(run(id))] as const));
+ for (const [id, outcome] of outcomes) tally(id, outcome);
}
} finally {
setLoading?.(false);
@@ -129,6 +133,7 @@ export function bulkConfirmAndRun<T>({
setLoading,
onComplete,
clearSelection,
+ onItemFailure,
sequential
}: BulkConfirmAndRunOptions<T>): void {
if (!ids || ids.length === 0) return;
@@ -148,9 +153,56 @@ export function bulkConfirmAndRun<T>({
setLoading,
onComplete,
clearSelection,
+ onItemFailure,
sequential
});
}
}
});
}
+
+export interface ConfirmAndRunOptions<T> {
+ title: string;
+ message: string;
+ confirmLabel: string;
+ destructive?: boolean;
+ setLoading?: (loading: boolean) => void;
+ run: () => Promise<T>;
+ failureMessage: string;
+ onSuccess?: (result: T) => void | Promise<void>;
+}
+
+export function confirmAndRun<T>({
+ title,
+ message,
+ confirmLabel,
+ destructive = false,
+ setLoading,
+ run,
+ failureMessage,
+ onSuccess
+}: ConfirmAndRunOptions<T>): void {
+ openConfirmDialog({
+ title,
+ message,
+ confirm: {
+ label: confirmLabel,
+ destructive,
+ action: async () => {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(run()),
+ message: failureMessage,
+ setLoadingState: setLoading ?? (() => {}),
+ onSuccess
+ });
+ }
+ }
+ });
+}
+
+export function hasAnyLoadingState<TStatus extends string>(
+ actionStatus: Record<string, TStatus>,
+ loadingState: Record<string, boolean>
+): boolean {
+ return Object.values(actionStatus).some((status) => status !== '') || Object.values(loadingState).some(Boolean);
+}
diff --git a/frontend/src/lib/utils/category-page.ts b/frontend/src/lib/utils/category-page.ts
new file mode 100644
index 000000000..72b88f505
--- /dev/null
+++ b/frontend/src/lib/utils/category-page.ts
@@ -0,0 +1,18 @@
+type CategoryLike = {
+ title: string;
+ url: string;
+};
+
+export function orderCategoriesByNav<T extends CategoryLike>(categories: T[], navUrls: string[]): T[] {
+ const categoriesByUrl = new Map(categories.map((category) => [category.url, category]));
+ const orderedCategories = navUrls.map((url) => categoriesByUrl.get(url)).filter((category): category is T => Boolean(category));
+ const unmatchedCategories = categories
+ .filter((category) => !navUrls.includes(category.url))
+ .sort((a, b) => a.title.localeCompare(b.title));
+
+ return [...orderedCategories, ...unmatchedCategories];
+}
+
+export function getCategoryIcon<T>(iconMap: Record<string, T>, iconName: string | null | undefined, fallback: T): T {
+ return iconMap[iconName ?? ''] ?? fallback;
+}
diff --git a/frontend/src/lib/utils/compose-flow.ts b/frontend/src/lib/utils/compose-flow.ts
new file mode 100644
index 000000000..4fce0c1cc
--- /dev/null
+++ b/frontend/src/lib/utils/compose-flow.ts
@@ -0,0 +1,208 @@
+import { arcaneButtonVariants, actionConfigs } from '$lib/components/arcane-button/variants';
+import { m } from '$lib/paraglide/messages';
+import { templateService } from '$lib/services/template-service.js';
+import type { Template } from '$lib/types/swarm';
+import { handleApiResultWithCallbacks, tryCatch } from '$lib/utils/api';
+import { toast } from 'svelte-sonner';
+import { z } from 'zod/v4';
+
+export type ConvertedDockerRun = {
+ dockerCompose: string;
+ envVars: string;
+ serviceName: string;
+};
+
+type ComposeFieldAccessors = {
+ getName: () => string | undefined;
+ setName: (value: string) => void;
+ setComposeContent: (value: string) => void;
+ setEnvContent: (value: string) => void;
+};
+
+type ComposeFormInputs = {
+ name: { value: string };
+ composeContent: { value: string };
+ envContent: { value: string };
+};
+
+type ComposeFieldKey = keyof ComposeFormInputs;
+type ComposeFieldSetter = (key: ComposeFieldKey, value: string) => void;
+
+export const templateBtnClass = arcaneButtonVariants({
+ tone: actionConfigs.template?.tone ?? 'outline-primary',
+ size: 'default',
+ hoverEffect: 'none'
+});
+
+export const dropdownContentClass =
+ 'arcane-dd-content min-w-[220px] overflow-visible rounded-lg border border-primary/30 bg-background/95 ' +
+ 'backdrop-blur supports-[backdrop-filter]:bg-background/80 ring-1 ring-inset ring-primary/20 shadow-sm p-1';
+
+export const dropdownItemClass =
+ 'flex cursor-pointer select-none items-center gap-2 rounded-md px-3 py-2 text-sm ' +
+ 'text-foreground/90 outline-none transition-colors ' +
+ 'hover:bg-primary/10 focus:bg-primary/10 ' +
+ 'data-[disabled]:opacity-50 data-[disabled]:pointer-events-none';
+
+export function templateNameSlug(name: string): string {
+ return name.toLowerCase().replace(/[^a-z0-9-_]/g, '-');
+}
+
+export function createComposeEditorSchema(nameRequiredMessage: string) {
+ return z.object({
+ name: z
+ .string()
+ .min(1, nameRequiredMessage)
+ .regex(/^[a-z0-9-_]+$/i, m.compose_project_name_invalid()),
+ composeContent: z.string().min(1, m.compose_compose_content_required()),
+ envContent: z.string().optional().default('')
+ });
+}
+
+function createComposeFieldAccessors(
+ getInputs: () => ComposeFormInputs,
+ setInputValue: ComposeFieldSetter
+): ComposeFieldAccessors {
+ return {
+ getName: () => getInputs().name.value,
+ setName: (value: string) => setInputValue('name', value),
+ setComposeContent: (value: string) => setInputValue('composeContent', value),
+ setEnvContent: (value: string) => setInputValue('envContent', value)
+ };
+}
+
+function applyTemplateToComposeFields(template: Template, fields: ComposeFieldAccessors) {
+ fields.setComposeContent(template.content ?? '');
+ fields.setEnvContent(template.envContent ?? '');
+
+ if (!fields.getName()?.trim()) {
+ fields.setName(templateNameSlug(template.name));
+ }
+ toast.success(m.compose_template_loaded({ name: template.name }));
+}
+
+function applyConvertedDockerRunToComposeFields(data: ConvertedDockerRun, fields: ComposeFieldAccessors) {
+ fields.setComposeContent(data.dockerCompose);
+ fields.setEnvContent(data.envVars);
+ if (!fields.getName()?.trim()) {
+ fields.setName(templateNameSlug(data.serviceName));
+ }
+}
+
+function createComposeFieldHandlers(fields: ComposeFieldAccessors, closeTemplateDialog: () => void) {
+ return {
+ handleTemplateSelect(template: Template) {
+ closeTemplateDialog();
+ applyTemplateToComposeFields(template, fields);
+ },
+ handleDockerRunConverted(data: ConvertedDockerRun) {
+ applyConvertedDockerRunToComposeFields(data, fields);
+ }
+ };
+}
+
+type ValidatedComposeTemplate = {
+ name: string;
+ composeContent: string;
+ envContent?: string;
+};
+
+type SubmitComposeResourceOptions<TResult> = {
+ validate: () => ValidatedComposeTemplate | undefined | false | null;
+ setLoading: (value: boolean) => void;
+ submit: (payload: ValidatedComposeTemplate) => Promise<TResult>;
+ failureMessage: (name: string) => string;
+ onSuccess: (result: TResult, payload: ValidatedComposeTemplate) => void | Promise<void>;
+};
+
+type CreateComposeTemplateOptions = {
+ validate: () => ValidatedComposeTemplate | undefined | false | null;
+ setLoading: (value: boolean) => void;
+ beforeValidate?: () => boolean;
+};
+
+type CreateComposeTemplateWithValidationOptions = Omit<CreateComposeTemplateOptions, 'beforeValidate'> & {
+ hasEditorErrors?: () => boolean;
+};
+
+type CreateComposeTemplateDialogFlowOptions = CreateComposeTemplateWithValidationOptions & {
+ getInputs: () => ComposeFormInputs;
+ setInputValue: ComposeFieldSetter;
+ closeTemplateDialog: () => void;
+};
+
+async function createComposeTemplate({ validate, setLoading, beforeValidate }: CreateComposeTemplateOptions) {
+ if (beforeValidate && !beforeValidate()) return;
+
+ const validated = validate();
+ if (!validated) return;
+
+ const { name, composeContent, envContent } = validated;
+
+ handleApiResultWithCallbacks({
+ result: await tryCatch(
+ templateService.createTemplate({
+ name,
+ content: composeContent,
+ envContent
+ })
+ ),
+ message: m.common_create_failed({ resource: `${m.resource_template()} "${name}"` }),
+ setLoadingState: setLoading,
+ onSuccess: async () => {
+ toast.success(m.common_create_success({ resource: `${m.resource_template()} "${name}"` }));
+ }
+ });
+}
+
+export async function submitComposeResourceForm<TResult>({
+ validate,
+ setLoading,
+ submit,
+ failureMessage,
+ onSuccess
+}: SubmitComposeResourceOptions<TResult>) {
+ const validated = validate();
+ if (!validated) return;
+
+ handleApiResultWithCallbacks({
+ result: await tryCatch(submit(validated)),
+ message: failureMessage(validated.name),
+ setLoadingState: setLoading,
+ onSuccess: async (result) => {
+ await onSuccess(result, validated);
+ }
+ });
+}
+
+async function createComposeTemplateWithValidation({
+ validate,
+ setLoading,
+ hasEditorErrors
+}: CreateComposeTemplateWithValidationOptions) {
+ await createComposeTemplate({
+ validate,
+ setLoading,
+ beforeValidate: hasEditorErrors
+ ? () => {
+ if (!hasEditorErrors()) return true;
+ toast.error(m.templates_validation_error());
+ return false;
+ }
+ : undefined
+ });
+}
+
+export function createComposeTemplateDialogFlow({
+ getInputs,
+ setInputValue,
+ closeTemplateDialog,
+ validate,
+ setLoading,
+ hasEditorErrors
+}: CreateComposeTemplateDialogFlowOptions) {
+ return {
+ composeHandlers: createComposeFieldHandlers(createComposeFieldAccessors(getInputs, setInputValue), closeTemplateDialog),
+ handleCreateTemplate: () => createComposeTemplateWithValidation({ validate, setLoading, hasEditorErrors })
+ };
+}
diff --git a/frontend/src/lib/utils/container-actions.ts b/frontend/src/lib/utils/container-actions.ts
new file mode 100644
index 000000000..e77f2a027
--- /dev/null
+++ b/frontend/src/lib/utils/container-actions.ts
@@ -0,0 +1,186 @@
+import { openConfirmDialog } from '$lib/components/confirm-dialog';
+import { m } from '$lib/paraglide/messages';
+import { containerService } from '$lib/services/container-service';
+import { handleApiResultWithCallbacks, tryCatch } from '$lib/utils/api';
+import { activityToastOptions, extractActivityId } from '$lib/utils/activity-toast';
+import { toast } from 'svelte-sonner';
+
+type ContainerLifecycleAction = 'start' | 'stop' | 'restart';
+type ContainerLifecycleStatus = 'starting' | 'stopping' | 'restarting' | '';
+type ContainerRemoveStatus = 'removing' | '';
+
+type ContainerLifecycleActionConfig = {
+ status: Exclude<ContainerLifecycleStatus, ''>;
+ run: (id: string) => Promise<unknown>;
+ success: () => string;
+ failure: () => string;
+};
+
+const containerLifecycleActionConfigs: Record<ContainerLifecycleAction, ContainerLifecycleActionConfig> = {
+ start: {
+ status: 'starting',
+ run: (id) => containerService.startContainer(id),
+ success: () => m.containers_start_success(),
+ failure: () => m.containers_start_failed()
+ },
+ stop: {
+ status: 'stopping',
+ run: (id) => containerService.stopContainer(id),
+ success: () => m.containers_stop_success(),
+ failure: () => m.containers_stop_failed()
+ },
+ restart: {
+ status: 'restarting',
+ run: (id) => containerService.restartContainer(id),
+ success: () => m.containers_restart_success(),
+ failure: () => m.containers_restart_failed()
+ }
+};
+
+type RunContainerLifecycleActionOptions = {
+ action: ContainerLifecycleAction;
+ containerId: string;
+ setStatus: (status: ContainerLifecycleStatus) => void;
+ onRefresh?: () => Promise<unknown> | unknown;
+};
+
+export async function runContainerLifecycleAction({
+ action,
+ containerId,
+ setStatus,
+ onRefresh
+}: RunContainerLifecycleActionOptions) {
+ if (!containerId) return;
+
+ const config = containerLifecycleActionConfigs[action];
+ setStatus(config.status);
+
+ try {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(config.run(containerId)),
+ message: config.failure(),
+ setLoadingState: (value) => {
+ setStatus(value ? config.status : '');
+ },
+ async onSuccess(data) {
+ toast.success(config.success(), activityToastOptions(extractActivityId(data)));
+ await onRefresh?.();
+ }
+ });
+ } catch (error) {
+ console.error('Container action failed:', error);
+ toast.error(m.containers_action_error());
+ setStatus('');
+ }
+}
+
+type ConfirmAndRemoveContainerOptions = {
+ containerId: string;
+ containerName: string;
+ setStatus: (status: ContainerRemoveStatus) => void;
+ onRefresh?: () => Promise<unknown> | unknown;
+};
+
+export function confirmAndRemoveContainer({
+ containerId,
+ containerName,
+ setStatus,
+ onRefresh
+}: ConfirmAndRemoveContainerOptions) {
+ openConfirmDialog({
+ title: m.containers_remove_confirm_title(),
+ message: m.containers_remove_confirm_message({ resource: containerName }),
+ checkboxes: [
+ { id: 'force', label: m.containers_remove_force_label(), initialState: false },
+ { id: 'volumes', label: m.containers_remove_volumes_label(), initialState: false }
+ ],
+ confirm: {
+ label: m.common_remove(),
+ destructive: true,
+ action: async (checkboxStates) => {
+ const force = !!checkboxStates['force'];
+ const volumes = !!checkboxStates['volumes'];
+ setStatus('removing');
+ handleApiResultWithCallbacks({
+ result: await tryCatch(containerService.deleteContainer(containerId, { force, volumes })),
+ message: m.containers_remove_failed(),
+ setLoadingState: (value) => {
+ setStatus(value ? 'removing' : '');
+ },
+ async onSuccess(data) {
+ toast.success(m.containers_remove_success(), activityToastOptions(extractActivityId(data)));
+ await onRefresh?.();
+ }
+ });
+ }
+ }
+ });
+}
+
+type ContainerUpdateResultItem = {
+ status?: string;
+ error?: string;
+};
+
+type ContainerUpdateResult = {
+ failed?: number;
+ updated?: number;
+ items?: ContainerUpdateResultItem[];
+};
+
+type ConfirmAndUpdateContainerOptions = {
+ containerId: string;
+ containerName: string;
+ showPullingToast?: boolean;
+ useActivityToast?: boolean;
+ setLoading?: (loading: boolean) => void;
+ onRefresh?: () => Promise<unknown> | unknown;
+};
+
+export function confirmAndUpdateContainer({
+ containerId,
+ containerName,
+ showPullingToast = false,
+ useActivityToast = false,
+ setLoading,
+ onRefresh
+}: ConfirmAndUpdateContainerOptions) {
+ openConfirmDialog({
+ title: m.containers_update_confirm_title(),
+ message: m.containers_update_confirm_message({ name: containerName }),
+ confirm: {
+ label: m.containers_update_container(),
+ destructive: false,
+ action: async () => {
+ setLoading?.(true);
+ try {
+ if (showPullingToast) {
+ toast.info(m.containers_update_pulling_image());
+ }
+
+ const result = (await containerService.updateContainer(containerId)) as ContainerUpdateResult;
+ const toastOptions = useActivityToast ? activityToastOptions(extractActivityId(result)) : undefined;
+
+ if ((result.failed ?? 0) > 0) {
+ const failedItem = result.items?.find((item) => item.status === 'failed');
+ toast.error(
+ m.containers_update_failed({ name: containerName }) + (failedItem?.error ? `: ${failedItem.error}` : ''),
+ toastOptions
+ );
+ } else if ((result.updated ?? 0) > 0) {
+ toast.success(m.containers_update_success({ name: containerName }), toastOptions);
+ } else {
+ toast.info(m.image_update_up_to_date_title(), toastOptions);
+ }
+
+ await onRefresh?.();
+ } catch (error) {
+ console.error('Container update failed:', error);
+ toast.error(m.containers_update_failed({ name: containerName }));
+ } finally {
+ setLoading?.(false);
+ }
+ }
+ }
+ });
+}
diff --git a/frontend/src/lib/utils/docker.ts b/frontend/src/lib/utils/docker.ts
index 661493e3e..3ded073a3 100644
--- a/frontend/src/lib/utils/docker.ts
+++ b/frontend/src/lib/utils/docker.ts
@@ -1,4 +1,3 @@
-import { PersistedState } from 'runed';
import { m } from '$lib/paraglide/messages';
import type { ContainerStats, ContainerSummaryDto } from '$lib/types/docker';
import type { Environment, EnvironmentStatus } from '$lib/types/environment';
@@ -154,7 +153,7 @@ export function getProjectUpdateTooltip(updateInfo?: ProjectUpdateInfo): string
// --- Updates filter transforms ---
-export const updatesFilter = 'has_update';
+const updatesFilter = 'has_update';
export function ensureUpdatesFilter<T extends SearchPaginationSortRequest>(options: T): T {
return {
@@ -179,33 +178,13 @@ export function ensureStandaloneContainerUpdatesFilter<T extends SearchPaginatio
// --- Image pull progress tracking ---
-export type PullPhase = 'preparing' | 'downloading' | 'extracting' | 'verifying' | 'waiting' | 'complete' | 'error';
-
export interface LayerProgress {
current: number;
total: number;
status: string;
}
-export interface PullProgressState {
- progress: number;
- statusText: string;
- error: string;
- layers: Record<string, LayerProgress>;
-}
-
-export const showImageLayersState = new PersistedState('arcane-show-image-layers', false);
-
-export function createPullProgressState(): PullProgressState {
- return {
- progress: 0,
- statusText: '',
- error: '',
- layers: {}
- };
-}
-
-export function isLayerComplete(status: string): boolean {
+function isLayerComplete(status: string): boolean {
const s = status.toLowerCase();
return (
s.includes('pull complete') ||
@@ -215,38 +194,6 @@ export function isLayerComplete(status: string): boolean {
);
}
-export function getPullPhase(status: string, isComplete = false, hasError = false): PullPhase {
- if (hasError) return 'error';
- if (isComplete) return 'complete';
-
- const s = status.toLowerCase();
- if (isLayerComplete(s)) return 'complete';
- if (s.includes('downloading')) return 'downloading';
- if (s.includes('extracting')) return 'extracting';
- if (s.includes('verifying') || s.includes('digest')) return 'verifying';
- if (s.includes('waiting')) return 'waiting';
- if (s.includes('pulling') || s.includes('pull')) return 'downloading';
- return 'preparing';
-}
-
-export function isDownloadingLine(data: unknown): boolean {
- if (!data || typeof data !== 'object') return false;
-
- const obj = data as Record<string, unknown>;
- const status = String(obj['status'] ?? '').toLowerCase();
- const pd = obj['progressDetail'] as Record<string, unknown> | undefined;
-
- if (pd && (typeof pd['total'] === 'number' || typeof pd['current'] === 'number')) return true;
-
- return (
- status.includes('downloading') ||
- status.includes('extracting') ||
- status.includes('pulling fs layer') ||
- status.includes('download complete') ||
- status.includes('pull complete')
- );
-}
-
export function calculateOverallProgress(layers: Record<string, LayerProgress>): number {
const entries = Object.values(layers);
if (entries.length === 0) return 0;
@@ -350,44 +297,6 @@ export function updateLayerFromStreamData(layers: Record<string, LayerProgress>,
return { ...layers, [id]: currentLayer };
}
-export function createPullStreamHandler(callbacks: {
- onStatusChange: (status: string) => void;
- onProgressChange: (progress: number) => void;
- onLayersChange: (layers: Record<string, LayerProgress>) => void;
- onError: (error: string) => void;
- onFirstDownload?: () => void;
- errorMessage: string;
-}) {
- let layers: Record<string, LayerProgress> = {};
- let hasOpenedPopover = false;
-
- return (data: unknown) => {
- if (!data) return;
-
- if (!hasOpenedPopover && isDownloadingLine(data)) {
- hasOpenedPopover = true;
- callbacks.onFirstDownload?.();
- }
-
- const errorMsg = extractErrorMessage(data, callbacks.errorMessage);
- if (errorMsg) {
- callbacks.onError(errorMsg);
- return;
- }
-
- const obj = data as Record<string, unknown>;
- if (obj['status'] && typeof obj['status'] === 'string') {
- callbacks.onStatusChange(obj['status']);
- }
-
- layers = updateLayerFromStreamData(layers, data);
- callbacks.onLayersChange(layers);
-
- const progress = calculateOverallProgress(layers);
- callbacks.onProgressChange(progress);
- };
-}
-
export function getAggregateStatus(layers: Record<string, LayerProgress>, fallbackStatus = '', isComplete = false): string {
if (isComplete) return 'Pull complete';
@@ -411,30 +320,6 @@ export function getAggregateStatus(layers: Record<string, LayerProgress>, fallba
return fallbackStatus || 'Preparing';
}
-export function getAggregatePullPhase(layers: Record<string, LayerProgress>, isComplete = false, hasError = false): PullPhase {
- if (hasError) return 'error';
- if (isComplete) return 'complete';
-
- const entries = Object.values(layers);
- if (entries.length === 0) return 'preparing';
-
- if (areAllLayersComplete(layers)) return 'complete';
-
- const stats = getLayerStats(layers);
-
- if (stats.downloading > 0 || stats.extracting > 0) return 'downloading';
-
- const hasVerifying = entries.some(
- (l) => l.status?.toLowerCase().includes('verifying') || l.status?.toLowerCase().includes('digest')
- );
- if (hasVerifying) return 'verifying';
-
- const hasWaiting = entries.some((l) => l.status?.toLowerCase().includes('waiting'));
- if (hasWaiting) return 'waiting';
-
- return 'preparing';
-}
-
// --- Vulnerability scan polling ---
const SCAN_IN_PROGRESS_STATUSES = new Set(['pending', 'scanning']);
@@ -447,11 +332,6 @@ export type VulnerabilityScanPollOptions = {
onError?: (error: unknown) => void;
};
-export type VulnerabilityScanTracker = {
- cancel: () => void;
- promise: Promise<VulnerabilityScanSummary>;
-};
-
export type VulnerabilityScanStabilizeOptions = {
scanRequestedAt?: string | number | Date | null;
failedRecheckDelayMs?: number;
@@ -465,7 +345,7 @@ function delay(ms: number): Promise<void> {
});
}
-export function toTimestampMs(value?: string | number | Date | null): number {
+function toTimestampMs(value?: string | number | Date | null): number {
if (value == null) return 0;
if (value instanceof Date) {
const ts = value.getTime();
@@ -574,38 +454,6 @@ export function startVulnerabilityScanPolling(
};
}
-export function startVulnerabilityScanTracking(
- imageId: string,
- fetchSummary: (imageId: string) => Promise<VulnerabilityScanSummary>,
- options: VulnerabilityScanPollOptions = {}
-): VulnerabilityScanTracker {
- let resolvePromise: (summary: VulnerabilityScanSummary) => void;
- let rejectPromise: (error: unknown) => void;
-
- const promise = new Promise<VulnerabilityScanSummary>((resolve, reject) => {
- resolvePromise = resolve;
- rejectPromise = reject;
- });
-
- const cancel = startVulnerabilityScanPolling(imageId, fetchSummary, {
- ...options,
- onComplete: (summary) => {
- options.onComplete?.(summary);
- if (summary.status === 'completed') {
- resolvePromise(summary);
- } else {
- rejectPromise(summary);
- }
- },
- onError: (error) => {
- options.onError?.(error);
- rejectPromise(error);
- }
- });
-
- return { cancel, promise };
-}
-
// --- Arcane icon label extraction ---
const ARCANE_ICON_LABELS = ['arcane.icon', 'com.getarcaneapp.arcane.icon'];
@@ -670,8 +518,6 @@ export function getStatusVariant(status?: string | null): StatusVariant {
return STATUS_VARIANT_MAP[String(status).toLowerCase()] ?? 'gray';
}
-export { STATUS_VARIANT_MAP as statusVariantMap };
-
// --- Environment status resolution ---
type RuntimeEnvironmentState = Pick<Environment, 'isEdge' | 'connected' | 'status' | 'lastPollAt'>;
diff --git a/frontend/src/lib/utils/form-parsers.ts b/frontend/src/lib/utils/form-parsers.ts
new file mode 100644
index 000000000..2f902a0c5
--- /dev/null
+++ b/frontend/src/lib/utils/form-parsers.ts
@@ -0,0 +1,20 @@
+export function parseKeyValuePairs(text: string): Record<string, string> {
+ if (!text?.trim()) return {};
+
+ const result: Record<string, string> = {};
+ const lines = text.split('\n');
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed || !trimmed.includes('=')) continue;
+
+ const [key, ...valueParts] = trimmed.split('=');
+ const value = valueParts.join('=');
+
+ if (key?.trim()) {
+ result[key.trim()] = value.trim();
+ }
+ }
+
+ return result;
+}
diff --git a/frontend/src/lib/utils/formatting.ts b/frontend/src/lib/utils/formatting.ts
index 0e6c62cad..bc1d3d6b1 100644
--- a/frontend/src/lib/utils/formatting.ts
+++ b/frontend/src/lib/utils/formatting.ts
@@ -10,11 +10,6 @@ export function capitalizeFirstLetter(string: string): string {
return string.charAt(0).toUpperCase() + string.slice(1);
}
-export function shortId(id: string | undefined, length = 12): string {
- if (!id) return 'N/A';
- return id.substring(0, length);
-}
-
export function truncateString(str: string | undefined, maxLength: number): string {
if (!str) return '';
if (str.length <= maxLength) {
@@ -75,7 +70,7 @@ function bytesImpl(value: BytesValue, options?: BytesFormatOptions): string | nu
return null;
}
-export function formatBytes(value: number, options?: BytesFormatOptions): string | null {
+function formatBytes(value: number, options?: BytesFormatOptions): string | null {
if (!Number.isFinite(value)) {
return null;
}
@@ -122,7 +117,7 @@ export function formatBytes(value: number, options?: BytesFormatOptions): string
return str + unitSeparator + unit;
}
-export function parseBytes(val: string | number): number | null {
+function parseBytes(val: string | number): number | null {
if (typeof val === 'number' && !Number.isNaN(val)) {
return val;
}
@@ -178,6 +173,19 @@ export function formatDateTimeShort(date: Date | string | null | undefined): str
return formatDate(d, 'PPp');
}
+export function formatOptionalDateTime(date: Date | string | null | undefined, fallback = '-'): string {
+ if (!date) return fallback;
+ const d = typeof date === 'string' ? new Date(date) : date;
+ if (isNaN(d.getTime())) return fallback;
+ return d.toLocaleString();
+}
+
+export function isPastDate(date: Date | string | null | undefined): boolean {
+ if (!date) return false;
+ const d = typeof date === 'string' ? new Date(date) : date;
+ return !isNaN(d.getTime()) && d < new Date();
+}
+
export function formatTime(date: Date | string | null | undefined): string {
if (!date) return '';
const d = typeof date === 'string' ? new Date(date) : date;
@@ -252,7 +260,7 @@ const ANSI_ESCAPE_SEQUENCE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
const ANSI_OSC_SEQUENCE = /\x1B\][^\x07]*(?:\x07|\x1B\\)/g;
const LOOSE_ANSI_MARKER_SEQUENCE = /\[(?:\d{1,3}(?:;\d{1,3})*)m/g;
-export function stripAnsi(input: string): string {
+function stripAnsi(input: string): string {
return input.replace(ANSI_ESCAPE_SEQUENCE, '').replace(ANSI_OSC_SEQUENCE, '').replace(LOOSE_ANSI_MARKER_SEQUENCE, '');
}
diff --git a/frontend/src/lib/utils/image-updates.ts b/frontend/src/lib/utils/image-updates.ts
new file mode 100644
index 000000000..4fbc516e6
--- /dev/null
+++ b/frontend/src/lib/utils/image-updates.ts
@@ -0,0 +1,21 @@
+import type { ImageUpdateInfoDto } from '$lib/types/docker';
+import { format } from 'date-fns';
+
+export function formatImageUpdateValue(updateInfo: ImageUpdateInfoDto | undefined, mode: 'current' | 'latest') {
+ if (!updateInfo) return '-';
+
+ const digest = mode === 'current' ? updateInfo.currentDigest : updateInfo.latestDigest;
+ if (digest?.trim()) return digest.trim();
+
+ const version = mode === 'current' ? updateInfo.currentVersion : updateInfo.latestVersion;
+ if (version?.trim()) return version.trim();
+
+ return '-';
+}
+
+export function formatImageUpdateCheckedAt(value: string) {
+ if (!value) return '-';
+ const parsed = new Date(value);
+ if (Number.isNaN(parsed.getTime())) return '-';
+ return format(parsed, 'PP p');
+}
diff --git a/frontend/src/lib/utils/log-viewer.ts b/frontend/src/lib/utils/log-viewer.ts
new file mode 100644
index 000000000..50da5180d
--- /dev/null
+++ b/frontend/src/lib/utils/log-viewer.ts
@@ -0,0 +1,17 @@
+type LogViewerHandle = {
+ startLogStream: () => void;
+ stopLogStream: () => void;
+ clearLogs: (options: { hard: boolean; restart: boolean }) => Promise<void>;
+};
+
+export function startLogViewerStream(viewer: LogViewerHandle | undefined) {
+ viewer?.startLogStream();
+}
+
+export function stopLogViewerStream(viewer: LogViewerHandle | undefined) {
+ viewer?.stopLogStream();
+}
+
+export async function refreshLogViewerStream(viewer: LogViewerHandle | undefined) {
+ await viewer?.clearLogs({ hard: true, restart: true });
+}
diff --git a/frontend/src/lib/utils/navigation.ts b/frontend/src/lib/utils/navigation.ts
index 9f9b98090..fd4e8a356 100644
--- a/frontend/src/lib/utils/navigation.ts
+++ b/frontend/src/lib/utils/navigation.ts
@@ -3,27 +3,28 @@ import { PersistedState } from 'runed';
import { get } from 'svelte/store';
import { defaultMobileNavigationSettings, type MobileNavigationSettings } from '$lib/config/navigation-config';
import settingsStore from '$lib/stores/config-store';
-import type { MobileNavInteractionManager } from '$lib/hooks/use-mobile-nav-interactions';
// --- Mobile nav state ---
-export const pinnedItemsStore = new PersistedState('mobile-nav-settings', defaultMobileNavigationSettings);
+const pinnedItemsStore = new PersistedState('mobile-nav-settings', defaultMobileNavigationSettings);
export const navigationSettingsOverridesStore = new PersistedState<Partial<MobileNavigationSettings>>(
'navigation-settings-overrides',
{}
);
-let mobileNavManager: MobileNavInteractionManager | null = null;
+type NavigationVisibilityController = {
+ resetVisibility: () => void;
+};
-export function registerNavigationManager(manager: MobileNavInteractionManager) {
- mobileNavManager = manager;
+let mobileNavController: NavigationVisibilityController | null = null;
+
+export function registerNavigationVisibilityController(controller: NavigationVisibilityController | null) {
+ mobileNavController = controller;
}
export function resetNavigationVisibility() {
- if (mobileNavManager) {
- mobileNavManager.resetVisibility();
- }
+ mobileNavController?.resetVisibility();
}
export function getEffectiveNavigationSettings(): MobileNavigationSettings {
@@ -49,22 +50,13 @@ export function getEffectiveNavigationSettings(): MobileNavigationSettings {
};
}
-export function updateNavigationOverrides(overrides: Partial<MobileNavigationSettings>) {
- const currentOverrides = navigationSettingsOverridesStore.current;
- navigationSettingsOverridesStore.current = { ...currentOverrides, ...overrides };
-}
-
-export function clearNavigationOverrides() {
- navigationSettingsOverridesStore.current = {};
-}
-
// --- Keyboard shortcuts ---
export type ShortcutKey = 'mod' | 'shift' | 'alt' | 'ctrl' | 'meta' | string;
const MODIFIER_KEYS = new Set(['mod', 'shift', 'alt', 'ctrl', 'meta']);
-export function isMacOS(): boolean {
+function isMacOS(): boolean {
if (!browser) return false;
const platform = navigator?.platform?.toLowerCase() ?? '';
const userAgent = navigator?.userAgent?.toLowerCase() ?? '';
@@ -185,7 +177,7 @@ function commitSegmentForHost(hostname: string): string {
return '/commit/';
}
-export function toGitWebUrl(raw: string): string | null {
+function toGitWebUrl(raw: string): string | null {
const trimmed = raw.trim();
if (!trimmed) return null;
diff --git a/frontend/src/lib/utils/options.ts b/frontend/src/lib/utils/options.ts
new file mode 100644
index 000000000..2c7cf1297
--- /dev/null
+++ b/frontend/src/lib/utils/options.ts
@@ -0,0 +1,25 @@
+function selectedOptionLabel<T extends { id: string; name: string }>(options: T[], value: string, fallback: string): string {
+ return options.find((option) => option.id === value)?.name ?? fallback;
+}
+
+export const GLOBAL_ENVIRONMENT_OPTION_ID = 'global';
+
+export function buildGlobalEnvironmentOptions<T extends { id: string; name: string }>(
+ environments: T[],
+ globalLabel: string
+): { id: string; name: string }[] {
+ return [
+ { id: GLOBAL_ENVIRONMENT_OPTION_ID, name: globalLabel },
+ ...environments.map((env) => ({ id: env.id, name: env.name }))
+ ];
+}
+
+export function createRoleEnvironmentLabelers<
+ TRole extends { id: string; name: string },
+ TEnvironment extends { id: string; name: string }
+>(roles: TRole[], environments: TEnvironment[], fallback: string) {
+ return {
+ environment: (value: string) => selectedOptionLabel(environments, value, fallback),
+ role: (value: string) => selectedOptionLabel(roles, value, fallback)
+ };
+}
diff --git a/frontend/src/lib/utils/resource-actions.ts b/frontend/src/lib/utils/resource-actions.ts
new file mode 100644
index 000000000..2484b0a3a
--- /dev/null
+++ b/frontend/src/lib/utils/resource-actions.ts
@@ -0,0 +1,38 @@
+import type { ActionButton } from '$lib/layouts';
+
+type CreateRefreshActionOptions = {
+ canCreate: boolean;
+ createLabel: string;
+ onCreate: () => void;
+ refreshLabel: string;
+ onRefresh: () => void | Promise<void>;
+ refreshing: boolean;
+};
+
+export function createRefreshActionButtons({
+ canCreate,
+ createLabel,
+ onCreate,
+ refreshLabel,
+ onRefresh,
+ refreshing
+}: CreateRefreshActionOptions): ActionButton[] {
+ const buttons: ActionButton[] = [];
+ if (canCreate) {
+ buttons.push({
+ id: 'create',
+ action: 'create',
+ label: createLabel,
+ onclick: onCreate
+ });
+ }
+ buttons.push({
+ id: 'refresh',
+ action: 'restart',
+ label: refreshLabel,
+ onclick: onRefresh,
+ loading: refreshing,
+ disabled: refreshing
+ });
+ return buttons;
+}
diff --git a/frontend/src/lib/utils/settings-form.ts b/frontend/src/lib/utils/settings-form.ts
new file mode 100644
index 000000000..37170930e
--- /dev/null
+++ b/frontend/src/lib/utils/settings-form.ts
@@ -0,0 +1,86 @@
+import { toast } from 'svelte-sonner';
+import { z } from 'zod/v4';
+import { UseSettingsForm } from '$lib/hooks/use-settings-form.svelte';
+import { m } from '$lib/paraglide/messages';
+import type { Settings } from '$lib/types/settings';
+import { createForm } from '$lib/utils/settings';
+
+type SettingsPayload = Partial<Settings> & Record<string, unknown>;
+
+export interface SettingsFormConfig<T extends z.ZodType<SettingsPayload, any>> {
+ schema: T;
+ currentSettings: z.infer<T>;
+ getCurrentSettings?: () => z.infer<T>;
+ /**
+ * Custom save handler. If provided, this will be called instead of the default
+ * settingsService.updateSettings(). Useful for environment-specific settings
+ * or other custom save logic.
+ */
+ onSave?: (data: z.infer<T>) => Promise<void>;
+ onSuccess?: () => void;
+ onReset?: () => void;
+ successMessage?: string;
+ errorMessage?: string;
+}
+
+export function createSettingsForm<T extends z.ZodType<any, any>>(config: SettingsFormConfig<T>) {
+ const {
+ schema,
+ currentSettings,
+ getCurrentSettings,
+ onSave,
+ onSuccess,
+ onReset,
+ successMessage = m.common_update_success({ resource: m.settings_title() }),
+ errorMessage = m.common_update_failed({ resource: m.settings_title() })
+ } = config;
+
+ const { inputs: formInputs, ...form } = createForm(schema, currentSettings);
+
+ const settingsForm = new UseSettingsForm({
+ formInputs,
+ getCurrentSettings: getCurrentSettings ?? (() => currentSettings),
+ onSave
+ });
+
+ const onSubmit = async () => {
+ const data = form.validate();
+ if (!data) {
+ toast.error(m.security_form_validation_error());
+ return;
+ }
+ settingsForm.setLoading(true);
+
+ try {
+ await settingsForm.updateSettings(data);
+ toast.success(successMessage);
+ onSuccess?.();
+ } catch (error) {
+ console.error('Failed to save settings:', error);
+ const message = error instanceof Error ? error.message : errorMessage;
+ toast.error(message);
+ } finally {
+ settingsForm.setLoading(false);
+ }
+ };
+
+ const resetForm = () => {
+ form.reset();
+ onReset?.();
+ };
+
+ settingsForm.registerFormActions(onSubmit, resetForm);
+
+ const registerOnMount = () => {
+ settingsForm.registerFormActions(onSubmit, resetForm);
+ };
+
+ return {
+ formInputs,
+ form,
+ settingsForm,
+ onSubmit,
+ resetForm,
+ registerOnMount
+ };
+}
diff --git a/frontend/src/lib/utils/settings-load.ts b/frontend/src/lib/utils/settings-load.ts
new file mode 100644
index 000000000..e38b307d6
--- /dev/null
+++ b/frontend/src/lib/utils/settings-load.ts
@@ -0,0 +1,29 @@
+import { queryKeys } from '$lib/query/query-keys';
+import { settingsService } from '$lib/services/settings-service';
+import { environmentStore } from '$lib/stores/environment.store.svelte';
+
+type ParentWithQueryClient = () => Promise<{
+ queryClient: unknown;
+ [key: string]: unknown;
+}>;
+
+type QueryClientLike = {
+ fetchQuery: <T>(options: { queryKey: unknown; queryFn: () => Promise<T> }) => Promise<T>;
+};
+
+export async function loadMergedSettingsPage(parent: ParentWithQueryClient, errorContext: string) {
+ const { queryClient } = await parent();
+ const client = queryClient as QueryClientLike;
+ const envId = await environmentStore.getCurrentEnvironmentId();
+
+ try {
+ const settings = await client.fetchQuery({
+ queryKey: queryKeys.settings.byEnvironment(envId),
+ queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
+ });
+ return { settings };
+ } catch (error) {
+ console.error(`Failed to load ${errorContext}:`, error);
+ throw error;
+ }
+}
diff --git a/frontend/src/lib/utils/settings.ts b/frontend/src/lib/utils/settings.ts
index a6145d38f..49bb7f18c 100644
--- a/frontend/src/lib/utils/settings.ts
+++ b/frontend/src/lib/utils/settings.ts
@@ -1,8 +1,6 @@
import { get, writable } from 'svelte/store';
-import { toast } from 'svelte-sonner';
import { z } from 'zod/v4';
-import { UseSettingsForm } from '$lib/hooks/use-settings-form.svelte';
-import type { ApplicationTheme, Settings } from '$lib/types/settings';
+import type { ApplicationTheme } from '$lib/types/settings';
// --- Local vs environment settings classification ---
@@ -190,85 +188,3 @@ export function createForm<T extends z.ZodType<any, any>>(schema: T, initialValu
reset
};
}
-
-// --- Settings-specific form wrapper ---
-
-type SettingsPayload = Partial<Settings> & Record<string, unknown>;
-
-export interface SettingsFormConfig<T extends z.ZodType<SettingsPayload, any>> {
- schema: T;
- currentSettings: z.infer<T>;
- getCurrentSettings?: () => z.infer<T>;
- /**
- * Custom save handler. If provided, this will be called instead of the default
- * settingsService.updateSettings(). Useful for environment-specific settings
- * or other custom save logic.
- */
- onSave?: (data: z.infer<T>) => Promise<void>;
- onSuccess?: () => void;
- onReset?: () => void;
- successMessage?: string;
- errorMessage?: string;
-}
-
-export function createSettingsForm<T extends z.ZodType<any, any>>(config: SettingsFormConfig<T>) {
- const {
- schema,
- currentSettings,
- getCurrentSettings,
- onSave,
- onSuccess,
- onReset,
- successMessage = 'Settings saved',
- errorMessage = 'Failed to save settings'
- } = config;
-
- const { inputs: formInputs, ...form } = createForm(schema, currentSettings);
-
- const settingsForm = new UseSettingsForm({
- formInputs,
- getCurrentSettings: getCurrentSettings ?? (() => currentSettings),
- onSave
- });
-
- const onSubmit = async () => {
- const data = form.validate();
- if (!data) {
- toast.error('Please check the form for errors');
- return;
- }
- settingsForm.setLoading(true);
-
- try {
- await settingsForm.updateSettings(data);
- toast.success(successMessage);
- onSuccess?.();
- } catch (error) {
- console.error('Failed to save settings:', error);
- const message = error instanceof Error ? error.message : errorMessage;
- toast.error(message);
- } finally {
- settingsForm.setLoading(false);
- }
- };
-
- const resetForm = () => {
- form.reset();
- onReset?.();
- };
-
- settingsForm.registerFormActions(onSubmit, resetForm);
-
- const registerOnMount = () => {
- settingsForm.registerFormActions(onSubmit, resetForm);
- };
-
- return {
- formInputs,
- form,
- settingsForm,
- onSubmit,
- resetForm,
- registerOnMount
- };
-}
diff --git a/frontend/src/lib/utils/streaming.ts b/frontend/src/lib/utils/streaming.ts
new file mode 100644
index 000000000..a3d9f1af0
--- /dev/null
+++ b/frontend/src/lib/utils/streaming.ts
@@ -0,0 +1,33 @@
+export async function readNdjsonStream(
+ body: ReadableStream<Uint8Array>,
+ onMessage?: (data: any) => void,
+ onLine?: (data: any) => void
+): Promise<void> {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split('\n');
+ buffer = lines.pop() || '';
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+
+ let obj: any;
+ try {
+ obj = JSON.parse(trimmed);
+ } catch {
+ continue;
+ }
+
+ onLine?.(obj);
+ onMessage?.(obj);
+ }
+ }
+}
diff --git a/frontend/src/lib/utils/swarm-kv.ts b/frontend/src/lib/utils/swarm-kv.ts
new file mode 100644
index 000000000..26743b0d1
--- /dev/null
+++ b/frontend/src/lib/utils/swarm-kv.ts
@@ -0,0 +1,31 @@
+import { m } from '$lib/paraglide/messages';
+import { formatDistanceToNow } from 'date-fns';
+
+export function getSwarmSpecName(spec: Record<string, unknown> | null | undefined, fallback: string): string {
+ const name = spec && typeof spec === 'object' ? spec['Name'] : undefined;
+ return typeof name === 'string' && name.trim() ? name : fallback.slice(0, 12);
+}
+
+export function decodeBase64ToText(base64Value: string): string {
+ try {
+ const binary = atob(base64Value);
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
+ return new TextDecoder().decode(bytes);
+ } catch {
+ return '';
+ }
+}
+
+export function encodeTextToBase64(value: string): string {
+ const bytes = new TextEncoder().encode(value);
+ let binary = '';
+ for (const byte of bytes) {
+ binary += String.fromCharCode(byte);
+ }
+ return btoa(binary);
+}
+
+export function formatSwarmTimestamp(timestamp: string): string {
+ if (!timestamp) return m.common_unknown();
+ return formatDistanceToNow(new Date(timestamp), { addSuffix: true });
+}
diff --git a/frontend/src/lib/utils/swarm-tasks.ts b/frontend/src/lib/utils/swarm-tasks.ts
new file mode 100644
index 000000000..2e07aa142
--- /dev/null
+++ b/frontend/src/lib/utils/swarm-tasks.ts
@@ -0,0 +1,37 @@
+import type { SwarmTaskSummary } from '$lib/types/swarm';
+
+const SWARM_TASK_STATE_ORDER: Record<string, number> = {
+ running: 0,
+ starting: 1,
+ pending: 2,
+ ready: 3,
+ complete: 4,
+ shutdown: 5,
+ failed: 6,
+ rejected: 7,
+ orphaned: 8,
+ remove: 9
+};
+
+export function getSwarmTaskStateVariant(state: string): 'green' | 'amber' | 'red' | 'gray' {
+ if (state === 'running') return 'green';
+ if (state === 'pending' || state === 'starting') return 'amber';
+ if (state === 'failed' || state === 'rejected' || state === 'shutdown') return 'red';
+ return 'gray';
+}
+
+export function getSwarmTaskIconVariant(state: string): 'emerald' | 'amber' | 'red' | 'gray' {
+ if (state === 'running') return 'emerald';
+ if (state === 'pending' || state === 'starting') return 'amber';
+ if (state === 'failed' || state === 'rejected' || state === 'shutdown') return 'red';
+ return 'gray';
+}
+
+export function sortSwarmTasks(raw: SwarmTaskSummary[]): SwarmTaskSummary[] {
+ return [...raw].sort((a, b) => {
+ const stateA = SWARM_TASK_STATE_ORDER[a.currentState] ?? 99;
+ const stateB = SWARM_TASK_STATE_ORDER[b.currentState] ?? 99;
+ if (stateA !== stateB) return stateA - stateB;
+ return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
+ });
+}
diff --git a/frontend/src/lib/utils/table-action-types.ts b/frontend/src/lib/utils/table-action-types.ts
new file mode 100644
index 000000000..3babeda32
--- /dev/null
+++ b/frontend/src/lib/utils/table-action-types.ts
@@ -0,0 +1,18 @@
+export type TableActionConfig<TStatus extends string> = {
+ status: TStatus;
+ run: (id: string) => Promise<unknown>;
+ success: () => string;
+ failure: () => string;
+};
+
+export type TableBulkActionConfig<TLoadingKey extends string> = {
+ title: (count: number) => string;
+ message: (count: number) => string;
+ label: string;
+ loadingKey: TLoadingKey;
+ run: (id: string) => Promise<unknown>;
+ success: (count: number) => string;
+ partial: (success: number, total: number, failed: number) => string;
+ failure: () => string;
+ destructive?: boolean;
+};
diff --git a/frontend/src/lib/utils/tables.ts b/frontend/src/lib/utils/tables.ts
index 4e7e2e604..a09f64d93 100644
--- a/frontend/src/lib/utils/tables.ts
+++ b/frontend/src/lib/utils/tables.ts
@@ -2,11 +2,12 @@ import { browser } from '$app/environment';
import { PersistedState } from 'runed';
import { decodeSort, type CompactTablePrefs } from '$lib/components/arcane-table/arcane-table.types.svelte';
import { TABLE_PAGE_SIZE_ALL, TABLE_PAGE_SIZE_OPTIONS } from '$lib/constants/table-pagination';
+import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { FilterMap, FilterValue, SearchPaginationSortRequest } from '$lib/types/shared';
const DEFAULT_LIMIT = 20;
-export function normalizeTablePageSize(limit: unknown): number | undefined {
+function normalizeTablePageSize(limit: unknown): number | undefined {
const parsed = typeof limit === 'number' ? limit : Number.parseInt(String(limit), 10);
if (!Number.isFinite(parsed)) return undefined;
@@ -115,6 +116,43 @@ export function resolveInitialTableRequest(
return base;
}
+export function resolveInitialListPageRequest(
+ persistKey: string,
+ sort: NonNullable<SearchPaginationSortRequest['sort']>,
+ limit = 20
+): SearchPaginationSortRequest {
+ return resolveInitialTableRequest(persistKey, {
+ pagination: {
+ page: 1,
+ limit
+ },
+ sort
+ } satisfies SearchPaginationSortRequest);
+}
+
+type QueryClientLike = {
+ fetchQuery: <T>(options: { queryKey: unknown; queryFn: () => Promise<T> }) => Promise<T>;
+};
+
+type ParentWithQueryClient = () => Promise<unknown>;
+
+export async function resolveListPageLoadContext(
+ parent: ParentWithQueryClient,
+ persistKey: string,
+ sort: NonNullable<SearchPaginationSortRequest['sort']>,
+ limit = 20
+) {
+ const parentData = (await parent()) as { queryClient: QueryClientLike };
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ const requestOptions = resolveInitialListPageRequest(persistKey, sort, limit);
+
+ return {
+ queryClient: parentData.queryClient,
+ envId,
+ requestOptions
+ };
+}
+
export function transformPaginationParams(options?: SearchPaginationSortRequest): Record<string, any> {
const params: Record<string, any> = {};
diff --git a/frontend/src/lib/utils/template-editor.ts b/frontend/src/lib/utils/template-editor.ts
new file mode 100644
index 000000000..3f0bd4beb
--- /dev/null
+++ b/frontend/src/lib/utils/template-editor.ts
@@ -0,0 +1,108 @@
+import { m } from '$lib/paraglide/messages';
+import { handleApiResultWithCallbacks, tryCatch } from '$lib/utils/api';
+import { toast } from 'svelte-sonner';
+import { z } from 'zod/v4';
+
+export type TemplateEditorValidationState = {
+ composeValidationReady: boolean;
+ envValidationReady: boolean;
+ composeHasErrors: boolean;
+ envHasErrors: boolean;
+};
+
+type ResetField<T> = {
+ set: (value: T) => void;
+ value: T;
+};
+
+type ValidationResult<T> = T | undefined | false | null;
+
+type RunTemplateEditorSaveOptions<TValidated, TResult> = {
+ validationState: TemplateEditorValidationState;
+ validate: () => ValidationResult<TValidated>;
+ save: (validated: TValidated) => Promise<TResult>;
+ failureMessage: string;
+ setLoading: (value: boolean) => void;
+ onSuccess: (validated: TValidated, result: TResult) => void | Promise<void>;
+};
+
+export function createNamedTemplateSchema() {
+ return z.object({
+ name: z.string().min(1, m.templates_template_name_required()),
+ description: z.string().optional().default(''),
+ composeContent: z.string().min(1, m.templates_content_required()),
+ envContent: z.string().optional().default('')
+ });
+}
+
+export function createTemplateContentSchema() {
+ return z.object({
+ composeContent: z.string().min(1, m.compose_compose_content_required()),
+ envContent: z.string().optional().default('')
+ });
+}
+
+export function getTemplateEditorValidationState(
+ composeValidationReady: boolean,
+ envValidationReady: boolean,
+ composeHasErrors: boolean,
+ envHasErrors: boolean
+): TemplateEditorValidationState {
+ return {
+ composeValidationReady,
+ envValidationReady,
+ composeHasErrors,
+ envHasErrors
+ };
+}
+
+export function hasTemplateEditorErrors(state: TemplateEditorValidationState): boolean {
+ return !state.composeValidationReady || !state.envValidationReady || state.composeHasErrors || state.envHasErrors;
+}
+
+export function validateTemplateEditorForm<T>(
+ state: TemplateEditorValidationState,
+ validate: () => ValidationResult<T>
+): T | null {
+ if (hasTemplateEditorErrors(state)) {
+ toast.error(m.templates_validation_error());
+ return null;
+ }
+
+ const validated = validate();
+ if (!validated) {
+ toast.error(m.templates_validation_error());
+ return null;
+ }
+
+ return validated;
+}
+
+export async function runTemplateEditorSave<TValidated, TResult>({
+ validationState,
+ validate,
+ save,
+ failureMessage,
+ setLoading,
+ onSuccess
+}: RunTemplateEditorSaveOptions<TValidated, TResult>) {
+ const validated = validateTemplateEditorForm(validationState, validate);
+ if (!validated) return;
+
+ handleApiResultWithCallbacks({
+ result: await tryCatch(save(validated)),
+ message: failureMessage,
+ setLoadingState: setLoading,
+ onSuccess: async (result) => {
+ await onSuccess(validated, result);
+ }
+ });
+}
+
+export function resetTemplateEditorFields<T>(fields: ResetField<T>[]) {
+ for (const field of fields) {
+ field.set(field.value);
+ }
+
+ toast.info(m.templates_reset_success());
+}
diff --git a/frontend/src/lib/utils/template-load.ts b/frontend/src/lib/utils/template-load.ts
new file mode 100644
index 000000000..b381d8ad8
--- /dev/null
+++ b/frontend/src/lib/utils/template-load.ts
@@ -0,0 +1,65 @@
+import { queryKeys } from '$lib/query/query-keys';
+import { templateService } from '$lib/services/template-service';
+import type { Variable } from '$lib/types/shared';
+
+type QueryClientLike = {
+ fetchQuery: <T>(options: { queryKey: unknown; queryFn: () => Promise<T> }) => Promise<T>;
+};
+
+type ParentWithQueryClient = () => Promise<{
+ queryClient: unknown;
+ [key: string]: unknown;
+}>;
+
+export function globalVariablesToMap(globalVariables: Variable[] | null | undefined): Record<string, string> {
+ return Object.fromEntries((globalVariables ?? []).map((item) => [item.key, item.value]));
+}
+
+export async function loadTemplateAuthoringData(parent: ParentWithQueryClient) {
+ const { queryClient } = await parent();
+ const client = queryClient as QueryClientLike;
+
+ const [defaultTemplates, templates, globalVariables] = await Promise.all([
+ client
+ .fetchQuery({
+ queryKey: queryKeys.templates.defaults(),
+ queryFn: () => templateService.getDefaultTemplates()
+ })
+ .catch((err) => {
+ console.warn('Failed to load default templates:', err);
+ return { composeTemplate: '', envTemplate: '' };
+ }),
+ client
+ .fetchQuery({
+ queryKey: queryKeys.templates.allTemplates(),
+ queryFn: () => templateService.getAllTemplates()
+ })
+ .catch((err) => {
+ console.warn('Failed to load templates:', err);
+ return [];
+ }),
+ client
+ .fetchQuery({
+ queryKey: queryKeys.templates.globalVariables(),
+ queryFn: () => templateService.getGlobalVariables()
+ })
+ .catch((err) => {
+ console.warn('Failed to load global variables:', err);
+ return [];
+ })
+ ]);
+
+ return { defaultTemplates, templates, globalVariables };
+}
+
+export async function loadTemplateContent(client: QueryClientLike, templateId: string) {
+ return client
+ .fetchQuery({
+ queryKey: queryKeys.templates.content(templateId),
+ queryFn: () => templateService.getTemplateContent(templateId)
+ })
+ .catch((err) => {
+ console.warn('Failed to load selected template:', err);
+ return null;
+ });
+}
diff --git a/frontend/src/lib/utils/theme.ts b/frontend/src/lib/utils/theme.ts
index 80e01a939..0d979f74e 100644
--- a/frontend/src/lib/utils/theme.ts
+++ b/frontend/src/lib/utils/theme.ts
@@ -213,8 +213,9 @@ const DEFAULT_ACCENT_COLOR = 'oklch(0.606 0.25 292.717)';
let htmlClassObserver: MutationObserver | null = null;
+// fallow-ignore-next-line unused-export
export const accentColorPreviewStore = writable<string>(DEFAULT_ACCENT_COLOR);
-export const oledModeStore = writable<boolean>(false);
+const oledModeStore = writable<boolean>(false);
export function resolveApplicationTheme(value?: string | null): ApplicationTheme {
if (!value) {
@@ -262,7 +263,7 @@ function ensureThemeColorSyncObserver(): void {
});
}
-export function syncBrowserThemeColor(): void {
+function syncBrowserThemeColor(): void {
if (typeof document === 'undefined') {
return;
}
diff --git a/frontend/src/lib/utils/vulnerability.ts b/frontend/src/lib/utils/vulnerability.ts
new file mode 100644
index 000000000..74b0934fb
--- /dev/null
+++ b/frontend/src/lib/utils/vulnerability.ts
@@ -0,0 +1,178 @@
+import { m } from '$lib/paraglide/messages';
+import type {
+ SeveritySummary,
+ Vulnerability,
+ VulnerabilityScanResult,
+ VulnerabilityScanSummary,
+ VulnerabilityWithImage
+} from '$lib/types/environment';
+import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
+import { activityToastOptions, extractActivityId } from '$lib/utils/activity-toast';
+import { toast } from 'svelte-sonner';
+
+export type VulnerabilitySeverityBadgeVariant = 'red' | 'orange' | 'amber' | 'green' | 'gray';
+export type VulnerabilitySeverityIconVariant = 'red' | 'orange' | 'amber' | 'emerald' | 'gray';
+export type VulnerabilityRow = VulnerabilityWithImage & { id: string };
+
+type VulnerabilitySeveritySource = Pick<Vulnerability, 'severity'>;
+type VulnerabilityToastSource = Pick<VulnerabilityScanResult | VulnerabilityScanSummary, 'status' | 'activityId' | 'error'>;
+
+export function buildSeveritySummary(vulnerabilities: VulnerabilitySeveritySource[]): SeveritySummary {
+ const summary: SeveritySummary = {
+ critical: 0,
+ high: 0,
+ medium: 0,
+ low: 0,
+ unknown: 0,
+ total: 0
+ };
+
+ for (const vulnerability of vulnerabilities) {
+ switch (vulnerability.severity) {
+ case 'CRITICAL':
+ summary.critical++;
+ break;
+ case 'HIGH':
+ summary.high++;
+ break;
+ case 'MEDIUM':
+ summary.medium++;
+ break;
+ case 'LOW':
+ summary.low++;
+ break;
+ default:
+ summary.unknown++;
+ }
+ summary.total++;
+ }
+
+ return summary;
+}
+
+export function getSeverityLabel(severity: string): string {
+ switch (severity) {
+ case 'CRITICAL':
+ return m.vuln_severity_critical();
+ case 'HIGH':
+ return m.vuln_severity_high();
+ case 'MEDIUM':
+ return m.vuln_severity_medium();
+ case 'LOW':
+ return m.vuln_severity_low();
+ default:
+ return m.vuln_severity_unknown();
+ }
+}
+
+export function getSeverityBadgeVariant(severity: string): VulnerabilitySeverityBadgeVariant {
+ switch (severity) {
+ case 'CRITICAL':
+ return 'red';
+ case 'HIGH':
+ return 'orange';
+ case 'MEDIUM':
+ return 'amber';
+ case 'LOW':
+ return 'green';
+ default:
+ return 'gray';
+ }
+}
+
+export function getSeverityIconVariant(severity: string): VulnerabilitySeverityIconVariant {
+ switch (severity) {
+ case 'CRITICAL':
+ return 'red';
+ case 'HIGH':
+ return 'orange';
+ case 'MEDIUM':
+ return 'amber';
+ case 'LOW':
+ return 'emerald';
+ default:
+ return 'gray';
+ }
+}
+
+export function mapVulnerabilityRequest(options: SearchPaginationSortRequest): SearchPaginationSortRequest {
+ const filters = { ...(options.filters ?? {}) };
+ if (filters['vulnSeverity']) {
+ filters['severity'] = filters['vulnSeverity'];
+ delete filters['vulnSeverity'];
+ }
+
+ const sort = options.sort?.column === 'vulnSeverity' ? { ...options.sort, column: 'severity' } : options.sort;
+
+ return {
+ ...options,
+ sort,
+ filters: Object.keys(filters).length ? filters : undefined
+ };
+}
+
+function getVulnerabilityKey(vulnerability: VulnerabilityWithImage, index: number): string {
+ return [
+ vulnerability.imageId,
+ vulnerability.vulnerabilityId,
+ vulnerability.pkgName,
+ vulnerability.installedVersion ?? '',
+ vulnerability.fixedVersion ?? '',
+ String(index)
+ ].join('-');
+}
+
+export function mapVulnerabilityPage(
+ page: Paginated<VulnerabilityWithImage>,
+ options: SearchPaginationSortRequest
+): Paginated<VulnerabilityRow> {
+ const pageNumber = options.pagination?.page ?? page.pagination?.currentPage ?? 1;
+ const limit = options.pagination?.limit ?? page.pagination?.itemsPerPage ?? 20;
+ const offset = (pageNumber - 1) * limit;
+ return {
+ ...page,
+ data: (page.data ?? []).map((item, index) => ({
+ ...item,
+ id: getVulnerabilityKey(item, offset + index)
+ }))
+ };
+}
+
+export function resolveSeverityFilter(options?: SearchPaginationSortRequest): string | undefined {
+ const rawSeverity = options?.filters?.['severity'] ?? options?.filters?.['vulnSeverity'];
+ if (Array.isArray(rawSeverity)) {
+ const values = rawSeverity.map((entry) => String(entry).trim()).filter(Boolean);
+ return values.length ? values.join(',') : undefined;
+ }
+
+ if (rawSeverity === undefined || rawSeverity === null) {
+ return undefined;
+ }
+
+ const value = String(rawSeverity).trim();
+ return value || undefined;
+}
+
+export function toastVulnerabilityScanStatus(
+ result: VulnerabilityToastSource,
+ options: {
+ includeStarted?: boolean;
+ } = {}
+) {
+ const { includeStarted = false } = options;
+ const toastOptions = activityToastOptions(extractActivityId(result));
+
+ if (result.status === 'completed') {
+ toast.success(m.vuln_scan_completed(), toastOptions);
+ return;
+ }
+
+ if (result.status === 'failed') {
+ toast.error(result.error || m.vuln_scan_failed(), toastOptions);
+ return;
+ }
+
+ if (includeStarted) {
+ toast.info(m.vuln_scan_started(), toastOptions);
+ }
+}
diff --git a/frontend/src/lib/utils/ws.ts b/frontend/src/lib/utils/ws.ts
index 17937d5f5..8364ade16 100644
--- a/frontend/src/lib/utils/ws.ts
+++ b/frontend/src/lib/utils/ws.ts
@@ -129,18 +129,6 @@ export class ReconnectingWebSocket<T = unknown> {
}, backoff);
}
- send(payload: string | ArrayBuffer | Blob) {
- try {
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
- this.ws.send(payload as any);
- return true;
- }
- } catch (err) {
- this.opts.onError?.(err as Error);
- }
- return false;
- }
-
close() {
this.closed = true;
this.attempt = 0;
@@ -197,10 +185,6 @@ export class ReconnectingWebSocket<T = unknown> {
}
});
}
-
- isConnected() {
- return !!this.ws && this.ws.readyState === WebSocket.OPEN;
- }
}
export function createStatsWebSocket(opts: {
@@ -264,20 +248,7 @@ export function createDiagnosticsWebSocket(opts: {
onError?: (err: Event | Error) => void;
maxBackoff?: number;
}) {
- const buildUrl = () => {
- const protocol = location.protocol === 'https:' ? 'wss' : 'ws';
- return `${protocol}://${location.host}/api/diagnostics/stream`;
- };
-
- return new ReconnectingWebSocket<Diagnostics>({
- buildUrl,
- parseMessage: (evt) => JSON.parse(evt.data as string) as Diagnostics,
- onMessage: opts.onMessage,
- onOpen: opts.onOpen,
- onClose: opts.onClose,
- onError: opts.onError,
- maxBackoff: opts.maxBackoff
- });
+ return createDiagnosticsStreamWebSocket('/api/diagnostics/stream', opts);
}
export function createBackendLogsWebSocket(opts: {
@@ -287,14 +258,27 @@ export function createBackendLogsWebSocket(opts: {
onError?: (err: Event | Error) => void;
maxBackoff?: number;
}) {
+ return createDiagnosticsStreamWebSocket('/api/diagnostics/logs/stream', opts);
+}
+
+function createDiagnosticsStreamWebSocket<T>(
+ path: string,
+ opts: {
+ onMessage: (data: T) => void;
+ onOpen?: () => void;
+ onClose?: () => void;
+ onError?: (err: Event | Error) => void;
+ maxBackoff?: number;
+ }
+) {
const buildUrl = () => {
const protocol = location.protocol === 'https:' ? 'wss' : 'ws';
- return `${protocol}://${location.host}/api/diagnostics/logs/stream`;
+ return `${protocol}://${location.host}${path}`;
};
- return new ReconnectingWebSocket<LogEntry>({
+ return new ReconnectingWebSocket<T>({
buildUrl,
- parseMessage: (evt) => JSON.parse(evt.data as string) as LogEntry,
+ parseMessage: (evt) => JSON.parse(evt.data as string) as T,
onMessage: opts.onMessage,
onOpen: opts.onOpen,
onClose: opts.onClose,
diff --git a/frontend/src/routes/(app)/containers/components/ContainerLogsPanel.svelte b/frontend/src/routes/(app)/containers/components/ContainerLogsPanel.svelte
index 4b8784643..657b16ec9 100644
--- a/frontend/src/routes/(app)/containers/components/ContainerLogsPanel.svelte
+++ b/frontend/src/routes/(app)/containers/components/ContainerLogsPanel.svelte
@@ -8,6 +8,7 @@
import { m } from '$lib/paraglide/messages';
import { bytes } from '$lib/utils/formatting';
import { calculateCPUPercent, calculateMemoryUsage } from '$lib/utils/docker';
+ import { refreshLogViewerStream, startLogViewerStream, stopLogViewerStream } from '$lib/utils/log-viewer';
import { CpuIcon, FileTextIcon, MemoryStickIcon } from '$lib/icons';
import ContainerLogStatMonitor from './ContainerLogStatMonitor.svelte';
@@ -127,15 +128,15 @@
}
function handleStart() {
- viewer?.startLogStream();
+ startLogViewerStream(viewer);
}
function handleStop() {
- viewer?.stopLogStream();
+ stopLogViewerStream(viewer);
}
async function handleRefresh() {
- await viewer?.clearLogs({ hard: true, restart: true });
+ await refreshLogViewerStream(viewer);
}
// Sync isStreaming from viewer callbacks
diff --git a/frontend/src/routes/(app)/containers/container-table.actions.ts b/frontend/src/routes/(app)/containers/container-table.actions.ts
index f21132ca7..c1b386011 100644
--- a/frontend/src/routes/(app)/containers/container-table.actions.ts
+++ b/frontend/src/routes/(app)/containers/container-table.actions.ts
@@ -6,6 +6,8 @@ import { handleApiResultWithCallbacks } from '$lib/utils/api';
import { tryCatch } from '$lib/utils/api';
import { activityToastOptions, extractActivityId } from '$lib/utils/activity-toast';
import { bulkConfirmAndRun } from '$lib/utils/bulk-actions';
+import { confirmAndRemoveContainer, confirmAndUpdateContainer, runContainerLifecycleAction } from '$lib/utils/container-actions';
+import type { TableActionConfig, TableBulkActionConfig } from '$lib/utils/table-action-types';
import { toast } from 'svelte-sonner';
import { getContainerDisplayName, type ActionStatus } from './container-table.helpers';
@@ -26,44 +28,10 @@ type ActionDeps = {
type ContainerActionKind = 'start' | 'stop' | 'restart' | 'redeploy';
-type ContainerActionConfig = {
- status: ActionStatus;
- run: (id: string) => Promise<unknown>;
- success: () => string;
- failure: () => string;
-};
-
-type BulkActionConfig = {
- title: (count: number) => string;
- message: (count: number) => string;
- label: string;
- loadingKey: keyof BulkLoadingState;
- run: (id: string) => Promise<unknown>;
- success: (count: number) => string;
- partial: (success: number, total: number, failed: number) => string;
- failure: () => string;
- destructive?: boolean;
-};
+type ContainerActionConfig = TableActionConfig<ActionStatus>;
+type BulkActionConfig = TableBulkActionConfig<keyof BulkLoadingState>;
-const containerActionConfigs: Record<ContainerActionKind, ContainerActionConfig> = {
- start: {
- status: 'starting',
- run: (id) => containerService.startContainer(id),
- success: () => m.containers_start_success(),
- failure: () => m.containers_start_failed()
- },
- stop: {
- status: 'stopping',
- run: (id) => containerService.stopContainer(id),
- success: () => m.containers_stop_success(),
- failure: () => m.containers_stop_failed()
- },
- restart: {
- status: 'restarting',
- run: (id) => containerService.restartContainer(id),
- success: () => m.containers_restart_success(),
- failure: () => m.containers_restart_failed()
- },
+const containerActionConfigs: Record<Exclude<ContainerActionKind, 'start' | 'stop' | 'restart'>, ContainerActionConfig> = {
redeploy: {
status: 'redeploying',
run: (id) => containerService.redeployContainer(id),
@@ -86,6 +54,18 @@ export function createContainerActions({
};
async function performContainerAction(action: ContainerActionKind, id: string) {
+ if (action === 'start' || action === 'stop' || action === 'restart') {
+ await runContainerLifecycleAction({
+ action,
+ containerId: id,
+ setStatus: (status) => {
+ actionStatus[id] = status;
+ },
+ onRefresh: reloadContainers
+ });
+ return;
+ }
+
const config = containerActionConfigs[action];
actionStatus[id] = config.status;
@@ -109,80 +89,27 @@ export function createContainerActions({
}
async function handleRemoveContainer(id: string, name: string) {
- openConfirmDialog({
- title: m.containers_remove_confirm_title(),
- message: m.containers_remove_confirm_message({ resource: name }),
- checkboxes: [
- {
- id: 'force',
- label: m.containers_remove_force_label(),
- initialState: false
- },
- {
- id: 'volumes',
- label: m.containers_remove_volumes_label(),
- initialState: false
- }
- ],
- confirm: {
- label: m.common_remove(),
- destructive: true,
- action: async (checkboxStates) => {
- const force = !!checkboxStates['force'];
- const volumes = !!checkboxStates['volumes'];
- actionStatus[id] = 'removing';
- handleApiResultWithCallbacks({
- result: await tryCatch(containerService.deleteContainer(id, { force, volumes })),
- message: m.containers_remove_failed(),
- setLoadingState: (value) => {
- actionStatus[id] = value ? 'removing' : '';
- },
- async onSuccess(data) {
- toast.success(m.containers_remove_success(), activityToastOptions(extractActivityId(data)));
- await reloadContainers();
- }
- });
- }
- }
+ confirmAndRemoveContainer({
+ containerId: id,
+ containerName: name,
+ setStatus: (status) => {
+ actionStatus[id] = status;
+ },
+ onRefresh: reloadContainers
});
}
async function handleUpdateContainer(container: ContainerSummaryDto) {
const containerName = getContainerDisplayName(container);
- openConfirmDialog({
- title: m.containers_update_confirm_title(),
- message: m.containers_update_confirm_message({ name: containerName }),
- confirm: {
- label: m.containers_update_container(),
- destructive: false,
- action: async () => {
- actionStatus[container.id] = 'updating';
- try {
- const result = await containerService.updateContainer(container.id);
- const toastOptions = activityToastOptions(extractActivityId(result));
-
- if (result.failed > 0) {
- const failedItem = result.items?.find((item: { status?: string; error?: string }) => item.status === 'failed');
- toast.error(
- m.containers_update_failed({ name: containerName }) + (failedItem?.error ? `: ${failedItem.error}` : ''),
- toastOptions
- );
- } else if (result.updated > 0) {
- toast.success(m.containers_update_success({ name: containerName }), toastOptions);
- } else {
- toast.info(m.image_update_up_to_date_title(), toastOptions);
- }
-
- await reloadContainers();
- } catch (error) {
- console.error('Container update failed:', error);
- toast.error(m.containers_update_failed({ name: containerName }));
- } finally {
- actionStatus[container.id] = '';
- }
- }
- }
+ confirmAndUpdateContainer({
+ containerId: container.id,
+ containerName,
+ useActivityToast: true,
+ setLoading: (loading) => {
+ actionStatus[container.id] = loading ? 'updating' : '';
+ },
+ onRefresh: reloadContainers
});
}
diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelte
index 5abd82330..b086c732b 100644
--- a/frontend/src/routes/(app)/containers/container-table.svelte
+++ b/frontend/src/routes/(app)/containers/container-table.svelte
@@ -29,6 +29,7 @@
import { hasPermission } from '$lib/utils/auth';
import IconImage from '$lib/components/icon-image.svelte';
import { getArcaneIconUrlFromLabels, getContainerIpAddresses } from '$lib/utils/docker';
+ import { hasAnyLoadingState } from '$lib/utils/bulk-actions';
import { createContainerActions } from './container-table.actions';
import {
getActionStatusMessage,
@@ -143,9 +144,7 @@
isBulkLoading
});
- const isAnyLoading = $derived(
- Object.values(actionStatus).some((status) => status !== '') || Object.values(isBulkLoading).some((loading) => loading)
- );
+ const isAnyLoading = $derived(hasAnyLoadingState(actionStatus, isBulkLoading));
let mobileFieldVisibility = $state<Record<string, boolean>>({});
let customSettings = $state<Record<string, unknown>>({});
diff --git a/frontend/src/routes/(app)/customize/+page.svelte b/frontend/src/routes/(app)/customize/+page.svelte
index 5c8aa0893..e8e69b2f1 100644
--- a/frontend/src/routes/(app)/customize/+page.svelte
+++ b/frontend/src/routes/(app)/customize/+page.svelte
@@ -8,10 +8,12 @@
import { customizeSearchService } from '$lib/services/customize-search';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { CustomizeCategory } from '$lib/types/shared';
- import { debounced } from '$lib/utils/ws';
import { canReachAccessSurfaceUrl } from '$lib/utils/access-policy';
import * as InputGroup from '$lib/components/ui/input-group/index.js';
import { getCustomizeSubpageUrlsInNavOrder } from '$lib/config/navigation-config';
+ import { useCategorySearch } from '$lib/hooks/use-category-search.svelte';
+ import { getCategoryIcon, orderCategoriesByNav } from '$lib/utils/category-page';
+ import { Spinner } from '$lib/components/ui/spinner/index.js';
import {
SearchIcon,
TemplateIcon,
@@ -20,19 +22,20 @@
RegistryIcon,
VariableIcon,
CustomizeIcon,
- GitBranchIcon
+ GitBranchIcon,
+ CloseIcon
} from '$lib/icons';
import HeaderCard from '$lib/components/header-card.svelte';
let { data }: PageProps = $props();
- let searchQuery = $state('');
- let showSearchResults = $state(false);
- let searchResults = $state<CustomizeCategory[]>([]);
- let isSearching = $state(false);
let customizeCategories = $state<CustomizeCategory[]>([]);
- let currentSearchRequest = $state(0);
const user = $derived(data.user);
const permissionsManifest = $derived(data.permissionsManifest);
+ const categorySearch = useCategorySearch<CustomizeCategory>({
+ search: (query) => customizeSearchService.search(query),
+ filter: isAccessibleCategory,
+ onError: (error) => console.error('Search failed:', error)
+ });
const iconMap: Record<string, any> = {
'file-text': FileTextIcon,
@@ -49,74 +52,21 @@
onMount(async () => {
try {
- customizeCategories = orderCategoriesByNav((await customizeSearchService.getCategories()).filter(isAccessibleCategory));
+ customizeCategories = orderCategoriesByNav(
+ (await customizeSearchService.getCategories()).filter(isAccessibleCategory),
+ getCustomizeSubpageUrlsInNavOrder()
+ );
} catch (error) {
console.error('Failed to load categories:', error);
}
});
- function orderCategoriesByNav(categories: CustomizeCategory[]) {
- const navUrls = getCustomizeSubpageUrlsInNavOrder();
- const categoriesByUrl = new Map(categories.map((category) => [category.url, category]));
- const orderedCategories = navUrls
- .map((url) => categoriesByUrl.get(url))
- .filter((category): category is CustomizeCategory => Boolean(category));
- const unmatchedCategories = categories
- .filter((category) => !navUrls.includes(category.url))
- .sort((a, b) => a.title.localeCompare(b.title));
-
- return [...orderedCategories, ...unmatchedCategories];
- }
-
- async function performSearch(query: string) {
- const trimmedQuery = query.trim();
-
- if (!trimmedQuery) {
- searchResults = [];
- showSearchResults = false;
- isSearching = false;
- currentSearchRequest++;
- return;
- }
-
- currentSearchRequest++;
- const requestId = currentSearchRequest;
- isSearching = true;
- showSearchResults = true;
-
- try {
- const response = await customizeSearchService.search(trimmedQuery);
- if (requestId === currentSearchRequest) {
- searchResults = (response.results || []).filter(isAccessibleCategory);
- isSearching = false;
- }
- } catch (error) {
- console.error('Search failed:', error);
- if (requestId === currentSearchRequest) {
- searchResults = [];
- isSearching = false;
- }
- }
- }
-
- const debouncedSearch = debounced((query: string) => {
- void performSearch(query);
- }, 300);
-
function navigateToCategory(categoryUrl: string) {
goto(categoryUrl);
}
- function clearSearch() {
- searchQuery = '';
- showSearchResults = false;
- isSearching = false;
- searchResults = [];
- currentSearchRequest++;
- }
-
function getIconComponent(iconName: string) {
- return iconMap[iconName] || CustomizeIcon;
+ return getCategoryIcon(iconMap, iconName, CustomizeIcon);
}
</script>
@@ -143,20 +93,29 @@
<InputGroup.Root>
<InputGroup.Input
placeholder={m.customize_search_placeholder()}
- value={searchQuery}
+ value={categorySearch.searchQuery}
oninput={(e) => {
- searchQuery = e.currentTarget.value;
- debouncedSearch(e.currentTarget.value);
+ categorySearch.searchQuery = e.currentTarget.value;
+ categorySearch.debouncedSearch(e.currentTarget.value);
}}
onkeydown={(e) => {
if (e.key === 'Enter') {
- performSearch((e.currentTarget as HTMLInputElement).value);
+ categorySearch.performSearch((e.currentTarget as HTMLInputElement).value);
}
}}
/>
<InputGroup.Addon>
- {#if showSearchResults}
- <ArcaneButton action="base" tone="ghost" size="icon" onclick={clearSearch} class="size-6 p-0">×</ArcaneButton>
+ {#if categorySearch.showSearchResults}
+ <ArcaneButton
+ action="base"
+ tone="ghost"
+ size="sm"
+ onclick={categorySearch.clearSearch}
+ class="h-6 w-6 p-0"
+ icon={CloseIcon}
+ showLabel={false}
+ customLabel={m.customize_clear_search()}
+ />
{:else}
<SearchIcon class="size-4" />
{/if}
@@ -165,7 +124,7 @@
</div>
</HeaderCard>
- {#if !showSearchResults}
+ {#if !categorySearch.showSearchResults}
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-6 xl:grid-cols-3">
{#each customizeCategories as category (category.id)}
{@const Icon = getIconComponent(category.icon)}
@@ -193,19 +152,17 @@
<div class="space-y-6 sm:space-y-8">
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<h2 class="text-base font-semibold sm:text-lg">
- {m.customize_search_results({ query: searchQuery })} ({searchResults.length}
- {searchResults.length === 1 ? m.customize_result() : m.customize_results()})
+ {m.customize_search_results({ query: categorySearch.searchQuery })} ({categorySearch.searchResults.length}
+ {categorySearch.searchResults.length === 1 ? m.customize_result() : m.customize_results()})
</h2>
</div>
- {#if isSearching}
+ {#if categorySearch.isSearching}
<div class="py-8 text-center sm:py-12">
- <div
- class="border-primary mx-auto mb-3 size-8 animate-spin rounded-full border-4 border-t-transparent sm:mb-4 sm:size-12"
- ></div>
- <p class="text-muted-foreground text-sm sm:text-base">Searching...</p>
+ <Spinner class="text-primary mx-auto mb-3 size-8 sm:mb-4 sm:size-12" />
+ <p class="text-muted-foreground text-sm sm:text-base">{m.customize_searching()}</p>
</div>
- {:else if searchResults.length === 0}
+ {:else if categorySearch.searchResults.length === 0}
<div class="py-8 text-center sm:py-12">
<SearchIcon class="text-muted-foreground mx-auto mb-3 size-8 sm:mb-4 sm:size-12" />
<h3 class="mb-2 text-base font-medium sm:text-lg">{m.customize_no_options()}</h3>
@@ -213,7 +170,7 @@
</div>
{:else}
<div class="space-y-4 sm:space-y-6">
- {#each searchResults as result (result.id)}
+ {#each categorySearch.searchResults as result (result.id)}
{@const Icon = getIconComponent(result.icon)}
<div class="bg-background/40 rounded-lg border shadow-sm">
<div class="border-b p-4 sm:p-6">
diff --git a/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte b/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte
index 3dc2e936d..34f621ac8 100644
--- a/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte
+++ b/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte
@@ -3,7 +3,6 @@
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
- import { openConfirmDialog } from '$lib/components/confirm-dialog';
import { toast } from 'svelte-sonner';
import { handleApiResultWithCallbacks } from '$lib/utils/api';
import { tryCatch } from '$lib/utils/api';
@@ -25,6 +24,7 @@
} from '$lib/icons';
import { hasPermission } from '$lib/utils/auth';
import IfPermitted from '$lib/components/if-permitted.svelte';
+ import { bulkConfirmAndRun, confirmAndRun } from '$lib/utils/bulk-actions';
type FieldVisibility = Record<string, boolean>;
@@ -62,67 +62,46 @@
let mobileFieldVisibility = $state<Record<string, boolean>>({});
async function handleDeleteSelected(ids: string[]) {
- if (!ids?.length) return;
-
- openConfirmDialog({
+ bulkConfirmAndRun({
+ ids,
title: m.common_remove_title({ resource: `${ids.length} ${m.resource_repository()}(s)` }),
message: m.common_remove_message({ resource: `${ids.length} ${m.resource_repository()}(s)` }),
- confirm: {
- label: m.common_remove(),
- destructive: true,
- action: async () => {
- isLoading.removing = true;
-
- let successCount = 0;
- let failureCount = 0;
- for (const id of ids) {
- const repo = repositories.data.find((r) => r.id === id);
- const result = await tryCatch(gitRepositoryService.deleteRepository(id));
- if (result.error) {
- failureCount++;
- toast.error(m.common_delete_failed({ resource: repo?.name ?? m.common_unknown() }));
- } else {
- successCount++;
- }
- }
-
- if (successCount > 0) {
- toast.success(m.common_delete_success({ resource: `${successCount} ${m.resource_repository()}(s)` }));
- repositories = await gitRepositoryService.getRepositories(requestOptions);
- }
- if (failureCount > 0) toast.error(m.common_delete_failed({ resource: `${failureCount} items` }));
-
- selectedIds = [];
- isLoading.removing = false;
+ confirmLabel: m.common_remove(),
+ destructive: true,
+ run: (id) => gitRepositoryService.deleteRepository(id),
+ messages: {
+ success: (count) => m.common_delete_success({ resource: `${count} ${m.resource_repository()}(s)` }),
+ partial: (_success, _total, failed) => m.common_delete_failed({ resource: `${failed} items` }),
+ failure: () => m.common_delete_failed({ resource: `${ids.length} items` })
+ },
+ setLoading: (loading) => (isLoading.removing = loading),
+ onItemFailure: (id) => {
+ const repo = repositories.data.find((item) => item.id === id);
+ toast.error(m.common_delete_failed({ resource: repo?.name ?? m.common_unknown() }));
+ },
+ onComplete: async (result) => {
+ if (result.success > 0) {
+ repositories = await gitRepositoryService.getRepositories(requestOptions);
}
- }
+ },
+ clearSelection: () => (selectedIds = []),
+ sequential: true
});
}
async function handleDeleteOne(id: string, name: string) {
const safeName = name ?? m.common_unknown();
- openConfirmDialog({
+ confirmAndRun({
title: m.git_repository_remove_confirm(),
message: m.git_repository_remove_message(),
- confirm: {
- label: m.common_remove(),
- destructive: true,
- action: async () => {
- isLoading.removing = true;
-
- const result = await tryCatch(gitRepositoryService.deleteRepository(id));
- handleApiResultWithCallbacks({
- result,
- message: m.common_delete_failed({ resource: safeName }),
- setLoadingState: () => {},
- onSuccess: async () => {
- toast.success(m.common_delete_success({ resource: `${m.resource_repository()} "${safeName}"` }));
- repositories = await gitRepositoryService.getRepositories(requestOptions);
- }
- });
-
- isLoading.removing = false;
- }
+ confirmLabel: m.common_remove(),
+ destructive: true,
+ setLoading: (loading) => (isLoading.removing = loading),
+ run: () => gitRepositoryService.deleteRepository(id),
+ failureMessage: m.common_delete_failed({ resource: safeName }),
+ onSuccess: async () => {
+ toast.success(m.common_delete_success({ resource: `${m.resource_repository()} "${safeName}"` }));
+ repositories = await gitRepositoryService.getRepositories(requestOptions);
}
});
}
diff --git a/frontend/src/routes/(app)/customize/templates/[id]/+page.svelte b/frontend/src/routes/(app)/customize/templates/[id]/+page.svelte
index d44059e49..234753e09 100644
--- a/frontend/src/routes/(app)/customize/templates/[id]/+page.svelte
+++ b/frontend/src/routes/(app)/customize/templates/[id]/+page.svelte
@@ -12,10 +12,15 @@
import { untrack } from 'svelte';
import { toast } from 'svelte-sonner';
import { createForm } from '$lib/utils/settings';
- import { tryCatch } from '$lib/utils/api';
- import { handleApiResultWithCallbacks } from '$lib/utils/api';
import { ComposeEditorSplit } from '$lib/components/compose';
- import { z } from 'zod/v4';
+ import { globalVariablesToMap } from '$lib/utils/template-load';
+ import {
+ createNamedTemplateSchema,
+ getTemplateEditorValidationState,
+ hasTemplateEditorErrors,
+ resetTemplateEditorFields,
+ runTemplateEditorSave
+ } from '$lib/utils/template-editor';
import {
ArrowLeftIcon,
ProjectsIcon,
@@ -36,25 +41,22 @@
let envVars = $derived(data.templateData.envVariables);
// Edit state (custom templates only)
- let saving = $state(false);
- let isDeleting = $state(false);
- let isDownloading = $state(false);
- let composeHasErrors = $state(false);
- let envHasErrors = $state(false);
- let composeValidationReady = $state(false);
- let envValidationReady = $state(false);
+ let status = $state({
+ saving: false,
+ isDeleting: false,
+ isDownloading: false
+ });
+ let validation = $state({
+ composeHasErrors: false,
+ envHasErrors: false,
+ composeValidationReady: false,
+ envValidationReady: false
+ });
- const globalVariableMap = $derived.by(() =>
- Object.fromEntries((data.globalVariables ?? []).map((item) => [item.key, item.value]))
- );
+ const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));
// Form schema for custom template editing
- const formSchema = z.object({
- name: z.string().min(1, m.templates_template_name_required()),
- description: z.string().optional().default(''),
- composeContent: z.string().min(1, m.templates_content_required()),
- envContent: z.string().optional().default('')
- });
+ const formSchema = createNamedTemplateSchema();
let originalName = $state(untrack(() => template.name));
let originalDescription = $state(untrack(() => template.description ?? ''));
@@ -76,32 +78,31 @@
$inputs.composeContent.value !== originalCompose ||
$inputs.envContent.value !== originalEnv
);
+ const validationState = $derived(
+ getTemplateEditorValidationState(
+ validation.composeValidationReady,
+ validation.envValidationReady,
+ validation.composeHasErrors,
+ validation.envHasErrors
+ )
+ );
- const canSave = $derived(hasChanges && composeValidationReady && envValidationReady && !composeHasErrors && !envHasErrors);
+ const canSave = $derived(hasChanges && !hasTemplateEditorErrors(validationState));
async function handleSave() {
- if (!composeValidationReady || !envValidationReady || composeHasErrors || envHasErrors) {
- toast.error(m.templates_validation_error());
- return;
- }
- const validated = form.validate();
- if (!validated) {
- toast.error(m.templates_validation_error());
- return;
- }
-
- handleApiResultWithCallbacks({
- result: await tryCatch(
+ await runTemplateEditorSave({
+ validationState,
+ validate: form.validate,
+ save: (validated) =>
templateService.updateTemplate(template.id, {
name: validated.name,
description: validated.description,
content: validated.composeContent,
envContent: validated.envContent
- })
- ),
- message: m.templates_save_template_failed(),
- setLoadingState: (value) => (saving = value),
- onSuccess: async () => {
+ }),
+ failureMessage: m.templates_save_template_failed(),
+ setLoading: (value) => (status.saving = value),
+ onSuccess: async (validated) => {
toast.success(m.templates_save_template_success({ name: validated.name }));
originalName = validated.name;
originalDescription = validated.description ?? '';
@@ -113,24 +114,37 @@
}
function handleReset() {
- $inputs.name.value = originalName;
- $inputs.description.value = originalDescription;
- $inputs.composeContent.value = originalCompose;
- $inputs.envContent.value = originalEnv;
- toast.info(m.templates_reset_success());
+ resetTemplateEditorFields([
+ {
+ set: (value) => ($inputs.name.value = value),
+ value: originalName
+ },
+ {
+ set: (value) => ($inputs.description.value = value),
+ value: originalDescription
+ },
+ {
+ set: (value) => ($inputs.composeContent.value = value),
+ value: originalCompose
+ },
+ {
+ set: (value) => ($inputs.envContent.value = value),
+ value: originalEnv
+ }
+ ]);
}
// Read-only view helpers (remote templates)
- const localVersionOfRemote = $derived(() => {
+ const localVersionOfRemote = $derived.by(() => {
if (!template.isRemote || !template.metadata?.remoteUrl) return null;
return data.allTemplates.find((t) => !t.isRemote && t.metadata?.remoteUrl === template.metadata?.remoteUrl);
});
- const canDownload = $derived(template.isRemote && !localVersionOfRemote());
+ const canDownload = $derived(template.isRemote && !localVersionOfRemote);
async function handleDownload() {
- if (isDownloading || !canDownload) return;
- isDownloading = true;
+ if (status.isDownloading || !canDownload) return;
+ status.isDownloading = true;
try {
const downloadedTemplate = await templateService.download(template.id);
toast.success(m.templates_downloaded_success({ name: template.name }));
@@ -143,12 +157,12 @@
console.error('Error downloading template:', error);
toast.error(error instanceof Error ? error.message : m.templates_download_failed());
} finally {
- isDownloading = false;
+ status.isDownloading = false;
}
}
async function handleDelete() {
- if (isDeleting) return;
+ if (status.isDeleting) return;
openConfirmDialog({
title: m.common_delete_title({ resource: m.resource_template() }),
message: m.common_delete_confirm({ resource: `${m.resource_template()} "${template.name}"` }),
@@ -156,7 +170,7 @@
label: m.templates_delete_template(),
destructive: true,
action: async () => {
- isDeleting = true;
+ status.isDeleting = true;
try {
await templateService.deleteTemplate(template.id);
toast.success(m.common_delete_success({ resource: `${m.resource_template()} "${template.name}"` }));
@@ -168,7 +182,7 @@
? error.message
: m.common_delete_failed({ resource: `${m.resource_template()} "${template.name}"` })
);
- isDeleting = false;
+ status.isDeleting = false;
}
}
}
@@ -192,13 +206,13 @@
input={$inputs.name}
label={m.templates_template_name_label()}
placeholder={m.templates_template_name_placeholder()}
- disabled={saving}
+ disabled={status.saving}
/>
<FormInput
input={$inputs.description}
label={m.templates_template_description_label()}
placeholder={m.templates_template_description_placeholder()}
- disabled={saving}
+ disabled={status.saving}
/>
</div>
<div class="flex flex-col gap-2 sm:flex-row sm:items-start">
@@ -208,21 +222,21 @@
customLabel={m.compose_create_project()}
class="w-full gap-2 sm:w-auto"
/>
- <ArcaneButton action="cancel" onclick={handleReset} disabled={!hasChanges || saving}>
+ <ArcaneButton action="cancel" onclick={handleReset} disabled={!hasChanges || status.saving}>
{m.common_reset()}
</ArcaneButton>
<ArcaneButton
action="save"
onclick={handleSave}
disabled={!canSave}
- loading={saving}
+ loading={status.saving}
loadingLabel={m.common_action_saving()}
/>
<ArcaneButton
action="remove"
onclick={handleDelete}
- disabled={isDeleting}
- loading={isDeleting}
+ disabled={status.isDeleting}
+ loading={status.isDeleting}
loadingLabel={m.common_action_deleting()}
customLabel={m.templates_delete_template()}
class="w-full gap-2 sm:w-auto"
@@ -260,7 +274,7 @@
{m.templates_remote()}
</Badge>
{#if template.metadata?.tags && template.metadata.tags.length > 0}
- {#each template.metadata.tags as tag}
+ {#each template.metadata.tags as tag (tag)}
<Badge variant="outline">{tag}</Badge>
{/each}
{/if}
@@ -277,18 +291,18 @@
<ArcaneButton
action="base"
onclick={handleDownload}
- disabled={isDownloading}
- loading={isDownloading}
+ disabled={status.isDownloading}
+ loading={status.isDownloading}
loadingLabel={m.common_action_downloading()}
class="w-full gap-2 sm:w-auto"
>
<DownloadIcon class="size-4" />
{m.templates_download()}
</ArcaneButton>
- {:else if template.isRemote && localVersionOfRemote()}
+ {:else if template.isRemote && localVersionOfRemote}
<ArcaneButton
action="base"
- onclick={() => goto(`/customize/templates/${localVersionOfRemote()?.id}`)}
+ onclick={() => goto(`/customize/templates/${localVersionOfRemote?.id}`)}
class="w-full gap-2 sm:w-auto"
>
<ProjectsIcon class="size-4" />
@@ -321,10 +335,10 @@
<CodeEditor
bind:value={$inputs.composeContent.value}
language="yaml"
- readOnly={saving}
+ readOnly={status.saving}
fontSize="13px"
- bind:hasErrors={composeHasErrors}
- bind:validationReady={composeValidationReady}
+ bind:hasErrors={validation.composeHasErrors}
+ bind:validationReady={validation.composeValidationReady}
fileId="templates:custom:{template.id}:compose"
originalValue={originalCompose}
enableDiff={true}
@@ -359,10 +373,10 @@
<CodeEditor
bind:value={$inputs.envContent.value}
language="env"
- readOnly={saving}
+ readOnly={status.saving}
fontSize="13px"
- bind:hasErrors={envHasErrors}
- bind:validationReady={envValidationReady}
+ bind:hasErrors={validation.envHasErrors}
+ bind:validationReady={validation.envValidationReady}
fileId="templates:custom:{template.id}:env"
originalValue={originalEnv}
enableDiff={true}
@@ -449,7 +463,7 @@
</div>
</Card.Header>
<Card.Content class="grid grid-cols-1 gap-2 p-4">
- {#each services as service}
+ {#each services as service (service)}
<Card.Root variant="subtle" class="min-w-0">
<Card.Content class="flex min-w-0 items-center gap-3 p-3">
<div class="flex size-8 shrink-0 items-center justify-center rounded-lg bg-blue-500/10">
@@ -474,7 +488,7 @@
</div>
</Card.Header>
<Card.Content class="grid grid-cols-1 gap-2 p-4">
- {#each envVars as envVar}
+ {#each envVars as envVar (envVar.key)}
<Card.Root variant="subtle" class="min-w-0">
<Card.Content class="flex min-w-0 flex-col gap-2 p-3">
<div class="text-muted-foreground text-xs font-semibold tracking-wide break-words uppercase select-all">
diff --git a/frontend/src/routes/(app)/customize/templates/create/+page.svelte b/frontend/src/routes/(app)/customize/templates/create/+page.svelte
index d0cae2802..5ae8d4fc0 100644
--- a/frontend/src/routes/(app)/customize/templates/create/+page.svelte
+++ b/frontend/src/routes/(app)/customize/templates/create/+page.svelte
@@ -9,10 +9,16 @@
import { createForm, preventDefault } from '$lib/utils/settings';
import { tryCatch } from '$lib/utils/api';
import { toast } from 'svelte-sonner';
- import { z } from 'zod/v4';
import CodePanel from '../../../projects/components/CodePanel.svelte';
import EditableName from '../../../projects/components/EditableName.svelte';
import { ComposeEditorSplit } from '$lib/components/compose';
+ import { globalVariablesToMap } from '$lib/utils/template-load';
+ import {
+ createNamedTemplateSchema,
+ getTemplateEditorValidationState,
+ hasTemplateEditorErrors,
+ validateTemplateEditorForm
+ } from '$lib/utils/template-editor';
let { data } = $props();
@@ -23,16 +29,9 @@
let envValidationReady = $state(false);
let nameInputRef = $state<HTMLInputElement | null>(null);
- const globalVariableMap = $derived.by(() =>
- Object.fromEntries((data.globalVariables ?? []).map((item) => [item.key, item.value]))
- );
+ const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));
- const formSchema = z.object({
- name: z.string().min(1, m.templates_template_name_required()),
- description: z.string().optional().default(''),
- composeContent: z.string().min(1, m.templates_content_required()),
- envContent: z.string().optional().default('')
- });
+ const formSchema = createNamedTemplateSchema();
const initialValues = {
name: '',
@@ -43,20 +42,19 @@
const { inputs, ...form } = createForm<typeof formSchema>(formSchema, initialValues);
- const hasEditorErrors = $derived(!composeValidationReady || !envValidationReady || composeHasErrors || envHasErrors);
+ const hasEditorErrors = $derived(
+ hasTemplateEditorErrors(
+ getTemplateEditorValidationState(composeValidationReady, envValidationReady, composeHasErrors, envHasErrors)
+ )
+ );
const canCreate = $derived(!!$inputs.name.value && !!$inputs.composeContent.value && !hasEditorErrors && !saving);
async function handleCreate() {
- if (hasEditorErrors) {
- toast.error(m.templates_validation_error());
- return;
- }
-
- const validated = form.validate();
- if (!validated) {
- toast.error(m.templates_validation_error());
- return;
- }
+ const validated = validateTemplateEditorForm(
+ getTemplateEditorValidationState(composeValidationReady, envValidationReady, composeHasErrors, envHasErrors),
+ form.validate
+ );
+ if (!validated) return;
handleApiResultWithCallbacks({
result: await tryCatch(
diff --git a/frontend/src/routes/(app)/customize/templates/default/+page.svelte b/frontend/src/routes/(app)/customize/templates/default/+page.svelte
index 8c4f06180..43449f0a8 100644
--- a/frontend/src/routes/(app)/customize/templates/default/+page.svelte
+++ b/frontend/src/routes/(app)/customize/templates/default/+page.svelte
@@ -4,39 +4,43 @@
import { toast } from 'svelte-sonner';
import CodeEditor from '$lib/components/code-editor/editor.svelte';
import { createForm } from '$lib/utils/settings';
- import { tryCatch } from '$lib/utils/api';
- import { handleApiResultWithCallbacks } from '$lib/utils/api';
import { m } from '$lib/paraglide/messages';
import { templateService } from '$lib/services/template-service';
- import { z } from 'zod/v4';
import { goto } from '$app/navigation';
import TemplateSelectionDialog from '$lib/components/dialogs/template-selection-dialog.svelte';
import { ComposeEditorSplit } from '$lib/components/compose';
import { untrack } from 'svelte';
import type { Template } from '$lib/types/swarm';
+ import { globalVariablesToMap } from '$lib/utils/template-load';
import { ArrowLeftIcon, CodeIcon, VariableIcon } from '$lib/icons';
+ import {
+ createTemplateContentSchema,
+ getTemplateEditorValidationState,
+ hasTemplateEditorErrors,
+ resetTemplateEditorFields,
+ runTemplateEditorSave
+ } from '$lib/utils/template-editor';
let { data } = $props();
- let saving = $state(false);
- let showTemplateDialog = $state(false);
- let isLoadingTemplate = $state(false);
+ let ui = $state({
+ saving: false,
+ showTemplateDialog: false,
+ isLoadingTemplate: false
+ });
let originalComposeContent = $state(untrack(() => data.composeTemplate));
let originalEnvContent = $state(untrack(() => data.envTemplate));
- let composeHasErrors = $state(false);
- let envHasErrors = $state(false);
- let composeValidationReady = $state(false);
- let envValidationReady = $state(false);
+ let validation = $state({
+ composeHasErrors: false,
+ envHasErrors: false,
+ composeValidationReady: false,
+ envValidationReady: false
+ });
- const globalVariableMap = $derived.by(() =>
- Object.fromEntries((data.globalVariables ?? []).map((item) => [item.key, item.value]))
- );
+ const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));
- const formSchema = z.object({
- composeContent: z.string().min(1, m.compose_compose_content_required()),
- envContent: z.string().optional().default('')
- });
+ const formSchema = createTemplateContentSchema();
let formData = $derived({
composeContent: originalComposeContent,
@@ -48,27 +52,24 @@
const hasChanges = $derived(
$inputs.composeContent.value !== originalComposeContent || $inputs.envContent.value !== originalEnvContent
);
+ const validationState = $derived(
+ getTemplateEditorValidationState(
+ validation.composeValidationReady,
+ validation.envValidationReady,
+ validation.composeHasErrors,
+ validation.envHasErrors
+ )
+ );
- const canSave = $derived(hasChanges && composeValidationReady && envValidationReady && !composeHasErrors && !envHasErrors);
+ const canSave = $derived(hasChanges && !hasTemplateEditorErrors(validationState));
async function handleSave() {
- if (!composeValidationReady || !envValidationReady || composeHasErrors || envHasErrors) {
- toast.error(m.templates_validation_error());
- return;
- }
-
- const validated = form.validate();
- if (!validated) {
- toast.error(m.templates_validation_error());
- return;
- }
-
- const { composeContent, envContent } = validated;
-
- handleApiResultWithCallbacks({
- result: await tryCatch(templateService.saveDefaultTemplates(composeContent, envContent)),
- message: m.templates_save_failed(),
- setLoadingState: (value) => (saving = value),
+ await runTemplateEditorSave({
+ validationState,
+ validate: form.validate,
+ save: ({ composeContent, envContent }) => templateService.saveDefaultTemplates(composeContent, envContent),
+ failureMessage: m.templates_save_failed(),
+ setLoading: (value) => (ui.saving = value),
onSuccess: async () => {
toast.success(m.templates_save_success());
originalComposeContent = $inputs.composeContent.value;
@@ -78,14 +79,21 @@
}
async function handleReset() {
- $inputs.composeContent.value = originalComposeContent;
- $inputs.envContent.value = originalEnvContent;
- toast.info(m.templates_reset_success());
+ resetTemplateEditorFields([
+ {
+ set: (value) => ($inputs.composeContent.value = value),
+ value: originalComposeContent
+ },
+ {
+ set: (value) => ($inputs.envContent.value = value),
+ value: originalEnvContent
+ }
+ ]);
}
async function handleTemplateSelect(template: Template) {
- showTemplateDialog = false;
- isLoadingTemplate = true;
+ ui.showTemplateDialog = false;
+ ui.isLoadingTemplate = true;
try {
const templateContent = await templateService.getTemplateContent(template.id);
@@ -96,7 +104,7 @@
console.error('Error loading template:', error);
toast.error(error instanceof Error ? error.message : m.templates_download_failed());
} finally {
- isLoadingTemplate = false;
+ ui.isLoadingTemplate = false;
}
}
</script>
@@ -119,19 +127,19 @@
<ArcaneButton
action="base"
tone="outline"
- onclick={() => (showTemplateDialog = true)}
- disabled={saving || isLoadingTemplate}
+ onclick={() => (ui.showTemplateDialog = true)}
+ disabled={ui.saving || ui.isLoadingTemplate}
>
{m.common_use_template()}
</ArcaneButton>
- <ArcaneButton action="cancel" onclick={handleReset} disabled={!hasChanges || saving || isLoadingTemplate}>
+ <ArcaneButton action="cancel" onclick={handleReset} disabled={!hasChanges || ui.saving || ui.isLoadingTemplate}>
{m.common_reset()}
</ArcaneButton>
<ArcaneButton
action="save"
onclick={handleSave}
- disabled={!canSave || isLoadingTemplate}
- loading={saving}
+ disabled={!canSave || ui.isLoadingTemplate}
+ loading={ui.saving}
loadingLabel={m.common_action_saving()}
/>
</div>
@@ -158,10 +166,10 @@
<CodeEditor
bind:value={$inputs.composeContent.value}
language="yaml"
- readOnly={saving || isLoadingTemplate}
+ readOnly={ui.saving || ui.isLoadingTemplate}
fontSize="13px"
- bind:hasErrors={composeHasErrors}
- bind:validationReady={composeValidationReady}
+ bind:hasErrors={validation.composeHasErrors}
+ bind:validationReady={validation.composeValidationReady}
fileId="templates:defaults:compose"
originalValue={originalComposeContent}
enableDiff={true}
@@ -198,10 +206,10 @@
<CodeEditor
bind:value={$inputs.envContent.value}
language="env"
- readOnly={saving || isLoadingTemplate}
+ readOnly={ui.saving || ui.isLoadingTemplate}
fontSize="13px"
- bind:hasErrors={envHasErrors}
- bind:validationReady={envValidationReady}
+ bind:hasErrors={validation.envHasErrors}
+ bind:validationReady={validation.envValidationReady}
fileId="templates:defaults:env"
originalValue={originalEnvContent}
enableDiff={true}
@@ -225,4 +233,4 @@
</ComposeEditorSplit>
</div>
-<TemplateSelectionDialog bind:open={showTemplateDialog} templates={data.templates || []} onSelect={handleTemplateSelect} />
+<TemplateSelectionDialog bind:open={ui.showTemplateDialog} templates={data.templates || []} onSelect={handleTemplateSelect} />
diff --git a/frontend/src/routes/(app)/customize/templates/default/+page.ts b/frontend/src/routes/(app)/customize/templates/default/+page.ts
index 3d710e6f1..c2de4338c 100644
--- a/frontend/src/routes/(app)/customize/templates/default/+page.ts
+++ b/frontend/src/routes/(app)/customize/templates/default/+page.ts
@@ -1,43 +1,12 @@
-import { templateService } from '$lib/services/template-service';
-import { queryKeys } from '$lib/query/query-keys';
import type { Template } from '$lib/types/swarm';
import type { Variable } from '$lib/types/shared';
+import { loadTemplateAuthoringData } from '$lib/utils/template-load';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({
parent
}): Promise<{ composeTemplate: string; envTemplate: string; templates: Template[]; globalVariables: Variable[] }> => {
- const { queryClient } = await parent();
-
- const [defaultTemplates, templates, globalVariables] = await Promise.all([
- queryClient
- .fetchQuery({
- queryKey: queryKeys.templates.defaults(),
- queryFn: () => templateService.getDefaultTemplates()
- })
- .catch((err) => {
- console.warn('Failed to load default templates:', err);
- return { composeTemplate: '', envTemplate: '' };
- }),
- queryClient
- .fetchQuery({
- queryKey: queryKeys.templates.allTemplates(),
- queryFn: () => templateService.getAllTemplates()
- })
- .catch((err) => {
- console.warn('Failed to load templates:', err);
- return [];
- }),
- queryClient
- .fetchQuery({
- queryKey: queryKeys.templates.globalVariables(),
- queryFn: () => templateService.getGlobalVariables()
- })
- .catch((err) => {
- console.warn('Failed to load global variables:', err);
- return [];
- })
- ]);
+ const { defaultTemplates, templates, globalVariables } = await loadTemplateAuthoringData(parent);
return {
composeTemplate: defaultTemplates.composeTemplate,
diff --git a/frontend/src/routes/(app)/dashboard/dash-container-table.svelte b/frontend/src/routes/(app)/dashboard/dash-container-table.svelte
index 714bce126..b7c57b7a7 100644
--- a/frontend/src/routes/(app)/dashboard/dash-container-table.svelte
+++ b/frontend/src/routes/(app)/dashboard/dash-container-table.svelte
@@ -12,8 +12,7 @@
import { m } from '$lib/paraglide/messages';
import { containerService } from '$lib/services/container-service';
import { goto } from '$app/navigation';
- import { untrack } from 'svelte';
- import { IsMobile } from '$lib/hooks';
+ import { useResponsiveTableLimit } from '$lib/hooks/use-responsive-table-limit.svelte';
import { ContainersIcon, ArrowRightIcon } from '$lib/icons';
import IconImage from '$lib/components/icon-image.svelte';
import { getArcaneIconUrlFromLabels } from '$lib/utils/docker';
@@ -26,67 +25,17 @@
isLoading: boolean;
} = $props();
- const isMobile = new IsMobile();
let selectedIds = $state<string[]>([]);
- let displayLimit = $state(containers.pagination?.itemsPerPage ?? 5);
- let lastMeasuredHeight = $state(0);
-
- const MOBILE_ROWS = 4;
- const ROW_HEIGHT = 57;
- const HEADER_HEIGHT = 145;
- const FOOTER_HEIGHT = 48;
- const MIN_ROWS = 3;
- const MAX_ROWS = 50;
-
- let requestOptions = $state<SearchPaginationSortRequest>({
- pagination: { page: 1, limit: 5 },
- sort: { column: 'created', direction: 'desc' }
- });
-
- function shouldReserveFooter(limit: number) {
- const totalItems = containers.pagination?.totalItems ?? 0;
- return totalItems > limit;
- }
-
- function calculateLimitForHeight(height: number) {
- if (isMobile.current) return MOBILE_ROWS;
- if (height <= 0) return 5;
-
- let availableHeight = height - HEADER_HEIGHT;
- const initialRows = Math.floor(Math.max(0, availableHeight) / ROW_HEIGHT);
- const footerLimit = Math.max(MIN_ROWS, Math.min(MAX_ROWS, initialRows));
- if (shouldReserveFooter(footerLimit)) {
- availableHeight -= FOOTER_HEIGHT;
- }
-
- const rows = Math.floor(Math.max(0, availableHeight) / ROW_HEIGHT);
- return Math.max(MIN_ROWS, Math.min(MAX_ROWS, rows));
- }
-
- function updateRequestLimit(limit: number) {
- const currentOptions = untrack(() => requestOptions);
- if (currentOptions.pagination?.limit === limit) return;
-
- requestOptions = {
- ...currentOptions,
- pagination: {
- page: currentOptions.pagination?.page ?? 1,
- limit
- }
- };
- }
-
- $effect(() => {
- const nextLimit = calculateLimitForHeight(lastMeasuredHeight);
- displayLimit = nextLimit;
- updateRequestLimit(nextLimit);
+ const tableLimit = useResponsiveTableLimit({
+ initialLimit: containers.pagination?.itemsPerPage ?? 5,
+ sort: { column: 'created', direction: 'desc' },
+ getTotalItems: () => containers.pagination?.totalItems ?? 0
});
async function refreshContainers(options: SearchPaginationSortRequest) {
- requestOptions = options;
+ tableLimit.requestOptions = options;
const result = await containerService.getContainers(options);
containers = result;
- displayLimit = result.pagination?.itemsPerPage ?? displayLimit;
return result;
}
@@ -150,7 +99,7 @@
/>
{/snippet}
-<div class="flex flex-col lg:h-full lg:min-h-0" bind:clientHeight={lastMeasuredHeight}>
+<div class="flex flex-col lg:h-full lg:min-h-0" bind:clientHeight={tableLimit.measuredHeight}>
<Card.Root class="flex flex-col lg:h-full lg:min-h-0">
<Card.Header icon={ContainersIcon} class="shrink-0">
<div class="flex flex-1 items-center justify-between">
@@ -168,8 +117,8 @@
</Card.Header>
<Card.Content class="px-0 lg:flex lg:min-h-0 lg:flex-1 lg:flex-col">
<ArcaneTable
- items={{ ...containers, data: containers.data.slice(0, displayLimit) }}
- bind:requestOptions
+ items={{ ...containers, data: containers.data.slice(0, tableLimit.displayLimit) }}
+ bind:requestOptions={tableLimit.requestOptions}
bind:selectedIds
onRefresh={refreshContainers}
{columns}
@@ -180,10 +129,10 @@
unstyled
/>
</Card.Content>
- {#if containers.data.length >= displayLimit && containers.pagination.totalItems > displayLimit}
+ {#if tableLimit.shouldShowFooter(containers.data.length)}
<Card.Footer class="border-t px-6 py-3">
<span class="text-muted-foreground text-xs">
- {m.containers_showing_of_total({ shown: displayLimit, total: containers.pagination.totalItems })}
+ {m.containers_showing_of_total({ shown: tableLimit.displayLimit, total: containers.pagination.totalItems })}
</span>
</Card.Footer>
{/if}
diff --git a/frontend/src/routes/(app)/dashboard/dash-image-table.svelte b/frontend/src/routes/(app)/dashboard/dash-image-table.svelte
index ae9e35bc2..93699fc73 100644
--- a/frontend/src/routes/(app)/dashboard/dash-image-table.svelte
+++ b/frontend/src/routes/(app)/dashboard/dash-image-table.svelte
@@ -11,8 +11,7 @@
import { m } from '$lib/paraglide/messages';
import { imageService } from '$lib/services/image-service';
import { goto } from '$app/navigation';
- import { untrack } from 'svelte';
- import { IsMobile } from '$lib/hooks';
+ import { useResponsiveTableLimit } from '$lib/hooks/use-responsive-table-limit.svelte';
import { ImagesIcon, ArrowRightIcon } from '$lib/icons';
let {
@@ -23,68 +22,18 @@
isLoading: boolean;
} = $props();
- const isMobile = new IsMobile();
- let displayLimit = $state(images.pagination?.itemsPerPage ?? 5);
- let lastMeasuredHeight = $state(0);
-
- const MOBILE_ROWS = 4;
- const ROW_HEIGHT = 57;
- const HEADER_HEIGHT = 145;
- const FOOTER_HEIGHT = 48;
- const MIN_ROWS = 3;
- const MAX_ROWS = 50;
-
- let requestOptions = $state<SearchPaginationSortRequest>({
- pagination: { page: 1, limit: 5 },
- sort: { column: 'size', direction: 'desc' }
+ const tableLimit = useResponsiveTableLimit({
+ initialLimit: images.pagination?.itemsPerPage ?? 5,
+ sort: { column: 'size', direction: 'desc' },
+ getTotalItems: () => images.pagination?.totalItems ?? 0
});
let selectedIds = $state<string[]>([]);
- function shouldReserveFooter(limit: number) {
- const totalItems = images.pagination?.totalItems ?? 0;
- return totalItems > limit;
- }
-
- function calculateLimitForHeight(height: number) {
- if (isMobile.current) return MOBILE_ROWS;
- if (height <= 0) return 5;
-
- let availableHeight = height - HEADER_HEIGHT;
- const initialRows = Math.floor(Math.max(0, availableHeight) / ROW_HEIGHT);
- const footerLimit = Math.max(MIN_ROWS, Math.min(MAX_ROWS, initialRows));
- if (shouldReserveFooter(footerLimit)) {
- availableHeight -= FOOTER_HEIGHT;
- }
-
- const rows = Math.floor(Math.max(0, availableHeight) / ROW_HEIGHT);
- return Math.max(MIN_ROWS, Math.min(MAX_ROWS, rows));
- }
-
- function updateRequestLimit(limit: number) {
- const currentOptions = untrack(() => requestOptions);
- if (currentOptions.pagination?.limit === limit) return;
-
- requestOptions = {
- ...currentOptions,
- pagination: {
- page: currentOptions.pagination?.page ?? 1,
- limit
- }
- };
- }
-
- $effect(() => {
- const nextLimit = calculateLimitForHeight(lastMeasuredHeight);
- displayLimit = nextLimit;
- updateRequestLimit(nextLimit);
- });
-
async function refreshImages(options: SearchPaginationSortRequest) {
- requestOptions = options;
+ tableLimit.requestOptions = options;
const result = await imageService.getImages(options);
images = result;
- displayLimit = result.pagination?.itemsPerPage ?? displayLimit;
return result;
}
@@ -158,7 +107,7 @@
/>
{/snippet}
-<div class="flex flex-col lg:h-full lg:min-h-0" bind:clientHeight={lastMeasuredHeight}>
+<div class="flex flex-col lg:h-full lg:min-h-0" bind:clientHeight={tableLimit.measuredHeight}>
<Card.Root class="flex flex-col lg:h-full lg:min-h-0">
<Card.Header icon={ImagesIcon} class="shrink-0">
<div class="flex flex-1 items-center justify-between">
@@ -176,8 +125,8 @@
</Card.Header>
<Card.Content class="px-0 lg:flex lg:min-h-0 lg:flex-1 lg:flex-col">
<ArcaneTable
- items={{ ...images, data: images.data.slice(0, displayLimit) }}
- bind:requestOptions
+ items={{ ...images, data: images.data.slice(0, tableLimit.displayLimit) }}
+ bind:requestOptions={tableLimit.requestOptions}
bind:selectedIds
onRefresh={refreshImages}
{columns}
@@ -188,10 +137,10 @@
unstyled
/>
</Card.Content>
- {#if images.data.length >= displayLimit && images.pagination.totalItems > displayLimit}
+ {#if tableLimit.shouldShowFooter(images.data.length)}
<Card.Footer class="border-t px-6 py-3">
<span class="text-muted-foreground text-xs">
- {m.images_showing_of_total({ shown: displayLimit, total: images.pagination.totalItems })}
+ {m.images_showing_of_total({ shown: tableLimit.displayLimit, total: images.pagination.totalItems })}
</span>
</Card.Footer>
{/if}
diff --git a/frontend/src/routes/(app)/environments/[id]/+page.svelte b/frontend/src/routes/(app)/environments/[id]/+page.svelte
index 2d232ffca..70716b17b 100644
--- a/frontend/src/routes/(app)/environments/[id]/+page.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/+page.svelte
@@ -21,7 +21,7 @@
import { hasPermission } from '$lib/utils/auth';
import { isEnvironmentOnline, resolveEnvironmentStatus } from '$lib/utils/docker';
import MobileFloatingFormActions from '$lib/components/form/mobile-floating-form-actions.svelte';
- import { createSettingsForm } from '$lib/utils/settings';
+ import { createSettingsForm } from '$lib/utils/settings-form';
import DetailsTab from './components/DetailsTab.svelte';
import GeneralTab from './components/GeneralTab.svelte';
import DockerTab from './components/DockerTab.svelte';
diff --git a/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte b/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte
index e51954b9f..b5c87f44b 100644
--- a/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte
@@ -56,14 +56,29 @@
let searchTerm = $state('');
let autoHealSearchTerm = $state('');
- const excludedContainers = $derived.by(() => {
- const savedValue = $formInputs.autoUpdateExcludedContainers?.value || '';
+ function parseExcludedContainerSet(value: string | undefined) {
return new SvelteSet(
- savedValue
+ (value || '')
.split(',')
.map((s: string) => normalizeContainerName(s.trim()))
.filter(Boolean)
);
+ }
+
+ function toggleExcludedContainerValue(current: SvelteSet<string>, containerName: string): string {
+ const normalizedName = normalizeContainerName(containerName);
+ const newSet = new SvelteSet(current);
+ if (newSet.has(normalizedName)) {
+ newSet.delete(normalizedName);
+ } else {
+ newSet.add(normalizedName);
+ }
+
+ return Array.from(newSet).join(',');
+ }
+
+ const excludedContainers = $derived.by(() => {
+ return parseExcludedContainerSet($formInputs.autoUpdateExcludedContainers?.value);
});
function resolveSettingsUrl(_job: JobStatus, prereq: JobPrerequisite): string | undefined {
@@ -91,40 +106,18 @@
}
function toggleContainerExclusion(containerName: string) {
- const normalizedName = normalizeContainerName(containerName);
- const newSet = new SvelteSet(excludedContainers);
- if (newSet.has(normalizedName)) {
- newSet.delete(normalizedName);
- } else {
- newSet.add(normalizedName);
- }
-
if ($formInputs.autoUpdateExcludedContainers) {
- $formInputs.autoUpdateExcludedContainers.value = Array.from(newSet).join(',');
+ $formInputs.autoUpdateExcludedContainers.value = toggleExcludedContainerValue(excludedContainers, containerName);
}
}
const autoHealExcludedContainers = $derived.by(() => {
- const savedValue = $formInputs.autoHealExcludedContainers?.value || '';
- return new SvelteSet(
- savedValue
- .split(',')
- .map((s: string) => normalizeContainerName(s.trim()))
- .filter(Boolean)
- );
+ return parseExcludedContainerSet($formInputs.autoHealExcludedContainers?.value);
});
function toggleAutoHealContainerExclusion(containerName: string) {
- const normalizedName = normalizeContainerName(containerName);
- const newSet = new SvelteSet(autoHealExcludedContainers);
- if (newSet.has(normalizedName)) {
- newSet.delete(normalizedName);
- } else {
- newSet.add(normalizedName);
- }
-
if ($formInputs.autoHealExcludedContainers) {
- $formInputs.autoHealExcludedContainers.value = Array.from(newSet).join(',');
+ $formInputs.autoHealExcludedContainers.value = toggleExcludedContainerValue(autoHealExcludedContainers, containerName);
}
}
diff --git a/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte b/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte
index 9cc801a69..759e279a1 100644
--- a/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte
@@ -3,7 +3,6 @@
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
- import { openConfirmDialog } from '$lib/components/confirm-dialog';
import { toast } from 'svelte-sonner';
import { handleApiResultWithCallbacks } from '$lib/utils/api';
import { tryCatch } from '$lib/utils/api';
@@ -26,6 +25,7 @@
HashIcon,
EllipsisIcon
} from '$lib/icons';
+ import { bulkConfirmAndRun, confirmAndRun } from '$lib/utils/bulk-actions';
type FieldVisibility = Record<string, boolean>;
@@ -59,67 +59,46 @@
}
async function handleDeleteSelected(ids: string[]) {
- if (!ids?.length) return;
-
- openConfirmDialog({
+ bulkConfirmAndRun({
+ ids,
title: m.common_remove_title({ resource: `${ids.length} ${m.resource_sync()}(s)` }),
message: m.common_remove_message({ resource: `${ids.length} ${m.resource_sync()}(s)` }),
- confirm: {
- label: m.common_remove(),
- destructive: true,
- action: async () => {
- isLoading.removing = true;
-
- let successCount = 0;
- let failureCount = 0;
- for (const id of ids) {
- const sync = syncs.data.find((s) => s.id === id);
- const result = await tryCatch(gitOpsSyncService.deleteSync(environmentId, id));
- if (result.error) {
- failureCount++;
- toast.error(m.common_delete_failed({ resource: sync?.name ?? m.common_unknown() }));
- } else {
- successCount++;
- }
- }
-
- if (successCount > 0) {
- toast.success(m.common_delete_success({ resource: `${successCount} ${m.resource_sync()}(s)` }));
- syncs = await gitOpsSyncService.getSyncs(environmentId, requestOptions);
- }
- if (failureCount > 0) toast.error(m.common_delete_failed({ resource: `${failureCount} items` }));
-
- selectedIds = [];
- isLoading.removing = false;
+ confirmLabel: m.common_remove(),
+ destructive: true,
+ run: (id) => gitOpsSyncService.deleteSync(environmentId, id),
+ messages: {
+ success: (count) => m.common_delete_success({ resource: `${count} ${m.resource_sync()}(s)` }),
+ partial: (_success, _total, failed) => m.common_delete_failed({ resource: `${failed} items` }),
+ failure: () => m.common_delete_failed({ resource: `${ids.length} items` })
+ },
+ setLoading: (loading) => (isLoading.removing = loading),
+ onItemFailure: (id) => {
+ const sync = syncs.data.find((item) => item.id === id);
+ toast.error(m.common_delete_failed({ resource: sync?.name ?? m.common_unknown() }));
+ },
+ onComplete: async (result) => {
+ if (result.success > 0) {
+ syncs = await gitOpsSyncService.getSyncs(environmentId, requestOptions);
}
- }
+ },
+ clearSelection: () => (selectedIds = []),
+ sequential: true
});
}
async function handleDeleteOne(id: string, name: string) {
const safeName = name ?? m.common_unknown();
- openConfirmDialog({
+ confirmAndRun({
title: m.git_sync_remove_confirm(),
message: m.git_sync_remove_message(),
- confirm: {
- label: m.common_remove(),
- destructive: true,
- action: async () => {
- isLoading.removing = true;
-
- const result = await tryCatch(gitOpsSyncService.deleteSync(environmentId, id));
- handleApiResultWithCallbacks({
- result,
- message: m.common_delete_failed({ resource: safeName }),
- setLoadingState: () => {},
- onSuccess: async () => {
- toast.success(m.common_delete_success({ resource: `${m.resource_sync()} "${safeName}"` }));
- syncs = await gitOpsSyncService.getSyncs(environmentId, requestOptions);
- }
- });
-
- isLoading.removing = false;
- }
+ confirmLabel: m.common_remove(),
+ destructive: true,
+ setLoading: (loading) => (isLoading.removing = loading),
+ run: () => gitOpsSyncService.deleteSync(environmentId, id),
+ failureMessage: m.common_delete_failed({ resource: safeName }),
+ onSuccess: async () => {
+ toast.success(m.common_delete_success({ resource: `${m.resource_sync()} "${safeName}"` }));
+ syncs = await gitOpsSyncService.getSyncs(environmentId, requestOptions);
}
});
}
@@ -175,7 +154,7 @@
},
{
accessorKey: 'lastSyncCommit',
- title: 'Commit',
+ title: m.git_sync_commit(),
sortable: true,
cell: CommitCell
},
@@ -194,7 +173,7 @@
{ id: 'composePath', label: m.git_sync_compose_path(), defaultVisible: true },
{ id: 'autoSync', label: m.git_sync_auto_sync(), defaultVisible: true },
{ id: 'lastSyncStatus', label: m.git_sync_status(), defaultVisible: true },
- { id: 'lastSyncCommit', label: 'Commit', defaultVisible: false },
+ { id: 'lastSyncCommit', label: m.git_sync_commit(), defaultVisible: false },
{ id: 'lastSyncAt', label: m.git_sync_last_sync(), defaultVisible: true }
];
diff --git a/frontend/src/routes/(app)/images/+page.ts b/frontend/src/routes/(app)/images/+page.ts
index 5ed5e0225..ece5b4e01 100644
--- a/frontend/src/routes/(app)/images/+page.ts
+++ b/frontend/src/routes/(app)/images/+page.ts
@@ -1,26 +1,19 @@
import { imageService } from '$lib/services/image-service';
import { settingsService } from '$lib/services/settings-service';
import { queryKeys } from '$lib/query/query-keys';
-import type { SearchPaginationSortRequest } from '$lib/types/shared';
-import { resolveInitialTableRequest } from '$lib/utils/tables';
+import { resolveListPageLoadContext } from '$lib/utils/tables';
import { throwPageLoadError } from '$lib/utils/api';
import type { PageLoad } from './$types';
-import { environmentStore } from '$lib/stores/environment.store.svelte';
export const load: PageLoad = async ({ parent }) => {
- const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
-
- const imageRequestOptions = resolveInitialTableRequest('arcane-image-table', {
- pagination: {
- page: 1,
- limit: 20
- },
- sort: {
- column: 'created',
- direction: 'desc'
- }
- } satisfies SearchPaginationSortRequest);
+ const {
+ queryClient,
+ envId,
+ requestOptions: imageRequestOptions
+ } = await resolveListPageLoadContext(parent, 'arcane-image-table', {
+ column: 'created',
+ direction: 'desc'
+ });
let images;
let settings;
let imageUsageCounts;
diff --git a/frontend/src/routes/(app)/images/[imageId]/+page.svelte b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
index 3628523af..a7195d287 100644
--- a/frontend/src/routes/(app)/images/[imageId]/+page.svelte
+++ b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
@@ -24,6 +24,7 @@
import type { VulnerabilityScanResult } from '$lib/types/environment';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { hasPermission } from '$lib/utils/auth';
+ import { toastVulnerabilityScanStatus } from '$lib/utils/vulnerability';
import { VolumesIcon, ClockIcon, TagIcon, LayersIcon, CpuIcon, InfoIcon, SettingsIcon, HashIcon } from '$lib/icons';
let { data } = $props();
@@ -72,13 +73,11 @@
const result = await vulnerabilityService.scanImage(image.id);
vulnerabilityScan = result;
lastScanRequestedAt = result.scanTime || new Date().toISOString();
- if (result.status === 'completed') {
- toast.success(m.vuln_scan_completed(), activityToastOptions(result.activityId));
- } else if (result.status === 'failed') {
- toast.error(result.error || m.vuln_scan_failed(), activityToastOptions(result.activityId));
- } else {
- toast.info(m.vuln_scan_started(), activityToastOptions(result.activityId));
+ if (isVulnerabilityScanInProgress(result.status)) {
+ toastVulnerabilityScanStatus(result, { includeStarted: true });
beginScanPolling(true);
+ } else {
+ toastVulnerabilityScanStatus(result);
}
} catch (error) {
console.error('Failed to scan image:', error);
@@ -153,12 +152,7 @@
} as VulnerabilityScanResult;
}
if (showToast) {
- const toastOptions = activityToastOptions(extractActivityId(resolvedSummary));
- if (resolvedSummary.status === 'completed') {
- toast.success(m.vuln_scan_completed(), toastOptions);
- } else {
- toast.error(resolvedSummary.error || m.vuln_scan_failed(), toastOptions);
- }
+ toastVulnerabilityScanStatus(resolvedSummary);
}
},
onError: () => {}
diff --git a/frontend/src/routes/(app)/images/builds/+page.svelte b/frontend/src/routes/(app)/images/builds/+page.svelte
index f7bba451a..02d0cf758 100644
--- a/frontend/src/routes/(app)/images/builds/+page.svelte
+++ b/frontend/src/routes/(app)/images/builds/+page.svelte
@@ -7,6 +7,7 @@
import { m } from '$lib/paraglide/messages';
import settingsStore from '$lib/stores/config-store';
import { createForm } from '$lib/utils/settings';
+ import { isDepotBuildAvailable } from '$lib/utils/build-provider';
import { toast } from 'svelte-sonner';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { ResourceDetailLayout } from '$lib/layouts/index.js';
@@ -67,11 +68,7 @@
return `…/${tail}`;
});
- const depotAvailable = $derived.by(() => {
- const projectId = ($settingsStore?.depotProjectId ?? '').trim();
- const token = ($settingsStore?.depotToken ?? '').trim();
- return Boolean($settingsStore?.depotConfigured) || (Boolean(projectId) && Boolean(token));
- });
+ const depotAvailable = $derived(isDepotBuildAvailable($settingsStore));
const providerOptions = $derived.by<BuildProviderOption[]>(() => {
const options: BuildProviderOption[] = [
@@ -219,30 +216,29 @@
});
const buildHistoryDetailsLoading = $derived(buildHistoryDetailQuery.isPending || buildHistoryDetailQuery.isFetching);
- type ImageBuildRequest = {
- envId: string;
- contextDir: string;
- dockerfile?: string;
- tags: string[];
- target?: string;
- buildArgs?: Record<string, string>;
- labels?: Record<string, string>;
- cacheFrom?: string[];
- cacheTo?: string[];
- noCache?: boolean;
- pull?: boolean;
- network?: string;
- isolation?: string;
- shmSize?: number;
- ulimits?: Record<string, string>;
- entitlements?: string[];
- privileged?: boolean;
- extraHosts?: string[];
- platforms?: string[];
- provider: 'local' | 'depot';
- push: boolean;
- load: boolean;
- };
+ type ImageBuildRequest = { envId: string; provider: 'local' | 'depot' } & Pick<
+ ImageBuildRecord,
+ | 'contextDir'
+ | 'dockerfile'
+ | 'tags'
+ | 'target'
+ | 'buildArgs'
+ | 'labels'
+ | 'cacheFrom'
+ | 'cacheTo'
+ | 'noCache'
+ | 'pull'
+ | 'network'
+ | 'isolation'
+ | 'shmSize'
+ | 'ulimits'
+ | 'entitlements'
+ | 'privileged'
+ | 'extraHosts'
+ | 'platforms'
+ | 'push'
+ | 'load'
+ >;
const buildMutation = createMutation(() => ({
mutationKey: queryKeys.images.buildRun(selectedEnvId),
diff --git a/frontend/src/routes/(app)/images/vulnerabilities/+page.svelte b/frontend/src/routes/(app)/images/vulnerabilities/+page.svelte
index 2e7862e0b..c624ea07b 100644
--- a/frontend/src/routes/(app)/images/vulnerabilities/+page.svelte
+++ b/frontend/src/routes/(app)/images/vulnerabilities/+page.svelte
@@ -15,6 +15,7 @@
import * as Tabs from '$lib/components/ui/tabs/index.js';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { hasPermission } from '$lib/utils/auth';
+ import { mapVulnerabilityPage, mapVulnerabilityRequest } from '$lib/utils/vulnerability';
let { data } = $props();
@@ -64,46 +65,6 @@
return items.filter((item) => item.value > 0);
});
- function mapVulnerabilityRequest(options: SearchPaginationSortRequest): SearchPaginationSortRequest {
- const filters = { ...(options.filters ?? {}) };
- if (filters['vulnSeverity']) {
- filters['severity'] = filters['vulnSeverity'];
- delete filters['vulnSeverity'];
- }
-
- const sort = options.sort?.column === 'vulnSeverity' ? { ...options.sort, column: 'severity' } : options.sort;
-
- return {
- ...options,
- sort,
- filters: Object.keys(filters).length ? filters : undefined
- };
- }
-
- function getVulnerabilityKey(vuln: VulnerabilityWithImage, index: number): string {
- return [
- vuln.imageId,
- vuln.vulnerabilityId,
- vuln.pkgName,
- vuln.installedVersion ?? '',
- vuln.fixedVersion ?? '',
- String(index)
- ].join('-');
- }
-
- function mapVulnerabilityPage(page: Paginated<VulnerabilityWithImage>, options: SearchPaginationSortRequest) {
- const pageNumber = options.pagination?.page ?? page.pagination?.currentPage ?? 1;
- const limit = options.pagination?.limit ?? page.pagination?.itemsPerPage ?? 20;
- const offset = (pageNumber - 1) * limit;
- return {
- ...page,
- data: (page.data ?? []).map((item, index) => ({
- ...item,
- id: getVulnerabilityKey(item, offset + index)
- }))
- };
- }
-
async function refreshAll() {
const requestForApi = mapVulnerabilityRequest(requestOptions);
await parallelRefresh(
diff --git a/frontend/src/routes/(app)/images/vulnerabilities/+page.ts b/frontend/src/routes/(app)/images/vulnerabilities/+page.ts
index 8e20a0ae0..5e170d4c0 100644
--- a/frontend/src/routes/(app)/images/vulnerabilities/+page.ts
+++ b/frontend/src/routes/(app)/images/vulnerabilities/+page.ts
@@ -3,54 +3,10 @@ import { environmentStore } from '$lib/stores/environment.store.svelte';
import { queryKeys } from '$lib/query/query-keys';
import type { SearchPaginationSortRequest } from '$lib/types/shared';
import { resolveInitialTableRequest } from '$lib/utils/tables';
-import type { Paginated } from '$lib/types/shared';
-import type { VulnerabilityWithImage } from '$lib/types/environment';
+import { mapVulnerabilityPage, mapVulnerabilityRequest } from '$lib/utils/vulnerability';
import { throwPageLoadError } from '$lib/utils/api';
import type { PageLoad } from './$types';
-function mapVulnerabilityRequest(options: SearchPaginationSortRequest): SearchPaginationSortRequest {
- const filters = { ...(options.filters ?? {}) };
- if (filters['vulnSeverity']) {
- filters['severity'] = filters['vulnSeverity'];
- delete filters['vulnSeverity'];
- }
-
- const sort = options.sort?.column === 'vulnSeverity' ? { ...options.sort, column: 'severity' } : options.sort;
-
- return {
- ...options,
- sort,
- filters: Object.keys(filters).length ? filters : undefined
- };
-}
-
-function getVulnerabilityKey(vuln: VulnerabilityWithImage, index: number): string {
- return [
- vuln.imageId,
- vuln.vulnerabilityId,
- vuln.pkgName,
- vuln.installedVersion ?? '',
- vuln.fixedVersion ?? '',
- String(index)
- ].join('-');
-}
-
-function mapVulnerabilityPage(
- page: Paginated<VulnerabilityWithImage>,
- options: SearchPaginationSortRequest
-): Paginated<VulnerabilityWithImage & { id: string }> {
- const pageNumber = options.pagination?.page ?? page.pagination?.currentPage ?? 1;
- const limit = options.pagination?.limit ?? page.pagination?.itemsPerPage ?? 20;
- const offset = (pageNumber - 1) * limit;
- return {
- ...page,
- data: (page.data ?? []).map((item, index) => ({
- ...item,
- id: getVulnerabilityKey(item, offset + index)
- }))
- };
-}
-
export const load: PageLoad = async ({ parent }) => {
const { queryClient } = await parent();
const envId = await environmentStore.getCurrentEnvironmentId();
diff --git a/frontend/src/routes/(app)/images/vulnerabilities/security-vulnerability-table.svelte b/frontend/src/routes/(app)/images/vulnerabilities/security-vulnerability-table.svelte
index 9ec1615f3..11fac80b8 100644
--- a/frontend/src/routes/(app)/images/vulnerabilities/security-vulnerability-table.svelte
+++ b/frontend/src/routes/(app)/images/vulnerabilities/security-vulnerability-table.svelte
@@ -12,8 +12,14 @@
import { onMount } from 'svelte';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { hasPermission } from '$lib/utils/auth';
-
- const DEFAULT_PAGE_SIZE = 20;
+ import {
+ getSeverityBadgeVariant,
+ getSeverityIconVariant,
+ getSeverityLabel,
+ mapVulnerabilityPage,
+ mapVulnerabilityRequest,
+ resolveSeverityFilter
+ } from '$lib/utils/vulnerability';
type VulnerabilityRow = VulnerabilityWithImage & { id: string };
@@ -30,77 +36,6 @@
const currentEnvId = $derived(environmentStore.selected?.id || '0');
const canManageVuln = $derived(hasPermission('vulnerabilities:manage', currentEnvId));
- function getSeverityLabel(severity: string): string {
- switch (severity) {
- case 'CRITICAL':
- return m.vuln_severity_critical();
- case 'HIGH':
- return m.vuln_severity_high();
- case 'MEDIUM':
- return m.vuln_severity_medium();
- case 'LOW':
- return m.vuln_severity_low();
- default:
- return m.vuln_severity_unknown();
- }
- }
-
- function getSeverityBadgeVariant(severity: string): 'red' | 'orange' | 'amber' | 'green' | 'gray' {
- switch (severity) {
- case 'CRITICAL':
- return 'red';
- case 'HIGH':
- return 'orange';
- case 'MEDIUM':
- return 'amber';
- case 'LOW':
- return 'green';
- default:
- return 'gray';
- }
- }
-
- function getSeverityIconVariant(severity: string): 'red' | 'orange' | 'amber' | 'emerald' | 'gray' {
- switch (severity) {
- case 'CRITICAL':
- return 'red';
- case 'HIGH':
- return 'orange';
- case 'MEDIUM':
- return 'amber';
- case 'LOW':
- return 'emerald';
- default:
- return 'gray';
- }
- }
-
- function getVulnerabilityKey(vuln: VulnerabilityWithImage, index: number): string {
- return [
- vuln.imageId,
- vuln.vulnerabilityId,
- vuln.pkgName,
- vuln.installedVersion ?? '',
- vuln.fixedVersion ?? '',
- String(index)
- ].join('-');
- }
-
- function resolveSeverityFilter(options?: SearchPaginationSortRequest): string | undefined {
- const rawSeverity = options?.filters?.['severity'] ?? options?.filters?.['vulnSeverity'];
- if (Array.isArray(rawSeverity)) {
- const values = rawSeverity.map((entry) => String(entry).trim()).filter(Boolean);
- return values.length ? values.join(',') : undefined;
- }
-
- if (rawSeverity === undefined || rawSeverity === null) {
- return undefined;
- }
-
- const value = String(rawSeverity).trim();
- return value || undefined;
- }
-
function deriveImageOptionsFromRows(rows: VulnerabilityRow[]): string[] {
return [...new Set(rows.map((row) => row.imageName || row.imageId).filter(Boolean) as string[])].sort();
}
@@ -122,34 +57,13 @@
}
async function refreshVulnerabilityTable(options: SearchPaginationSortRequest) {
- const mergedFilters = { ...(options.filters ?? {}) };
- if (mergedFilters['vulnSeverity']) {
- mergedFilters['severity'] = mergedFilters['vulnSeverity'];
- delete mergedFilters['vulnSeverity'];
- }
-
- const sort = options.sort?.column === 'vulnSeverity' ? { ...options.sort, column: 'severity' } : options.sort;
-
- const request: SearchPaginationSortRequest = {
- ...options,
- sort,
- filters: Object.keys(mergedFilters).length ? mergedFilters : undefined
- };
+ const request = mapVulnerabilityRequest(options);
const [response, optionsResponse] = await Promise.all([
vulnerabilityService.getAllVulnerabilities(request),
refreshImageNameFilterOptions(request)
]);
- const page = request.pagination?.page ?? 1;
- const limit = request.pagination?.limit ?? DEFAULT_PAGE_SIZE;
- const offset = (page - 1) * limit;
- const mapped: Paginated<VulnerabilityRow> = {
- ...response,
- data: (response.data ?? []).map((item, index) => ({
- ...item,
- id: getVulnerabilityKey(item, offset + index)
- }))
- };
+ const mapped = mapVulnerabilityPage(response, request);
vulnerabilities = mapped;
if (optionsResponse.length === 0) {
diff --git a/frontend/src/routes/(app)/networks/+page.ts b/frontend/src/routes/(app)/networks/+page.ts
index 26922571e..9bfa54909 100644
--- a/frontend/src/routes/(app)/networks/+page.ts
+++ b/frontend/src/routes/(app)/networks/+page.ts
@@ -1,25 +1,18 @@
import { networkService } from '$lib/services/network-service';
import { queryKeys } from '$lib/query/query-keys';
-import type { SearchPaginationSortRequest } from '$lib/types/shared';
-import { resolveInitialTableRequest } from '$lib/utils/tables';
+import { resolveListPageLoadContext } from '$lib/utils/tables';
import { throwPageLoadError } from '$lib/utils/api';
import type { PageLoad } from './$types';
-import { environmentStore } from '$lib/stores/environment.store.svelte';
export const load: PageLoad = async ({ parent }) => {
- const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
-
- const networkRequestOptions = resolveInitialTableRequest('arcane-networks-table', {
- pagination: {
- page: 1,
- limit: 20
- },
- sort: {
- column: 'name',
- direction: 'asc'
- }
- } satisfies SearchPaginationSortRequest);
+ const {
+ queryClient,
+ envId,
+ requestOptions: networkRequestOptions
+ } = await resolveListPageLoadContext(parent, 'arcane-networks-table', {
+ column: 'name',
+ direction: 'asc'
+ });
// Single API call - counts are included in the response
let networks;
diff --git a/frontend/src/routes/(app)/ports/+page.ts b/frontend/src/routes/(app)/ports/+page.ts
index 20eb27f8b..ddd0a62c3 100644
--- a/frontend/src/routes/(app)/ports/+page.ts
+++ b/frontend/src/routes/(app)/ports/+page.ts
@@ -1,25 +1,18 @@
import { portService } from '$lib/services/port-service';
import { queryKeys } from '$lib/query/query-keys';
-import type { SearchPaginationSortRequest } from '$lib/types/shared';
-import { resolveInitialTableRequest } from '$lib/utils/tables';
+import { resolveListPageLoadContext } from '$lib/utils/tables';
import { throwPageLoadError } from '$lib/utils/api';
import type { PageLoad } from './$types';
-import { environmentStore } from '$lib/stores/environment.store.svelte';
export const load: PageLoad = async ({ parent }) => {
- const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
-
- const portRequestOptions = resolveInitialTableRequest('arcane-ports-table', {
- pagination: {
- page: 1,
- limit: 20
- },
- sort: {
- column: 'hostPort',
- direction: 'asc'
- }
- } satisfies SearchPaginationSortRequest);
+ const {
+ queryClient,
+ envId,
+ requestOptions: portRequestOptions
+ } = await resolveListPageLoadContext(parent, 'arcane-ports-table', {
+ column: 'hostPort',
+ direction: 'asc'
+ });
let ports;
try {
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
index 824fd3501..4dad18673 100644
--- a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
@@ -42,6 +42,7 @@
import ProjectUpdateItem from '$lib/components/project-update-item.svelte';
import IfPermitted from '$lib/components/if-permitted.svelte';
import { activityToastOptions, extractActivityId } from '$lib/utils/activity-toast';
+ import { globalVariablesToMap } from '$lib/utils/template-load';
let { data } = $props();
let projectId = $derived(data.projectId);
@@ -71,9 +72,7 @@
let loadedIncludeFileContents = $state<Record<string, string>>({});
let loadedDirectoryFileContents = $state<Record<string, string>>({});
let projectFilePromises: Record<string, Promise<IncludeFile> | undefined> = {};
- const globalVariableMap = $derived.by(() =>
- Object.fromEntries((data.globalVariables ?? []).map((item) => [item.key, item.value]))
- );
+ const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));
const projectDetailQuery = createQuery(() => ({
queryKey: queryKeys.projects.detail(envId, projectId),
diff --git a/frontend/src/routes/(app)/projects/components/ProjectContainersTable.svelte b/frontend/src/routes/(app)/projects/components/ProjectContainersTable.svelte
index 26cc979cd..d37a73876 100644
--- a/frontend/src/routes/(app)/projects/components/ProjectContainersTable.svelte
+++ b/frontend/src/routes/(app)/projects/components/ProjectContainersTable.svelte
@@ -13,17 +13,14 @@
import type { ColumnSpec, BulkAction } from '$lib/components/arcane-table';
import { m } from '$lib/paraglide/messages';
import { goto } from '$app/navigation';
- import { toast } from 'svelte-sonner';
- import { openConfirmDialog } from '$lib/components/confirm-dialog';
- import { handleApiResultWithCallbacks } from '$lib/utils/api';
- import { tryCatch } from '$lib/utils/api';
import { containerService } from '$lib/services/container-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { hasPermission } from '$lib/utils/auth';
import * as ArcaneTooltip from '$lib/components/arcane-tooltip';
import IconImage from '$lib/components/icon-image.svelte';
import { getArcaneIconUrlFromLabels } from '$lib/utils/docker';
- import { activityToastOptions, extractActivityId } from '$lib/utils/activity-toast';
+ import { bulkConfirmAndRun, hasAnyLoadingState } from '$lib/utils/bulk-actions';
+ import { confirmAndRemoveContainer, runContainerLifecycleAction } from '$lib/utils/container-actions';
import {
StartIcon,
StopIcon,
@@ -106,72 +103,24 @@
}
async function performContainerAction(action: 'start' | 'stop' | 'restart', id: string) {
- if (!id) return;
-
- const statusMap = { start: 'starting', stop: 'stopping', restart: 'restarting' } as const;
- actionStatus[id] = statusMap[action];
-
- try {
- const serviceCall =
- action === 'start'
- ? containerService.startContainer(id)
- : action === 'stop'
- ? containerService.stopContainer(id)
- : containerService.restartContainer(id);
-
- const messageMap = {
- start: { failed: m.containers_start_failed(), success: m.containers_start_success() },
- stop: { failed: m.containers_stop_failed(), success: m.containers_stop_success() },
- restart: { failed: m.containers_restart_failed(), success: m.containers_restart_success() }
- };
-
- handleApiResultWithCallbacks({
- result: await tryCatch(serviceCall),
- message: messageMap[action].failed,
- setLoadingState: (value) => {
- actionStatus[id] = value ? statusMap[action] : '';
- },
- async onSuccess(data) {
- toast.success(messageMap[action].success, activityToastOptions(extractActivityId(data)));
- await onRefresh?.();
- }
- });
- } catch (error) {
- console.error('Container action failed:', error);
- toast.error(m.containers_action_error());
- actionStatus[id] = '';
- }
+ await runContainerLifecycleAction({
+ action,
+ containerId: id,
+ setStatus: (status) => {
+ actionStatus[id] = status;
+ },
+ onRefresh
+ });
}
async function handleRemoveContainer(id: string, name: string) {
- openConfirmDialog({
- title: m.containers_remove_confirm_title(),
- message: m.containers_remove_confirm_message({ resource: name }),
- checkboxes: [
- { id: 'force', label: m.containers_remove_force_label(), initialState: false },
- { id: 'volumes', label: m.containers_remove_volumes_label(), initialState: false }
- ],
- confirm: {
- label: m.common_remove(),
- destructive: true,
- action: async (checkboxStates) => {
- const force = !!checkboxStates['force'];
- const volumes = !!checkboxStates['volumes'];
- actionStatus[id] = 'removing';
-
- handleApiResultWithCallbacks({
- result: await tryCatch(containerService.deleteContainer(id, { force, volumes })),
- message: m.containers_remove_failed(),
- setLoadingState: (value) => {
- actionStatus[id] = value ? 'removing' : '';
- },
- async onSuccess(data) {
- toast.success(m.containers_remove_success(), activityToastOptions(extractActivityId(data)));
- await onRefresh?.();
- }
- });
- }
- }
+ confirmAndRemoveContainer({
+ containerId: id,
+ containerName: name,
+ setStatus: (status) => {
+ actionStatus[id] = status;
+ },
+ onRefresh
});
}
@@ -188,7 +137,9 @@
label: m.common_start(),
destructive: false,
fn: (id: string) => containerService.startContainer(id),
- success: m.containers_bulk_start_success({ count: validIds.length }),
+ success: (count: number) => m.containers_bulk_start_success({ count }),
+ partial: (success: number, total: number, failed: number) => m.containers_bulk_start_partial({ success, total, failed }),
+ failure: () => m.containers_start_failed(),
loadingKey: 'start' as const
},
stop: {
@@ -197,7 +148,9 @@
label: m.common_stop(),
destructive: false,
fn: (id: string) => containerService.stopContainer(id),
- success: m.containers_bulk_stop_success({ count: validIds.length }),
+ success: (count: number) => m.containers_bulk_stop_success({ count }),
+ partial: (success: number, total: number, failed: number) => m.containers_bulk_stop_partial({ success, total, failed }),
+ failure: () => m.containers_stop_failed(),
loadingKey: 'stop' as const
},
restart: {
@@ -206,7 +159,10 @@
label: m.common_restart(),
destructive: false,
fn: (id: string) => containerService.restartContainer(id),
- success: m.containers_bulk_restart_success({ count: validIds.length }),
+ success: (count: number) => m.containers_bulk_restart_success({ count }),
+ partial: (success: number, total: number, failed: number) =>
+ m.containers_bulk_restart_partial({ success, total, failed }),
+ failure: () => m.containers_restart_failed(),
loadingKey: 'restart' as const
},
remove: {
@@ -215,45 +171,38 @@
label: m.common_remove(),
destructive: true,
fn: (id: string) => containerService.deleteContainer(id, { force: false, volumes: false }),
- success: m.containers_bulk_remove_success({ count: validIds.length }),
+ success: (count: number) => m.containers_bulk_remove_success({ count }),
+ partial: (success: number, total: number, failed: number) => m.containers_bulk_remove_partial({ success, total, failed }),
+ failure: () => m.containers_remove_failed(),
loadingKey: 'remove' as const
}
};
const config = actionConfig[action];
- openConfirmDialog({
+ bulkConfirmAndRun({
+ ids: validIds,
title: config.title,
message: config.message,
- confirm: {
- label: config.label,
- destructive: config.destructive,
- action: async () => {
- isBulkLoading[config.loadingKey] = true;
-
- const results = await Promise.allSettled(validIds.map((id) => config.fn(id)));
- const successCount = results.filter((r) => r.status === 'fulfilled').length;
-
- isBulkLoading[config.loadingKey] = false;
-
- if (successCount === validIds.length) {
- toast.success(config.success);
- } else if (successCount > 0) {
- toast.warning(`${successCount} of ${validIds.length} succeeded`);
- } else {
- toast.error(m.containers_action_error());
- }
-
- selectedIds = [];
- await onRefresh?.();
- }
+ confirmLabel: config.label,
+ destructive: config.destructive,
+ run: (id) => config.fn(id),
+ messages: {
+ success: config.success,
+ partial: config.partial,
+ failure: config.failure
+ },
+ setLoading: (loading) => {
+ isBulkLoading[config.loadingKey] = loading;
+ },
+ onComplete: async () => onRefresh?.(),
+ clearSelection: () => {
+ selectedIds = [];
}
});
}
- const isAnyLoading = $derived(
- Object.values(actionStatus).some((status) => status !== '') || Object.values(isBulkLoading).some((loading) => loading)
- );
+ const isAnyLoading = $derived(hasAnyLoadingState(actionStatus, isBulkLoading));
const showActionsColumn = $derived(servicesWithIds.some((service) => service.status === 'running'));
diff --git a/frontend/src/routes/(app)/projects/new/+page.svelte b/frontend/src/routes/(app)/projects/new/+page.svelte
index 2569efe1a..382d66975 100644
--- a/frontend/src/routes/(app)/projects/new/+page.svelte
+++ b/frontend/src/routes/(app)/projects/new/+page.svelte
@@ -1,24 +1,14 @@
<script lang="ts">
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { ArrowLeftIcon, TerminalIcon, CopyIcon, TemplateIcon, AddIcon, GitBranchIcon } from '$lib/icons';
+ import { ArrowLeftIcon, TerminalIcon, TemplateIcon, AddIcon, GitBranchIcon } from '$lib/icons';
import { Spinner } from '$lib/components/ui/spinner/index.js';
- import { Label } from '$lib/components/ui/label/index.js';
import { goto, invalidateAll } from '$app/navigation';
import { toast } from 'svelte-sonner';
import { preventDefault, createForm } from '$lib/utils/settings';
- import { tryCatch } from '$lib/utils/api';
- import { handleApiResultWithCallbacks } from '$lib/utils/api';
- import { Textarea } from '$lib/components/ui/textarea/index.js';
- import * as Dialog from '$lib/components/ui/dialog/index.js';
import * as ArcaneTooltip from '$lib/components/arcane-tooltip';
import TemplateSelectionDialog from '$lib/components/dialogs/template-selection-dialog.svelte';
- import type { Template } from '$lib/types/swarm';
- import { z } from 'zod/v4';
- import { arcaneButtonVariants, actionConfigs } from '$lib/components/arcane-button/variants';
import { m } from '$lib/paraglide/messages';
import { projectService } from '$lib/services/project-service.js';
- import { systemService } from '$lib/services/system-service.js';
- import { templateService } from '$lib/services/template-service.js';
import * as ButtonGroup from '$lib/components/ui/button-group/index.js';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
import { ArrowDownIcon as ChevronDown } from '$lib/icons';
@@ -28,52 +18,69 @@
import { hasPermission } from '$lib/utils/auth';
import IfPermitted from '$lib/components/if-permitted.svelte';
import { ComposeEditorSplit } from '$lib/components/compose';
+ import DockerRunConverterDialog from '$lib/components/compose/docker-run-converter-dialog.svelte';
import { activityToastOptions, extractActivityId } from '$lib/utils/activity-toast';
+ import { globalVariablesToMap } from '$lib/utils/template-load';
+ import {
+ createComposeEditorSchema,
+ createComposeTemplateDialogFlow,
+ dropdownContentClass,
+ dropdownItemClass,
+ submitComposeResourceForm,
+ templateBtnClass,
+ templateNameSlug
+ } from '$lib/utils/compose-flow';
+ import {
+ getTemplateEditorValidationState,
+ hasTemplateEditorErrors,
+ validateTemplateEditorForm
+ } from '$lib/utils/template-editor';
let { data } = $props();
const currentEnvId = $derived(environmentStore.selected?.id || '0');
const canCreateProject = $derived(hasPermission('projects:create', currentEnvId));
- let saving = $state(false);
- let converting = $state(false);
- let creatingTemplate = $state(false);
- let showTemplateDialog = $state(false);
- let showConverterDialog = $state(false);
- let isLoadingTemplateContent = $state(false);
-
- const formSchema = z.object({
- name: z
- .string()
- .min(1, m.compose_project_name_required())
- .regex(/^[a-z0-9-_]+$/i, m.compose_project_name_invalid()),
- composeContent: z.string().min(1, m.compose_compose_content_required()),
- envContent: z.string().optional().default('')
+ let ui = $state({
+ saving: false,
+ converting: false,
+ creatingTemplate: false,
+ showTemplateDialog: false,
+ showConverterDialog: false,
+ isLoadingTemplateContent: false
});
+ const formSchema = createComposeEditorSchema(m.compose_project_name_required());
+
// Initial form values intentionally come from the page load data once.
// svelte-ignore state_referenced_locally
const formData = {
- name: data.selectedTemplate ? data.selectedTemplate.name.toLowerCase().replace(/[^a-z0-9-_]/g, '-') : '',
+ name: data.selectedTemplate ? templateNameSlug(data.selectedTemplate.name) : '',
composeContent: data.defaultTemplate || '',
envContent: data.envTemplate || ''
};
const { inputs, ...form } = createForm<typeof formSchema>(formSchema, formData);
- let dockerRunCommand = $state('');
let composeOpen = $state(true);
let envOpen = $state(true);
- let composeHasErrors = $state(false);
- let envHasErrors = $state(false);
- let composeValidationReady = $state(false);
- let envValidationReady = $state(false);
+ let validation = $state({
+ composeHasErrors: false,
+ envHasErrors: false,
+ composeValidationReady: false,
+ envValidationReady: false
+ });
- const globalVariableMap = $derived.by(() =>
- Object.fromEntries((data.globalVariables ?? []).map((item) => [item.key, item.value]))
+ const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));
+ const validationState = $derived(
+ getTemplateEditorValidationState(
+ validation.composeValidationReady,
+ validation.envValidationReady,
+ validation.composeHasErrors,
+ validation.envHasErrors
+ )
);
-
- let hasEditorErrors = $derived(!composeValidationReady || !envValidationReady || composeHasErrors || envHasErrors);
+ let hasEditorErrors = $derived(hasTemplateEditorErrors(validationState));
let nameInputRef = $state<HTMLInputElement | null>(null);
@@ -82,21 +89,12 @@
}
async function handleCreateProject() {
- if (hasEditorErrors) {
- toast.error(m.templates_validation_error());
- return;
- }
-
- const validated = form.validate();
- if (!validated) return;
-
- const { name, composeContent, envContent } = validated;
-
- handleApiResultWithCallbacks({
- result: await tryCatch(projectService.createProject(name, composeContent, envContent)),
- message: m.common_create_failed({ resource: `${m.resource_project()} "${name}"` }),
- setLoadingState: (value) => (saving = value),
- onSuccess: async (project) => {
+ await submitComposeResourceForm({
+ validate: () => validateTemplateEditorForm(validationState, form.validate),
+ setLoading: (value) => (ui.saving = value),
+ submit: ({ name, composeContent, envContent }) => projectService.createProject(name, composeContent, envContent),
+ failureMessage: (name) => m.common_create_failed({ resource: `${m.resource_project()} "${name}"` }),
+ onSuccess: async (project, { name }) => {
toast.success(
m.common_create_success({ resource: `${m.resource_project()} "${name}"` }),
activityToastOptions(extractActivityId(project))
@@ -106,88 +104,14 @@
});
}
- async function handleConvertDockerRun() {
- if (!dockerRunCommand.trim()) {
- toast.error(m.compose_enter_docker_run_command());
- return;
- }
-
- handleApiResultWithCallbacks({
- result: await tryCatch(systemService.convert(dockerRunCommand)),
- message: m.compose_convert_failed(),
- setLoadingState: (value) => (converting = value),
- onSuccess: (data) => {
- $inputs.composeContent.value = data.dockerCompose;
- $inputs.envContent.value = data.envVars;
- $inputs.name.value = data.serviceName;
-
- toast.success(m.compose_convert_success());
- dockerRunCommand = '';
- showConverterDialog = false;
- }
- });
- }
-
- async function handleTemplateSelect(template: Template) {
- showTemplateDialog = false;
-
- $inputs.composeContent.value = template.content ?? '';
- $inputs.envContent.value = template.envContent ?? '';
-
- if (!$inputs.name.value?.trim()) {
- $inputs.name.value = template.name.toLowerCase().replace(/[^a-z0-9-_]/g, '-');
- }
- toast.success(m.compose_template_loaded({ name: template.name }));
- }
-
- const exampleCommands = [m.compose_example_command_1(), m.compose_example_command_2(), m.compose_example_command_3()];
-
- function useExample(command: string) {
- dockerRunCommand = command;
- }
-
- async function handleCreateTemplate() {
- if (hasEditorErrors) {
- toast.error(m.templates_validation_error());
- return;
- }
-
- const validated = form.validate();
- if (!validated) return;
-
- const { name, composeContent, envContent } = validated;
-
- handleApiResultWithCallbacks({
- result: await tryCatch(
- templateService.createTemplate({
- name,
- content: composeContent,
- envContent
- })
- ),
- message: m.common_create_failed({ resource: `${m.resource_template()} "${name}"` }),
- setLoadingState: (value) => (creatingTemplate = value),
- onSuccess: async () => {
- toast.success(m.common_create_success({ resource: `${m.resource_template()} "${name}"` }));
- }
- });
- }
-
- const templateBtnClass = arcaneButtonVariants({
- tone: actionConfigs.template?.tone ?? 'outline-primary',
- size: 'default',
- hoverEffect: 'none'
+ const { composeHandlers, handleCreateTemplate } = createComposeTemplateDialogFlow({
+ getInputs: () => $inputs,
+ setInputValue: (key, value) => form.setValue(key, value),
+ closeTemplateDialog: () => (ui.showTemplateDialog = false),
+ validate: form.validate,
+ setLoading: (value) => (ui.creatingTemplate = value),
+ hasEditorErrors: () => hasEditorErrors
});
-
- const dropdownContentClass =
- 'arcane-dd-content min-w-[220px] overflow-visible rounded-lg border border-primary/30 bg-background/95 ' +
- 'backdrop-blur supports-[backdrop-filter]:bg-background/80 ring-1 ring-inset ring-primary/20 shadow-sm p-1';
-
- const dropdownItemClass =
- 'flex cursor-pointer select-none items-center gap-2 rounded-md px-3 py-2 text-sm ' +
- 'text-foreground/90 outline-none transition-colors ' +
- 'hover:bg-primary/10 focus:bg-primary/10 ' +
- 'data-[disabled]:opacity-50 data-[disabled]:pointer-events-none';
</script>
<div class="bg-background flex h-full min-h-0 flex-col">
@@ -212,7 +136,7 @@
error={$inputs.name.error ?? undefined}
originalValue=""
placeholder={m.compose_project_name_placeholder?.() || 'Enter project name...'}
- canEdit={!saving && !isLoadingTemplateContent}
+ canEdit={!ui.saving && !ui.isLoadingTemplateContent}
class="hidden sm:block"
/>
</div>
@@ -221,7 +145,7 @@
<div class="flex items-center gap-2">
<ButtonGroup.Root>
<ArcaneTooltip.Root
- open={!$inputs.name.value && !saving && !converting && !isLoadingTemplateContent ? undefined : false}
+ open={!$inputs.name.value && !ui.saving && !ui.converting && !ui.isLoadingTemplateContent ? undefined : false}
>
<ArcaneTooltip.Trigger>
<span>
@@ -232,12 +156,12 @@
disabled={!$inputs.name.value ||
!$inputs.composeContent.value ||
hasEditorErrors ||
- saving ||
- converting ||
- isLoadingTemplateContent}
+ ui.saving ||
+ ui.converting ||
+ ui.isLoadingTemplateContent}
onclick={() => handleSubmit()}
class={`${templateBtnClass} gap-2 rounded-r-none`}
- loading={saving}
+ loading={ui.saving}
customLabel={m.compose_create_project()}
loadingLabel={m.common_action_creating()}
/>
@@ -273,13 +197,13 @@
<DropdownMenu.Group>
<DropdownMenu.Item
class={dropdownItemClass}
- disabled={saving || converting || isLoadingTemplateContent}
- onclick={() => (showTemplateDialog = true)}
+ disabled={ui.saving || ui.converting || ui.isLoadingTemplateContent}
+ onclick={() => (ui.showTemplateDialog = true)}
>
<TemplateIcon class="size-4" />
{m.common_use_template()}
</DropdownMenu.Item>
- <DropdownMenu.Item class={dropdownItemClass} onclick={() => (showConverterDialog = true)}>
+ <DropdownMenu.Item class={dropdownItemClass} onclick={() => (ui.showConverterDialog = true)}>
<TerminalIcon class="size-4" />
{m.compose_convert_from_docker_run()}
</DropdownMenu.Item>
@@ -298,13 +222,13 @@
disabled={!$inputs.name.value ||
!$inputs.composeContent.value ||
hasEditorErrors ||
- saving ||
- converting ||
- creatingTemplate ||
- isLoadingTemplateContent}
+ ui.saving ||
+ ui.converting ||
+ ui.creatingTemplate ||
+ ui.isLoadingTemplateContent}
onclick={handleCreateTemplate}
>
- {#if creatingTemplate}
+ {#if ui.creatingTemplate}
<Spinner class="size-4" />
{:else}
<AddIcon class="size-4" />
@@ -331,7 +255,7 @@
error={$inputs.name.error ?? undefined}
originalValue=""
placeholder={m.compose_project_name_placeholder()}
- canEdit={!saving && !isLoadingTemplateContent}
+ canEdit={!ui.saving && !ui.isLoadingTemplateContent}
/>
</div>
@@ -343,8 +267,8 @@
language="yaml"
bind:value={$inputs.composeContent.value}
error={$inputs.composeContent.error ?? undefined}
- bind:hasErrors={composeHasErrors}
- bind:validationReady={composeValidationReady}
+ bind:hasErrors={validation.composeHasErrors}
+ bind:validationReady={validation.composeValidationReady}
fileId="projects:new:compose"
editorContext={{
envContent: $inputs.envContent.value,
@@ -361,8 +285,8 @@
language="env"
bind:value={$inputs.envContent.value}
error={$inputs.envContent.error ?? undefined}
- bind:hasErrors={envHasErrors}
- bind:validationReady={envValidationReady}
+ bind:hasErrors={validation.envHasErrors}
+ bind:validationReady={validation.envValidationReady}
fileId="projects:new:env"
editorContext={{
envContent: $inputs.envContent.value,
@@ -377,60 +301,15 @@
</div>
</div>
-<Dialog.Root bind:open={showConverterDialog}>
- <Dialog.Content class="max-h-[80vh] sm:max-w-[800px]">
- <Dialog.Header>
- <Dialog.Title>{m.compose_converter_title()}</Dialog.Title>
- <Dialog.Description>{m.compose_converter_description()}</Dialog.Description>
- </Dialog.Header>
-
- <div class="max-h-[60vh] space-y-4 overflow-y-auto">
- <div class="space-y-2">
- <Label for="dockerRunCommand">{m.compose_docker_run_command_label()}</Label>
- <Textarea
- id="dockerRunCommand"
- bind:value={dockerRunCommand}
- placeholder={m.compose_docker_run_placeholder()}
- rows={3}
- disabled={converting}
- class="font-mono text-sm"
- />
- </div>
-
- <div class="space-y-2">
- <Label class="text-muted-foreground text-xs">{m.compose_example_commands_label()}</Label>
- <div class="space-y-1">
- {#each exampleCommands as command (command)}
- <ArcaneButton
- action="base"
- tone="ghost"
- size="sm"
- class="h-auto w-full justify-start p-2 text-left font-mono text-xs break-all whitespace-normal"
- onclick={() => useExample(command)}
- icon={CopyIcon}
- customLabel={command}
- />
- {/each}
- </div>
- </div>
- </div>
-
- <div class="flex w-full justify-end pt-4">
- <ArcaneButton
- action="create"
- disabled={!dockerRunCommand.trim() || converting}
- onclick={handleConvertDockerRun}
- loading={converting}
- customLabel={m.compose_convert_action()}
- loadingLabel={m.compose_converting()}
- />
- </div>
- </Dialog.Content>
-</Dialog.Root>
+<DockerRunConverterDialog
+ bind:open={ui.showConverterDialog}
+ bind:converting={ui.converting}
+ onConverted={composeHandlers.handleDockerRunConverted}
+/>
<TemplateSelectionDialog
- bind:open={showTemplateDialog}
+ bind:open={ui.showTemplateDialog}
templates={data.composeTemplates || []}
- onSelect={handleTemplateSelect}
+ onSelect={composeHandlers.handleTemplateSelect}
onDownloadSuccess={invalidateAll}
/>
diff --git a/frontend/src/routes/(app)/projects/new/+page.ts b/frontend/src/routes/(app)/projects/new/+page.ts
index c301e7714..b09c62bef 100644
--- a/frontend/src/routes/(app)/projects/new/+page.ts
+++ b/frontend/src/routes/(app)/projects/new/+page.ts
@@ -1,52 +1,15 @@
-import { templateService } from '$lib/services/template-service';
-import { queryKeys } from '$lib/query/query-keys';
+import { loadTemplateAuthoringData, loadTemplateContent } from '$lib/utils/template-load';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({ url, parent }) => {
const { queryClient } = await parent();
const templateId = url.searchParams.get('templateId');
+ const { defaultTemplates, templates: allTemplates, globalVariables } = await loadTemplateAuthoringData(parent);
- const [allTemplates, defaultTemplates, selectedTemplate, globalVariables] = await Promise.all([
- queryClient
- .fetchQuery({
- queryKey: queryKeys.templates.allTemplates(),
- queryFn: () => templateService.getAllTemplates()
- })
- .catch((err) => {
- console.warn('Failed to load templates:', err);
- return [];
- }),
- queryClient
- .fetchQuery({
- queryKey: queryKeys.templates.defaults(),
- queryFn: () => templateService.getDefaultTemplates()
- })
- .catch((err) => {
- console.warn('Failed to load default templates:', err);
- return { composeTemplate: '', envTemplate: '' };
- }),
- templateId
- ? queryClient
- .fetchQuery({
- queryKey: queryKeys.templates.content(templateId),
- queryFn: () => templateService.getTemplateContent(templateId)
- })
- .catch((err) => {
- console.warn('Failed to load selected template:', err);
- return null;
- })
- : Promise.resolve(null),
- queryClient
- .fetchQuery({
- queryKey: queryKeys.templates.globalVariables(),
- queryFn: () => templateService.getGlobalVariables()
- })
- .catch((err) => {
- console.warn('Failed to load global variables:', err);
- return [];
- })
- ]);
+ const selectedTemplate = templateId
+ ? await loadTemplateContent(queryClient as Parameters<typeof loadTemplateContent>[0], templateId)
+ : null;
return {
composeTemplates: allTemplates,
diff --git a/frontend/src/routes/(app)/projects/projects-table.actions.ts b/frontend/src/routes/(app)/projects/projects-table.actions.ts
index cb44f8da5..a3b9c59a0 100644
--- a/frontend/src/routes/(app)/projects/projects-table.actions.ts
+++ b/frontend/src/routes/(app)/projects/projects-table.actions.ts
@@ -7,6 +7,7 @@ import type { SearchPaginationSortRequest } from '$lib/types/shared';
import { handleApiResultWithCallbacks } from '$lib/utils/api';
import { tryCatch } from '$lib/utils/api';
import { activityToastOptions, extractActivityId } from '$lib/utils/activity-toast';
+import type { TableActionConfig, TableBulkActionConfig } from '$lib/utils/table-action-types';
import { toast } from 'svelte-sonner';
import type { ActionStatus } from './projects-table.helpers';
@@ -28,24 +29,8 @@ type ActionDeps = {
type ProjectActionKind = 'start' | 'stop' | 'restart' | 'redeploy' | 'archive' | 'unarchive';
-type ProjectActionConfig = {
- status: ActionStatus;
- run: (id: string) => Promise<unknown>;
- success: () => string;
- failure: () => string;
-};
-
-type BulkActionConfig = {
- title: (count: number) => string;
- message: (count: number) => string;
- label: string;
- loadingKey: keyof BulkLoadingState;
- run: (id: string) => Promise<unknown>;
- success: (count: number) => string;
- partial: (success: number, total: number, failed: number) => string;
- failure: () => string;
- destructive?: boolean;
-};
+type ProjectActionConfig = TableActionConfig<ActionStatus>;
+type BulkActionConfig = TableBulkActionConfig<keyof BulkLoadingState>;
type DestroyConfirmResult = {
checkboxes?: {
diff --git a/frontend/src/routes/(app)/projects/projects-table.svelte b/frontend/src/routes/(app)/projects/projects-table.svelte
index a4853f3d9..a3c57493c 100644
--- a/frontend/src/routes/(app)/projects/projects-table.svelte
+++ b/frontend/src/routes/(app)/projects/projects-table.svelte
@@ -20,6 +20,7 @@
import { FolderOpenIcon, LayersIcon, CalendarIcon, ProjectsIcon, GitBranchIcon, RefreshIcon } from '$lib/icons';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { hasPermission } from '$lib/utils/auth';
+ import { hasAnyLoadingState } from '$lib/utils/bulk-actions';
import IfPermitted from '$lib/components/if-permitted.svelte';
import IconImage from '$lib/components/icon-image.svelte';
import type { ActionStatus } from './projects-table.helpers';
@@ -134,9 +135,7 @@
getEnvId: () => envId
});
- const isAnyLoading = $derived(
- Object.values(actionStatus).some((status) => status !== '') || Object.values(isBulkLoading).some((loading) => loading)
- );
+ const isAnyLoading = $derived(hasAnyLoadingState(actionStatus, isBulkLoading));
const selectedProjects = $derived.by(() => (projects?.data ?? []).filter((project) => selectedIds?.includes(project.id)));
const hasRedeployDisabledSelection = $derived.by(() => selectedProjects.some((project) => project.redeployDisabled));
const hasArchivedSelection = $derived.by(() => selectedProjects.some((project) => project.isArchived));
diff --git a/frontend/src/routes/(app)/settings/+page.svelte b/frontend/src/routes/(app)/settings/+page.svelte
index 2ddf90b07..1d33137b7 100644
--- a/frontend/src/routes/(app)/settings/+page.svelte
+++ b/frontend/src/routes/(app)/settings/+page.svelte
@@ -25,23 +25,24 @@
import { settingsSearchService } from '$lib/services/settings-search';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { SettingsCategory } from '$lib/types/shared';
- import { debounced } from '$lib/utils/ws';
import { canReachAccessSurface, canReachAccessSurfaceUrl } from '$lib/utils/access-policy';
import * as InputGroup from '$lib/components/ui/input-group/index.js';
import { getSettingsSubpageUrlsInNavOrder } from '$lib/config/navigation-config';
import HeaderCard from '$lib/components/header-card.svelte';
import { Spinner } from '$lib/components/ui/spinner/index.js';
+ import { useCategorySearch } from '$lib/hooks/use-category-search.svelte';
+ import { getCategoryIcon, orderCategoriesByNav } from '$lib/utils/category-page';
let { data }: PageProps = $props();
- let searchQuery = $state('');
- let showSearchResults = $state(false);
- let searchResults = $state<SettingsCategory[]>([]);
- let isSearching = $state(false);
let settingsCategories = $state<SettingsCategory[]>([]);
- let currentSearchRequest = $state(0);
const user = $derived(data.user);
const permissionsManifest = $derived(data.permissionsManifest);
+ const categorySearch = useCategorySearch<SettingsCategory>({
+ search: (query) => settingsSearchService.search(query),
+ filter: isAccessibleCategory,
+ onError: (error) => console.error('Search failed:', error)
+ });
const iconMap: Record<string, any> = {
settings: SettingsIcon,
@@ -60,47 +61,15 @@
onMount(async () => {
try {
- settingsCategories = orderCategoriesByNav((await settingsSearchService.getCategories()).filter(isAccessibleCategory));
+ settingsCategories = orderCategoriesByNav(
+ (await settingsSearchService.getCategories()).filter(isAccessibleCategory),
+ getSettingsSubpageUrlsInNavOrder()
+ );
} catch (error) {
console.error('Failed to load categories:', error);
}
});
- async function performSearch(query: string) {
- const trimmedQuery = query.trim();
-
- if (!trimmedQuery) {
- searchResults = [];
- showSearchResults = false;
- isSearching = false;
- currentSearchRequest++;
- return;
- }
-
- currentSearchRequest++;
- const requestId = currentSearchRequest;
- isSearching = true;
- showSearchResults = true;
-
- try {
- const response = await settingsSearchService.search(trimmedQuery);
- if (requestId === currentSearchRequest) {
- searchResults = (response.results || []).filter(isAccessibleCategory);
- isSearching = false;
- }
- } catch (error) {
- console.error('Search failed:', error);
- if (requestId === currentSearchRequest) {
- searchResults = [];
- isSearching = false;
- }
- }
- }
-
- const debouncedSearch = debounced((query: string) => {
- void performSearch(query);
- }, 300);
-
function navigateToCategory(categoryUrl: string) {
goto(categoryUrl);
}
@@ -120,29 +89,8 @@
return category.url;
}
- function orderCategoriesByNav(categories: SettingsCategory[]) {
- const navUrls = getSettingsSubpageUrlsInNavOrder();
- const categoriesByUrl = new Map(categories.map((category) => [category.url, category]));
- const orderedCategories = navUrls
- .map((url) => categoriesByUrl.get(url))
- .filter((category): category is SettingsCategory => Boolean(category));
- const unmatchedCategories = categories
- .filter((category) => !navUrls.includes(category.url))
- .sort((a, b) => a.title.localeCompare(b.title));
-
- return [...orderedCategories, ...unmatchedCategories];
- }
-
- function clearSearch() {
- searchQuery = '';
- showSearchResults = false;
- isSearching = false;
- searchResults = [];
- currentSearchRequest++;
- }
-
function getIconComponent(iconName: string) {
- return iconMap[iconName] || SettingsIcon;
+ return getCategoryIcon(iconMap, iconName, SettingsIcon);
}
</script>
@@ -169,24 +117,24 @@
<InputGroup.Root>
<InputGroup.Input
placeholder={m.settings_search_placeholder()}
- value={searchQuery}
+ value={categorySearch.searchQuery}
oninput={(e) => {
- searchQuery = e.currentTarget.value;
- debouncedSearch(e.currentTarget.value);
+ categorySearch.searchQuery = e.currentTarget.value;
+ categorySearch.debouncedSearch(e.currentTarget.value);
}}
onkeydown={(e) => {
if (e.key === 'Enter') {
- performSearch((e.currentTarget as HTMLInputElement).value);
+ categorySearch.performSearch((e.currentTarget as HTMLInputElement).value);
}
}}
/>
<InputGroup.Addon>
- {#if showSearchResults}
+ {#if categorySearch.showSearchResults}
<ArcaneButton
action="base"
tone="ghost"
size="sm"
- onclick={clearSearch}
+ onclick={categorySearch.clearSearch}
class="h-6 w-6 p-0"
icon={CloseIcon}
showLabel={false}
@@ -200,7 +148,7 @@
</div>
</HeaderCard>
- {#if !showSearchResults}
+ {#if !categorySearch.showSearchResults}
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-6 xl:grid-cols-3">
{#each settingsCategories as category (category.id)}
{@const Icon = getIconComponent(category.icon)}
@@ -228,16 +176,16 @@
<div class="space-y-6 sm:space-y-8">
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<h2 class="text-base font-semibold sm:text-lg">
- {m.settings_search_results({ query: searchQuery, count: searchResults.length })}
+ {m.settings_search_results({ query: categorySearch.searchQuery, count: categorySearch.searchResults.length })}
</h2>
</div>
- {#if isSearching}
+ {#if categorySearch.isSearching}
<div class="py-8 text-center sm:py-12">
<Spinner class="text-primary mx-auto mb-3 size-8 sm:mb-4 sm:size-12" />
<p class="text-muted-foreground text-sm sm:text-base">{m.settings_searching()}</p>
</div>
- {:else if searchResults.length === 0}
+ {:else if categorySearch.searchResults.length === 0}
<div class="py-8 text-center sm:py-12">
<SearchIcon class="text-muted-foreground mx-auto mb-3 size-8 sm:mb-4 sm:size-12" />
<h3 class="mb-2 text-base font-medium sm:text-lg">{m.settings_no_results()}</h3>
@@ -245,7 +193,7 @@
</div>
{:else}
<div class="space-y-4 sm:space-y-6">
- {#each searchResults as result (result.id)}
+ {#each categorySearch.searchResults as result (result.id)}
{@const Icon = getIconComponent(result.icon)}
<div class="bg-background/40 rounded-lg border">
<div class="border-b p-4 sm:p-6">
diff --git a/frontend/src/routes/(app)/settings/activity/+page.svelte b/frontend/src/routes/(app)/settings/activity/+page.svelte
index 60df08997..4df534121 100644
--- a/frontend/src/routes/(app)/settings/activity/+page.svelte
+++ b/frontend/src/routes/(app)/settings/activity/+page.svelte
@@ -7,7 +7,7 @@
import { Label } from '$lib/components/ui/label';
import { ActivityIcon } from '$lib/icons';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
- import { createSettingsForm } from '$lib/utils/settings';
+ import { createSettingsForm } from '$lib/utils/settings-form';
let { data } = $props();
diff --git a/frontend/src/routes/(app)/settings/activity/+page.ts b/frontend/src/routes/(app)/settings/activity/+page.ts
index 41fcb0fd6..84983f653 100644
--- a/frontend/src/routes/(app)/settings/activity/+page.ts
+++ b/frontend/src/routes/(app)/settings/activity/+page.ts
@@ -1,20 +1,6 @@
import type { PageLoad } from './$types';
-import { settingsService } from '$lib/services/settings-service';
-import { environmentStore } from '$lib/stores/environment.store.svelte';
-import { queryKeys } from '$lib/query/query-keys';
+import { loadMergedSettingsPage } from '$lib/utils/settings-load';
export const load: PageLoad = async ({ parent }) => {
- const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
-
- try {
- const settings = await queryClient.fetchQuery({
- queryKey: queryKeys.settings.byEnvironment(envId),
- queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
- });
- return { settings };
- } catch (error) {
- console.error('Failed to load activity settings:', error);
- throw error;
- }
+ return loadMergedSettingsPage(parent, 'activity settings');
};
diff --git a/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte b/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte
index 62a9694c5..7f79811ca 100644
--- a/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte
+++ b/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte
@@ -13,6 +13,7 @@
import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '$lib/components/arcane-table';
import { UniversalMobileCard } from '$lib/components/arcane-table';
import { apiKeyService } from '$lib/services/api-key-service';
+ import { formatOptionalDateTime, isPastDate } from '$lib/utils/formatting';
import * as m from '$lib/paraglide/messages.js';
import { ApiKeyIcon, TrashIcon, EditIcon, EllipsisIcon } from '$lib/icons';
import IfPermitted from '$lib/components/if-permitted.svelte';
@@ -35,23 +36,13 @@
removing: false
});
- function formatDate(dateString?: string): string {
- if (!dateString) return '-';
- return new Date(dateString).toLocaleString();
- }
-
- function isExpired(expiresAt?: string): boolean {
- if (!expiresAt) return false;
- return new Date(expiresAt) < new Date();
- }
-
function getStatusText(apiKey: ApiKey): string {
- if (isExpired(apiKey.expiresAt)) return m.api_key_status_expired();
+ if (isPastDate(apiKey.expiresAt)) return m.api_key_status_expired();
return m.api_key_status_active();
}
function getStatusVariant(apiKey: ApiKey): 'red' | 'green' {
- if (isExpired(apiKey.expiresAt)) return 'red';
+ if (isPastDate(apiKey.expiresAt)) return 'red';
return 'green';
}
@@ -200,7 +191,7 @@
{#snippet ExpiresCell({ item }: { item: ApiKey })}
<div class="flex items-center gap-2">
{#if item.expiresAt}
- <span class={isExpired(item.expiresAt) ? 'text-red-500' : ''}>{formatDate(item.expiresAt)}</span>
+ <span class={isPastDate(item.expiresAt) ? 'text-red-500' : ''}>{formatOptionalDateTime(item.expiresAt)}</span>
{:else}
<span class="text-muted-foreground">{m.api_key_expires_never()}</span>
{/if}
@@ -209,7 +200,7 @@
{/snippet}
{#snippet LastUsedCell({ item }: { item: ApiKey })}
- {formatDate(item.lastUsedAt)}
+ {formatOptionalDateTime(item.lastUsedAt)}
{/snippet}
{#snippet ApiKeyMobileCardSnippet({
@@ -240,14 +231,14 @@
},
{
label: m.api_key_expires_at(),
- getValue: (item: ApiKey) => (item.expiresAt ? formatDate(item.expiresAt) : m.api_key_expires_never()),
+ getValue: (item: ApiKey) => (item.expiresAt ? formatOptionalDateTime(item.expiresAt) : m.api_key_expires_never()),
icon: ApiKeyIcon,
iconVariant: 'gray' as const,
show: mobileFieldVisibility['expiresAt'] ?? true
},
{
label: m.api_key_last_used(),
- getValue: (item: ApiKey) => formatDate(item.lastUsedAt),
+ getValue: (item: ApiKey) => formatOptionalDateTime(item.lastUsedAt),
icon: ApiKeyIcon,
iconVariant: 'gray' as const,
show: mobileFieldVisibility['lastUsedAt'] ?? true
diff --git a/frontend/src/routes/(app)/settings/appearance/+page.svelte b/frontend/src/routes/(app)/settings/appearance/+page.svelte
index b00c65e8f..d18e65996 100644
--- a/frontend/src/routes/(app)/settings/appearance/+page.svelte
+++ b/frontend/src/routes/(app)/settings/appearance/+page.svelte
@@ -8,7 +8,7 @@
import { SettingsPageLayout } from '$lib/layouts';
import { Switch } from '$lib/components/ui/switch/index.js';
import { useSidebar } from '$lib/components/ui/sidebar/context.svelte.js';
- import { createSettingsForm } from '$lib/utils/settings';
+ import { createSettingsForm } from '$lib/utils/settings-form';
import SettingsRow from '$lib/components/settings/settings-row.svelte';
import LocalePicker from '$lib/components/locale-picker.svelte';
import AccentColorPicker from '$lib/components/accent-color/accent-color-picker.svelte';
diff --git a/frontend/src/routes/(app)/settings/authentication/+page.svelte b/frontend/src/routes/(app)/settings/authentication/+page.svelte
index 6191914d7..fd245f5b5 100644
--- a/frontend/src/routes/(app)/settings/authentication/+page.svelte
+++ b/frontend/src/routes/(app)/settings/authentication/+page.svelte
@@ -13,7 +13,7 @@
import settingsStore from '$lib/stores/config-store';
import { SettingsPageLayout } from '$lib/layouts';
import { CopyButton } from '$lib/components/ui/copy-button';
- import { createSettingsForm } from '$lib/utils/settings';
+ import { createSettingsForm } from '$lib/utils/settings-form';
import * as Alert from '$lib/components/ui/alert';
import * as Collapsible from '$lib/components/ui/collapsible';
import SettingsRow from '$lib/components/settings/settings-row.svelte';
diff --git a/frontend/src/routes/(app)/settings/authentication/federated-credential-table.svelte b/frontend/src/routes/(app)/settings/authentication/federated-credential-table.svelte
index a7e9fdb9d..77bee0c64 100644
--- a/frontend/src/routes/(app)/settings/authentication/federated-credential-table.svelte
+++ b/frontend/src/routes/(app)/settings/authentication/federated-credential-table.svelte
@@ -12,6 +12,7 @@
import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '$lib/components/arcane-table';
import { UniversalMobileCard } from '$lib/components/arcane-table';
import { federatedCredentialService } from '$lib/services/federated-credential-service';
+ import { formatOptionalDateTime, isPastDate } from '$lib/utils/formatting';
import * as m from '$lib/paraglide/messages.js';
import { LockIcon, TrashIcon, EditIcon, EllipsisIcon } from '$lib/icons';
import { isGlobalAdmin } from '$lib/utils/auth';
@@ -35,24 +36,14 @@
});
const canManageFederatedCredentials = $derived(isGlobalAdmin());
- function formatDate(dateString?: string): string {
- if (!dateString) return '-';
- return new Date(dateString).toLocaleString();
- }
-
- function isExpired(expiresAt?: string): boolean {
- if (!expiresAt) return false;
- return new Date(expiresAt) < new Date();
- }
-
function getStatusText(credential: FederatedCredential): string {
- if (isExpired(credential.expiresAt)) return m.federated_credential_status_expired();
+ if (isPastDate(credential.expiresAt)) return m.federated_credential_status_expired();
if (!credential.enabled) return m.common_disabled();
return m.common_enabled();
}
function getStatusVariant(credential: FederatedCredential): 'red' | 'green' | 'gray' {
- if (isExpired(credential.expiresAt)) return 'red';
+ if (isPastDate(credential.expiresAt)) return 'red';
if (!credential.enabled) return 'gray';
return 'green';
}
@@ -195,7 +186,7 @@
{/snippet}
{#snippet LastUsedCell({ item }: { item: FederatedCredential })}
- {formatDate(item.lastUsedAt)}
+ {formatOptionalDateTime(item.lastUsedAt)}
{/snippet}
{#snippet FederatedCredentialMobileCardSnippet({
@@ -233,7 +224,7 @@
},
{
label: m.federated_credential_last_used(),
- getValue: (item: FederatedCredential) => formatDate(item.lastUsedAt),
+ getValue: (item: FederatedCredential) => formatOptionalDateTime(item.lastUsedAt),
icon: LockIcon,
iconVariant: 'gray' as const,
show: mobileFieldVisibility['lastUsedAt'] ?? true
diff --git a/frontend/src/routes/(app)/settings/builds/+page.svelte b/frontend/src/routes/(app)/settings/builds/+page.svelte
index dcfaa6c7f..53e9d391b 100644
--- a/frontend/src/routes/(app)/settings/builds/+page.svelte
+++ b/frontend/src/routes/(app)/settings/builds/+page.svelte
@@ -7,7 +7,7 @@
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
import SelectWithLabel from '$lib/components/form/select-with-label.svelte';
import { m } from '$lib/paraglide/messages';
- import { createSettingsForm } from '$lib/utils/settings';
+ import { createSettingsForm } from '$lib/utils/settings-form';
import { settingsService } from '$lib/services/settings-service';
let { data } = $props();
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte
index 4a7c9ea20..239e23ecd 100644
--- a/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte
@@ -64,6 +64,24 @@
}
};
+ const eventSubscriptionSchemaFields = {
+ eventImageUpdate: z.boolean(),
+ eventContainerUpdate: z.boolean(),
+ eventVulnerabilityFound: z.boolean(),
+ eventPruneReport: z.boolean(),
+ eventAutoHeal: z.boolean()
+ };
+
+ function addCustomFieldIssue(ctx: z.RefinementCtx, path: string, message: string) {
+ ctx.addIssue({ code: 'custom', message, path: [path] });
+ }
+
+ function addRequiredTrimmedFieldIssue(ctx: z.RefinementCtx, value: string, path: string, message: string) {
+ if (!value.trim()) {
+ addCustomFieldIssue(ctx, path, message);
+ }
+ }
+
const providerSchemas: Record<NotificationProviderKey, z.ZodTypeAny> = {
discord: z
.object({
@@ -72,20 +90,12 @@
token: z.string(),
username: z.string(),
avatarUrl: z.string(),
- eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean(),
- eventVulnerabilityFound: z.boolean(),
- eventPruneReport: z.boolean(),
- eventAutoHeal: z.boolean()
+ ...eventSubscriptionSchemaFields
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
- if (!d.webhookId.trim()) {
- ctx.addIssue({ code: 'custom', message: 'Webhook ID is required when Discord is enabled', path: ['webhookId'] });
- }
- if (!d.token.trim()) {
- ctx.addIssue({ code: 'custom', message: 'Webhook Token is required when Discord is enabled', path: ['token'] });
- }
+ addRequiredTrimmedFieldIssue(ctx, d.webhookId, 'webhookId', 'Webhook ID is required when Discord is enabled');
+ addRequiredTrimmedFieldIssue(ctx, d.token, 'token', 'Webhook Token is required when Discord is enabled');
}),
email: z
.object({
@@ -98,11 +108,7 @@
toAddresses: z.string(),
tlsMode: z.enum(['none', 'starttls', 'ssl']),
authMode: z.enum(['auto', 'plain', 'login', 'crammd5']),
- eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean(),
- eventVulnerabilityFound: z.boolean(),
- eventPruneReport: z.boolean(),
- eventAutoHeal: z.boolean()
+ ...eventSubscriptionSchemaFields
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
@@ -150,17 +156,11 @@
preview: z.boolean(),
notification: z.boolean(),
title: z.string(),
- eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean(),
- eventVulnerabilityFound: z.boolean(),
- eventPruneReport: z.boolean(),
- eventAutoHeal: z.boolean()
+ ...eventSubscriptionSchemaFields
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
- if (!d.botToken.trim()) {
- ctx.addIssue({ code: 'custom', message: 'Bot Token is required when Telegram is enabled', path: ['botToken'] });
- }
+ addRequiredTrimmedFieldIssue(ctx, d.botToken, 'botToken', 'Bot Token is required when Telegram is enabled');
if (!d.chatIds.trim()) {
ctx.addIssue({
code: 'custom',
@@ -180,11 +180,7 @@
source: z.string(),
recipients: z.string(),
disableTls: z.boolean(),
- eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean(),
- eventVulnerabilityFound: z.boolean(),
- eventPruneReport: z.boolean(),
- eventAutoHeal: z.boolean()
+ ...eventSubscriptionSchemaFields
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
@@ -234,17 +230,11 @@
title: z.string(),
channel: z.string(),
threadTs: z.string(),
- eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean(),
- eventVulnerabilityFound: z.boolean(),
- eventPruneReport: z.boolean(),
- eventAutoHeal: z.boolean()
+ ...eventSubscriptionSchemaFields
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
- if (!d.token.trim()) {
- ctx.addIssue({ code: 'custom', message: m.notifications_slack_token_required(), path: ['token'] });
- }
+ addRequiredTrimmedFieldIssue(ctx, d.token, 'token', m.notifications_slack_token_required());
}),
ntfy: z
.object({
@@ -261,19 +251,13 @@
cache: z.boolean(),
firebase: z.boolean(),
disableTlsVerification: z.boolean(),
- eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean(),
- eventVulnerabilityFound: z.boolean(),
- eventPruneReport: z.boolean(),
- eventAutoHeal: z.boolean()
+ ...eventSubscriptionSchemaFields
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
- if (!d.topic.trim()) {
- ctx.addIssue({ code: 'custom', message: 'Topic is required when Ntfy is enabled', path: ['topic'] });
- }
+ addRequiredTrimmedFieldIssue(ctx, d.topic, 'topic', 'Topic is required when Ntfy is enabled');
if (d.port > 0 && (d.port < 1 || d.port > 65535)) {
- ctx.addIssue({ code: 'custom', message: 'Port must be between 1 and 65535', path: ['port'] });
+ addCustomFieldIssue(ctx, 'port', 'Port must be between 1 and 65535');
}
}),
pushover: z
@@ -284,20 +268,12 @@
devices: z.string(),
priority: z.coerce.number().int().min(-2).max(2),
title: z.string(),
- eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean(),
- eventVulnerabilityFound: z.boolean(),
- eventPruneReport: z.boolean(),
- eventAutoHeal: z.boolean()
+ ...eventSubscriptionSchemaFields
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
- if (!d.token.trim()) {
- ctx.addIssue({ code: 'custom', message: m.common_required(), path: ['token'] });
- }
- if (!d.user.trim()) {
- ctx.addIssue({ code: 'custom', message: m.common_required(), path: ['user'] });
- }
+ addRequiredTrimmedFieldIssue(ctx, d.token, 'token', m.common_required());
+ addRequiredTrimmedFieldIssue(ctx, d.user, 'user', m.common_required());
}),
gotify: z
.object({
@@ -309,20 +285,12 @@
priority: z.coerce.number().int(),
title: z.string(),
disableTls: z.boolean(),
- eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean(),
- eventVulnerabilityFound: z.boolean(),
- eventPruneReport: z.boolean(),
- eventAutoHeal: z.boolean()
+ ...eventSubscriptionSchemaFields
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
- if (!d.host.trim()) {
- ctx.addIssue({ code: 'custom', message: m.common_required(), path: ['host'] });
- }
- if (!d.token.trim()) {
- ctx.addIssue({ code: 'custom', message: m.common_required(), path: ['token'] });
- }
+ addRequiredTrimmedFieldIssue(ctx, d.host, 'host', m.common_required());
+ addRequiredTrimmedFieldIssue(ctx, d.token, 'token', m.common_required());
}),
matrix: z
.object({
@@ -333,17 +301,11 @@
username: z.string(),
password: z.string(),
disableTlsVerification: z.boolean(),
- eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean(),
- eventVulnerabilityFound: z.boolean(),
- eventPruneReport: z.boolean(),
- eventAutoHeal: z.boolean()
+ ...eventSubscriptionSchemaFields
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
- if (!d.host.trim()) {
- ctx.addIssue({ code: 'custom', message: m.common_required(), path: ['host'] });
- }
+ addRequiredTrimmedFieldIssue(ctx, d.host, 'host', m.common_required());
}),
generic: z
.object({
@@ -354,21 +316,11 @@
titleKey: z.string(),
messageKey: z.string(),
customHeaders: z.string(),
- eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean(),
- eventVulnerabilityFound: z.boolean(),
- eventPruneReport: z.boolean(),
- eventAutoHeal: z.boolean()
+ ...eventSubscriptionSchemaFields
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
- if (!d.webhookUrl.trim()) {
- ctx.addIssue({
- code: 'custom',
- message: 'Webhook URL is required when Generic Webhook is enabled',
- path: ['webhookUrl']
- });
- }
+ addRequiredTrimmedFieldIssue(ctx, d.webhookUrl, 'webhookUrl', 'Webhook URL is required when Generic Webhook is enabled');
})
};
diff --git a/frontend/src/routes/(app)/settings/roles/[id]/+page.svelte b/frontend/src/routes/(app)/settings/roles/[id]/+page.svelte
index 7aa43ac78..82ba82a27 100644
--- a/frontend/src/routes/(app)/settings/roles/[id]/+page.svelte
+++ b/frontend/src/routes/(app)/settings/roles/[id]/+page.svelte
@@ -3,12 +3,10 @@
import { goto } from '$app/navigation';
import { handleApiResultWithCallbacks } from '$lib/utils/api';
import { tryCatch } from '$lib/utils/api';
- import RoleEditor from '$lib/components/role-editor/role-editor.svelte';
import type { UpdateRole, CreateRole } from '$lib/types/auth';
import { m } from '$lib/paraglide/messages';
import { roleService } from '$lib/services/role-service';
- import { SettingsPageLayout } from '$lib/layouts/index.js';
- import { ShieldAlertIcon } from '$lib/icons';
+ import RoleEditorPage from '../role-editor-page.svelte';
let { data } = $props();
@@ -49,8 +47,11 @@
}
</script>
-<SettingsPageLayout title={m.roles_edit_title()} description={m.roles_subtitle()} icon={ShieldAlertIcon} pageType="form">
- {#snippet mainContent()}
- <RoleEditor role={data.role} manifest={data.permissionsManifest} {isLoading} onSubmit={handleSubmit} onClone={handleClone} />
- {/snippet}
-</SettingsPageLayout>
+<RoleEditorPage
+ title={m.roles_edit_title()}
+ role={data.role}
+ manifest={data.permissionsManifest}
+ {isLoading}
+ onSubmit={handleSubmit}
+ onClone={handleClone}
+/>
diff --git a/frontend/src/routes/(app)/settings/roles/new/+page.svelte b/frontend/src/routes/(app)/settings/roles/new/+page.svelte
index 4606e491f..ff380caaa 100644
--- a/frontend/src/routes/(app)/settings/roles/new/+page.svelte
+++ b/frontend/src/routes/(app)/settings/roles/new/+page.svelte
@@ -3,12 +3,10 @@
import { goto } from '$app/navigation';
import { handleApiResultWithCallbacks } from '$lib/utils/api';
import { tryCatch } from '$lib/utils/api';
- import RoleEditor from '$lib/components/role-editor/role-editor.svelte';
import type { CreateRole } from '$lib/types/auth';
import { m } from '$lib/paraglide/messages';
import { roleService } from '$lib/services/role-service';
- import { SettingsPageLayout } from '$lib/layouts/index.js';
- import { ShieldAlertIcon } from '$lib/icons';
+ import RoleEditorPage from '../role-editor-page.svelte';
let { data } = $props();
@@ -29,8 +27,10 @@
}
</script>
-<SettingsPageLayout title={m.roles_create_title()} description={m.roles_subtitle()} icon={ShieldAlertIcon} pageType="form">
- {#snippet mainContent()}
- <RoleEditor role={null} manifest={data.permissionsManifest} {isLoading} onSubmit={handleSubmit} />
- {/snippet}
-</SettingsPageLayout>
+<RoleEditorPage
+ title={m.roles_create_title()}
+ role={null}
+ manifest={data.permissionsManifest}
+ {isLoading}
+ onSubmit={handleSubmit}
+/>
diff --git a/frontend/src/routes/(app)/settings/roles/role-editor-page.svelte b/frontend/src/routes/(app)/settings/roles/role-editor-page.svelte
new file mode 100644
index 000000000..d3dea0a17
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/roles/role-editor-page.svelte
@@ -0,0 +1,24 @@
+<script lang="ts">
+ import RoleEditor from '$lib/components/role-editor/role-editor.svelte';
+ import { SettingsPageLayout } from '$lib/layouts/index.js';
+ import { ShieldAlertIcon } from '$lib/icons';
+ import { m } from '$lib/paraglide/messages';
+ import type { CreateRole, PermissionsManifest, Role, UpdateRole } from '$lib/types/auth';
+
+ type Props = {
+ title: string;
+ role: Role | null;
+ manifest: PermissionsManifest;
+ isLoading?: boolean;
+ onSubmit: (payload: CreateRole | UpdateRole) => void | Promise<void>;
+ onClone?: () => void | Promise<void>;
+ };
+
+ let { title, role, manifest, isLoading = false, onSubmit, onClone }: Props = $props();
+</script>
+
+<SettingsPageLayout {title} description={m.roles_subtitle()} icon={ShieldAlertIcon} pageType="form">
+ {#snippet mainContent()}
+ <RoleEditor {role} {manifest} {isLoading} {onSubmit} {onClone} />
+ {/snippet}
+</SettingsPageLayout>
diff --git a/frontend/src/routes/(app)/settings/timeouts/+page.svelte b/frontend/src/routes/(app)/settings/timeouts/+page.svelte
index 9c8560f6a..62f9e7dc5 100644
--- a/frontend/src/routes/(app)/settings/timeouts/+page.svelte
+++ b/frontend/src/routes/(app)/settings/timeouts/+page.svelte
@@ -6,7 +6,7 @@
import { SettingsPageLayout } from '$lib/layouts';
import { ClockIcon } from '$lib/icons';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
- import { createSettingsForm } from '$lib/utils/settings';
+ import { createSettingsForm } from '$lib/utils/settings-form';
let { data } = $props();
diff --git a/frontend/src/routes/(app)/settings/timeouts/+page.ts b/frontend/src/routes/(app)/settings/timeouts/+page.ts
index fb604d1dc..166ffe700 100644
--- a/frontend/src/routes/(app)/settings/timeouts/+page.ts
+++ b/frontend/src/routes/(app)/settings/timeouts/+page.ts
@@ -1,20 +1,6 @@
import type { PageLoad } from './$types';
-import { settingsService } from '$lib/services/settings-service';
-import { environmentStore } from '$lib/stores/environment.store.svelte';
-import { queryKeys } from '$lib/query/query-keys';
+import { loadMergedSettingsPage } from '$lib/utils/settings-load';
export const load: PageLoad = async ({ parent }) => {
- const { queryClient } = await parent();
- const envId = await environmentStore.getCurrentEnvironmentId();
-
- try {
- const settings = await queryClient.fetchQuery({
- queryKey: queryKeys.settings.byEnvironment(envId),
- queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
- });
- return { settings };
- } catch (error) {
- console.error('Failed to load timeout settings:', error);
- throw error;
- }
+ return loadMergedSettingsPage(parent, 'timeout settings');
};
diff --git a/frontend/src/routes/(app)/swarm/configs/+page.svelte b/frontend/src/routes/(app)/swarm/configs/+page.svelte
index 4b42774eb..898cfb20f 100644
--- a/frontend/src/routes/(app)/swarm/configs/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/configs/+page.svelte
@@ -1,272 +1,46 @@
<script lang="ts">
- import * as Card from '$lib/components/ui/card';
- import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { Input } from '$lib/components/ui/input/index.js';
- import { Textarea } from '$lib/components/ui/textarea/index.js';
- import { CopyButton } from '$lib/components/ui/copy-button';
- import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';
- import { TemplateIcon, TrashIcon } from '$lib/icons';
- import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
+ import SwarmKvPage from '$lib/components/swarm/swarm-kv-page.svelte';
+ import { TemplateIcon } from '$lib/icons';
import { m } from '$lib/paraglide/messages';
import { swarmService } from '$lib/services/swarm-service';
- import { hasPermission } from '$lib/utils/auth';
import { environmentStore } from '$lib/stores/environment.store.svelte';
- import type { SwarmConfigSummary } from '$lib/types/swarm';
- import { handleApiResultWithCallbacks } from '$lib/utils/api';
- import { tryCatch } from '$lib/utils/api';
- import { toast } from 'svelte-sonner';
- import { formatDistanceToNow } from 'date-fns';
- import { openConfirmDialog } from '$lib/components/confirm-dialog';
- import IfPermitted from '$lib/components/if-permitted.svelte';
+ import { hasPermission } from '$lib/utils/auth';
let {}: PageProps = $props();
const currentEnvId = $derived(environmentStore.selected?.id);
const canManageConfigs = $derived(hasPermission('swarm:configs', currentEnvId));
- let configs = $state<SwarmConfigSummary[]>([]);
- let selectedConfigId = $state('');
- let createName = $state('');
- let createData = $state('');
- let editName = $state('');
- let editData = $state('');
- let isLoading = $state({
- refresh: false,
- create: false,
- delete: false
- });
-
- function getSpecName(spec: Record<string, unknown> | null | undefined, fallback: string): string {
- const name = spec && typeof spec === 'object' ? (spec as Record<string, unknown>)['Name'] : undefined;
- return typeof name === 'string' && name.trim() ? name : fallback.slice(0, 12);
- }
-
- function decodeBase64ToText(base64Value: string): string {
- try {
- const binary = atob(base64Value);
- const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
- return new TextDecoder().decode(bytes);
- } catch {
- return '';
- }
- }
-
- function encodeTextToBase64(value: string): string {
- const bytes = new TextEncoder().encode(value);
- let binary = '';
- for (const byte of bytes) {
- binary += String.fromCharCode(byte);
- }
- return btoa(binary);
- }
-
- function formatTimestamp(timestamp: string): string {
- if (!timestamp) return m.common_unknown();
- return formatDistanceToNow(new Date(timestamp), { addSuffix: true });
- }
-
- function selectConfig(config: SwarmConfigSummary) {
- selectedConfigId = config.id;
- const spec = (config.spec ?? {}) as Record<string, unknown>;
- editName = typeof spec['Name'] === 'string' ? spec['Name'] : '';
- editData = typeof spec['Data'] === 'string' ? decodeBase64ToText(spec['Data']) : '';
- }
-
- function clearSelectedConfig() {
- selectedConfigId = '';
- editName = '';
- editData = '';
- }
-
- function toggleConfig(config: SwarmConfigSummary) {
- if (selectedConfigId === config.id) {
- clearSelectedConfig();
- return;
- }
-
- selectConfig(config);
- }
-
- async function refresh() {
- isLoading.refresh = true;
- try {
- configs = await swarmService.getConfigs();
- if (selectedConfigId && !configs.some((config) => config.id === selectedConfigId)) {
- clearSelectedConfig();
- }
- } finally {
- isLoading.refresh = false;
- }
- }
-
- useEnvironmentRefresh(refresh);
-
- $effect(() => {
- refresh();
- });
-
- async function createConfig() {
- const name = createName.trim();
- if (!name) {
- toast.error(m.swarm_configs_name_required());
- return;
- }
- const spec: Record<string, unknown> = {
- Name: name,
- Data: encodeTextToBase64(createData)
- };
-
- handleApiResultWithCallbacks({
- result: await tryCatch(swarmService.createConfig({ spec })),
- message: m.swarm_configs_create_failed(),
- setLoadingState: (value) => (isLoading.create = value),
- onSuccess: async (created) => {
- toast.success(m.swarm_configs_create_success({ name: getSpecName(created.spec, created.id) }));
- createName = '';
- createData = '';
- await refresh();
- selectConfig(created);
- }
- });
- }
-
- function removeConfig(config: SwarmConfigSummary) {
- const name = getSpecName(config.spec, config.id);
- openConfirmDialog({
- title: m.common_delete_title({ resource: m.swarm_config() }),
- message: m.swarm_configs_delete_confirm({ name }),
- confirm: {
- label: m.common_delete(),
- destructive: true,
- action: async () => {
- handleApiResultWithCallbacks({
- result: await tryCatch(swarmService.removeConfig(config.id)),
- message: m.swarm_configs_delete_failed({ name }),
- setLoadingState: (value) => (isLoading.delete = value),
- onSuccess: async () => {
- toast.success(m.swarm_configs_delete_success({ name }));
- await refresh();
- }
- });
- }
- }
- });
- }
-
- const actionButtons: ActionButton[] = $derived([
- {
- id: 'refresh',
- action: 'restart',
- label: m.common_refresh(),
- onclick: refresh,
- loading: isLoading.refresh,
- disabled: isLoading.refresh
- }
- ]);
-
- const statCards: StatCardConfig[] = $derived([
- {
- title: m.swarm_configs_title(),
- value: configs.length,
- icon: TemplateIcon,
- iconColor: 'text-blue-500'
- }
- ]);
+ const messages = {
+ pageTitle: m.swarm_configs_title(),
+ pageSubtitle: m.swarm_configs_subtitle(),
+ statTitle: m.swarm_configs_title(),
+ createTitle: m.swarm_configs_create_title(),
+ createSubtitle: m.swarm_configs_create_subtitle(),
+ namePlaceholder: m.swarm_configs_name_placeholder(),
+ dataPlaceholder: m.swarm_configs_data_placeholder(),
+ createButton: m.swarm_configs_create_button(),
+ listTitle: m.swarm_configs_list_title(),
+ listSubtitle: m.swarm_configs_list_subtitle(),
+ empty: m.swarm_configs_empty(),
+ immutableNotice: m.swarm_configs_immutable_notice(),
+ deleteButton: m.swarm_configs_delete_button(),
+ nameRequired: m.swarm_configs_name_required(),
+ createFailed: m.swarm_configs_create_failed(),
+ createSuccess: (name: string) => m.swarm_configs_create_success({ name }),
+ deleteConfirm: (name: string) => m.swarm_configs_delete_confirm({ name }),
+ deleteFailed: (name: string) => m.swarm_configs_delete_failed({ name }),
+ deleteSuccess: (name: string) => m.swarm_configs_delete_success({ name })
+ };
</script>
-<ResourcePageLayout
- title={m.swarm_configs_title()}
- subtitle={m.swarm_configs_subtitle()}
+<SwarmKvPage
icon={TemplateIcon}
- {actionButtons}
- {statCards}
->
- {#snippet mainContent()}
- <div class="grid gap-4 lg:grid-cols-[1fr,1.1fr]">
- <Card.Root class="pt-0">
- <Card.Header>
- <Card.Title>{m.swarm_configs_create_title()}</Card.Title>
- <Card.Description>{m.swarm_configs_create_subtitle()}</Card.Description>
- </Card.Header>
- <Card.Content class="space-y-3 pb-6">
- <Input placeholder={m.swarm_configs_name_placeholder()} bind:value={createName} />
- <Textarea
- rows={10}
- bind:value={createData}
- placeholder={m.swarm_configs_data_placeholder()}
- class="font-mono text-xs"
- />
- <IfPermitted perm="swarm:configs">
- <ArcaneButton
- action="create"
- customLabel={m.swarm_configs_create_button()}
- onclick={createConfig}
- disabled={!canManageConfigs || isLoading.create}
- loading={isLoading.create}
- />
- </IfPermitted>
- </Card.Content>
- </Card.Root>
-
- <div class="space-y-4">
- <Card.Root class="pt-0">
- <Card.Header>
- <Card.Title>{m.swarm_configs_list_title()}</Card.Title>
- <Card.Description>{m.swarm_configs_list_subtitle()}</Card.Description>
- </Card.Header>
- <Card.Content class="space-y-3 pb-6">
- {#if configs.length === 0}
- <div class="text-muted-foreground py-8 text-center text-sm">{m.swarm_configs_empty()}</div>
- {:else}
- {#each configs as config (config.id)}
- <Card.Root class="overflow-hidden border py-0">
- <button
- type="button"
- class={`w-full px-4 py-3 text-left transition-colors ${selectedConfigId === config.id ? 'bg-muted/50' : 'hover:bg-muted/40'}`}
- onclick={() => toggleConfig(config)}
- >
- <div class="flex items-center justify-between gap-2">
- <div class="min-w-0">
- <div class="truncate font-medium">{getSpecName(config.spec, config.id)}</div>
- <div class="text-muted-foreground font-mono text-xs">{config.id}</div>
- </div>
- <div class="text-muted-foreground shrink-0 text-xs">{formatTimestamp(config.updatedAt)}</div>
- </div>
- </button>
-
- {#if selectedConfigId === config.id}
- <div class="space-y-3 border-t px-4 pt-4 pb-5">
- <div class="flex items-center gap-2">
- <div class="text-muted-foreground font-mono text-xs">{config.id}</div>
- <CopyButton text={config.id} />
- </div>
- <p class="text-muted-foreground text-sm">{m.swarm_configs_immutable_notice()}</p>
- <Input placeholder={m.swarm_configs_name_placeholder()} bind:value={editName} readonly />
- <Textarea
- rows={12}
- bind:value={editData}
- placeholder={m.swarm_configs_data_placeholder()}
- class="font-mono text-xs"
- readonly
- />
- <div class="flex flex-wrap items-center gap-2 pt-1">
- <ArcaneButton
- action="remove"
- customLabel={m.swarm_configs_delete_button()}
- icon={TrashIcon}
- onclick={() => removeConfig(config)}
- disabled={!canManageConfigs || isLoading.delete}
- loading={isLoading.delete}
- />
- </div>
- </div>
- {/if}
- </Card.Root>
- {/each}
- {/if}
- </Card.Content>
- </Card.Root>
- </div>
- </div>
- {/snippet}
-</ResourcePageLayout>
+ permission="swarm:configs"
+ resourceLabel={m.swarm_config()}
+ canManage={canManageConfigs}
+ {messages}
+ loadItems={() => swarmService.getConfigs()}
+ createItem={(spec) => swarmService.createConfig({ spec })}
+ removeItem={(id) => swarmService.removeConfig(id)}
+/>
diff --git a/frontend/src/routes/(app)/swarm/secrets/+page.svelte b/frontend/src/routes/(app)/swarm/secrets/+page.svelte
index c446fadda..110cf3124 100644
--- a/frontend/src/routes/(app)/swarm/secrets/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/secrets/+page.svelte
@@ -1,272 +1,46 @@
<script lang="ts">
- import * as Card from '$lib/components/ui/card';
- import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { Input } from '$lib/components/ui/input/index.js';
- import { Textarea } from '$lib/components/ui/textarea/index.js';
- import { CopyButton } from '$lib/components/ui/copy-button';
- import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';
- import { LockIcon, TrashIcon } from '$lib/icons';
- import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
+ import SwarmKvPage from '$lib/components/swarm/swarm-kv-page.svelte';
+ import { LockIcon } from '$lib/icons';
import { m } from '$lib/paraglide/messages';
import { swarmService } from '$lib/services/swarm-service';
- import { hasPermission } from '$lib/utils/auth';
import { environmentStore } from '$lib/stores/environment.store.svelte';
- import type { SwarmSecretSummary } from '$lib/types/swarm';
- import { handleApiResultWithCallbacks } from '$lib/utils/api';
- import { tryCatch } from '$lib/utils/api';
- import { toast } from 'svelte-sonner';
- import { formatDistanceToNow } from 'date-fns';
- import { openConfirmDialog } from '$lib/components/confirm-dialog';
- import IfPermitted from '$lib/components/if-permitted.svelte';
+ import { hasPermission } from '$lib/utils/auth';
let {}: PageProps = $props();
const currentEnvId = $derived(environmentStore.selected?.id);
const canManageSecrets = $derived(hasPermission('swarm:secrets', currentEnvId));
- let secrets = $state<SwarmSecretSummary[]>([]);
- let selectedSecretId = $state('');
- let createName = $state('');
- let createData = $state('');
- let editName = $state('');
- let editData = $state('');
- let isLoading = $state({
- refresh: false,
- create: false,
- delete: false
- });
-
- function getSpecName(spec: Record<string, unknown> | null | undefined, fallback: string): string {
- const name = spec && typeof spec === 'object' ? (spec as Record<string, unknown>)['Name'] : undefined;
- return typeof name === 'string' && name.trim() ? name : fallback.slice(0, 12);
- }
-
- function decodeBase64ToText(base64Value: string): string {
- try {
- const binary = atob(base64Value);
- const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
- return new TextDecoder().decode(bytes);
- } catch {
- return '';
- }
- }
-
- function encodeTextToBase64(value: string): string {
- const bytes = new TextEncoder().encode(value);
- let binary = '';
- for (const byte of bytes) {
- binary += String.fromCharCode(byte);
- }
- return btoa(binary);
- }
-
- function formatTimestamp(timestamp: string): string {
- if (!timestamp) return m.common_unknown();
- return formatDistanceToNow(new Date(timestamp), { addSuffix: true });
- }
-
- function selectSecret(secret: SwarmSecretSummary) {
- selectedSecretId = secret.id;
- const spec = (secret.spec ?? {}) as Record<string, unknown>;
- editName = typeof spec['Name'] === 'string' ? spec['Name'] : '';
- editData = typeof spec['Data'] === 'string' ? decodeBase64ToText(spec['Data']) : '';
- }
-
- function clearSelectedSecret() {
- selectedSecretId = '';
- editName = '';
- editData = '';
- }
-
- function toggleSecret(secret: SwarmSecretSummary) {
- if (selectedSecretId === secret.id) {
- clearSelectedSecret();
- return;
- }
-
- selectSecret(secret);
- }
-
- async function refresh() {
- isLoading.refresh = true;
- try {
- secrets = await swarmService.getSecrets();
- if (selectedSecretId && !secrets.some((secret) => secret.id === selectedSecretId)) {
- clearSelectedSecret();
- }
- } finally {
- isLoading.refresh = false;
- }
- }
-
- useEnvironmentRefresh(refresh);
-
- $effect(() => {
- refresh();
- });
-
- async function createSecret() {
- const name = createName.trim();
- if (!name) {
- toast.error(m.swarm_secrets_name_required());
- return;
- }
- const spec: Record<string, unknown> = {
- Name: name,
- Data: encodeTextToBase64(createData)
- };
-
- handleApiResultWithCallbacks({
- result: await tryCatch(swarmService.createSecret({ spec })),
- message: m.swarm_secrets_create_failed(),
- setLoadingState: (value) => (isLoading.create = value),
- onSuccess: async (created) => {
- toast.success(m.swarm_secrets_create_success({ name: getSpecName(created.spec, created.id) }));
- createName = '';
- createData = '';
- await refresh();
- selectSecret(created);
- }
- });
- }
-
- function removeSecret(secret: SwarmSecretSummary) {
- const name = getSpecName(secret.spec, secret.id);
- openConfirmDialog({
- title: m.common_delete_title({ resource: m.swarm_secret() }),
- message: m.swarm_secrets_delete_confirm({ name }),
- confirm: {
- label: m.common_delete(),
- destructive: true,
- action: async () => {
- handleApiResultWithCallbacks({
- result: await tryCatch(swarmService.removeSecret(secret.id)),
- message: m.swarm_secrets_delete_failed({ name }),
- setLoadingState: (value) => (isLoading.delete = value),
- onSuccess: async () => {
- toast.success(m.swarm_secrets_delete_success({ name }));
- await refresh();
- }
- });
- }
- }
- });
- }
-
- const actionButtons: ActionButton[] = $derived([
- {
- id: 'refresh',
- action: 'restart',
- label: m.common_refresh(),
- onclick: refresh,
- loading: isLoading.refresh,
- disabled: isLoading.refresh
- }
- ]);
-
- const statCards: StatCardConfig[] = $derived([
- {
- title: m.swarm_secrets_title(),
- value: secrets.length,
- icon: LockIcon,
- iconColor: 'text-blue-500'
- }
- ]);
+ const messages = {
+ pageTitle: m.swarm_secrets_title(),
+ pageSubtitle: m.swarm_secrets_subtitle(),
+ statTitle: m.swarm_secrets_title(),
+ createTitle: m.swarm_secrets_create_title(),
+ createSubtitle: m.swarm_secrets_create_subtitle(),
+ namePlaceholder: m.swarm_secrets_name_placeholder(),
+ dataPlaceholder: m.swarm_secrets_data_placeholder(),
+ createButton: m.swarm_secrets_create_button(),
+ listTitle: m.swarm_secrets_list_title(),
+ listSubtitle: m.swarm_secrets_list_subtitle(),
+ empty: m.swarm_secrets_empty(),
+ immutableNotice: m.swarm_secrets_immutable_notice(),
+ deleteButton: m.swarm_secrets_delete_button(),
+ nameRequired: m.swarm_secrets_name_required(),
+ createFailed: m.swarm_secrets_create_failed(),
+ createSuccess: (name: string) => m.swarm_secrets_create_success({ name }),
+ deleteConfirm: (name: string) => m.swarm_secrets_delete_confirm({ name }),
+ deleteFailed: (name: string) => m.swarm_secrets_delete_failed({ name }),
+ deleteSuccess: (name: string) => m.swarm_secrets_delete_success({ name })
+ };
</script>
-<ResourcePageLayout
- title={m.swarm_secrets_title()}
- subtitle={m.swarm_secrets_subtitle()}
+<SwarmKvPage
icon={LockIcon}
- {actionButtons}
- {statCards}
->
- {#snippet mainContent()}
- <div class="grid gap-4 lg:grid-cols-[1fr,1.1fr]">
- <Card.Root class="pt-0">
- <Card.Header>
- <Card.Title>{m.swarm_secrets_create_title()}</Card.Title>
- <Card.Description>{m.swarm_secrets_create_subtitle()}</Card.Description>
- </Card.Header>
- <Card.Content class="space-y-3 pb-6">
- <Input placeholder={m.swarm_secrets_name_placeholder()} bind:value={createName} />
- <Textarea
- rows={10}
- bind:value={createData}
- placeholder={m.swarm_secrets_data_placeholder()}
- class="font-mono text-xs"
- />
- <IfPermitted perm="swarm:secrets">
- <ArcaneButton
- action="create"
- customLabel={m.swarm_secrets_create_button()}
- onclick={createSecret}
- disabled={!canManageSecrets || isLoading.create}
- loading={isLoading.create}
- />
- </IfPermitted>
- </Card.Content>
- </Card.Root>
-
- <div class="space-y-4">
- <Card.Root class="pt-0">
- <Card.Header>
- <Card.Title>{m.swarm_secrets_list_title()}</Card.Title>
- <Card.Description>{m.swarm_secrets_list_subtitle()}</Card.Description>
- </Card.Header>
- <Card.Content class="space-y-3 pb-6">
- {#if secrets.length === 0}
- <div class="text-muted-foreground py-8 text-center text-sm">{m.swarm_secrets_empty()}</div>
- {:else}
- {#each secrets as secret (secret.id)}
- <Card.Root class="overflow-hidden border py-0">
- <button
- type="button"
- class={`w-full px-4 py-3 text-left transition-colors ${selectedSecretId === secret.id ? 'bg-muted/50' : 'hover:bg-muted/40'}`}
- onclick={() => toggleSecret(secret)}
- >
- <div class="flex items-center justify-between gap-2">
- <div class="min-w-0">
- <div class="truncate font-medium">{getSpecName(secret.spec, secret.id)}</div>
- <div class="text-muted-foreground font-mono text-xs">{secret.id}</div>
- </div>
- <div class="text-muted-foreground shrink-0 text-xs">{formatTimestamp(secret.updatedAt)}</div>
- </div>
- </button>
-
- {#if selectedSecretId === secret.id}
- <div class="space-y-3 border-t px-4 pt-4 pb-5">
- <div class="flex items-center gap-2">
- <div class="text-muted-foreground font-mono text-xs">{secret.id}</div>
- <CopyButton text={secret.id} />
- </div>
- <p class="text-muted-foreground text-sm">{m.swarm_secrets_immutable_notice()}</p>
- <Input placeholder={m.swarm_secrets_name_placeholder()} bind:value={editName} readonly />
- <Textarea
- rows={12}
- bind:value={editData}
- placeholder={m.swarm_secrets_data_placeholder()}
- class="font-mono text-xs"
- readonly
- />
- <div class="flex flex-wrap items-center gap-2 pt-1">
- <ArcaneButton
- action="remove"
- customLabel={m.swarm_secrets_delete_button()}
- icon={TrashIcon}
- onclick={() => removeSecret(secret)}
- disabled={!canManageSecrets || isLoading.delete}
- loading={isLoading.delete}
- />
- </div>
- </div>
- {/if}
- </Card.Root>
- {/each}
- {/if}
- </Card.Content>
- </Card.Root>
- </div>
- </div>
- {/snippet}
-</ResourcePageLayout>
+ permission="swarm:secrets"
+ resourceLabel={m.swarm_secret()}
+ canManage={canManageSecrets}
+ {messages}
+ loadItems={() => swarmService.getSecrets()}
+ createItem={(spec) => swarmService.createSecret({ spec })}
+ removeItem={(id) => swarmService.removeSecret(id)}
+/>
diff --git a/frontend/src/routes/(app)/swarm/services/+page.svelte b/frontend/src/routes/(app)/swarm/services/+page.svelte
index 91d9050aa..6b34bcdc6 100644
--- a/frontend/src/routes/(app)/swarm/services/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/services/+page.svelte
@@ -6,9 +6,10 @@
import { untrack } from 'svelte';
import { tryCatch } from '$lib/utils/api';
import { handleApiResultWithCallbacks } from '$lib/utils/api';
- import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
+ import { ResourcePageLayout, type StatCardConfig } from '$lib/layouts/index.js';
import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';
import { parallelRefresh } from '$lib/utils/api';
+ import { createRefreshActionButtons } from '$lib/utils/resource-actions';
import type { SwarmServiceCreateSpec } from '$lib/types/swarm';
import SwarmServicesTable from './services-table.svelte';
import CreateServiceDialog from '$lib/components/dialogs/create-service-dialog.svelte';
@@ -57,26 +58,16 @@
});
}
- const actionButtons: ActionButton[] = $derived.by(() => {
- const buttons: ActionButton[] = [];
- if (canCreateService) {
- buttons.push({
- id: 'create',
- action: 'create',
- label: m.common_create_button({ resource: m.swarm_service() }),
- onclick: () => (showCreateDialog = true)
- });
- }
- buttons.push({
- id: 'refresh',
- action: 'restart',
- label: m.common_refresh(),
- onclick: refresh,
- loading: isLoading.refresh,
- disabled: isLoading.refresh
- });
- return buttons;
- });
+ const actionButtons = $derived.by(() =>
+ createRefreshActionButtons({
+ canCreate: canCreateService,
+ createLabel: m.common_create_button({ resource: m.swarm_service() }),
+ onCreate: () => (showCreateDialog = true),
+ refreshLabel: m.common_refresh(),
+ onRefresh: refresh,
+ refreshing: isLoading.refresh
+ })
+ );
const statCards: StatCardConfig[] = $derived([
{
diff --git a/frontend/src/routes/(app)/swarm/services/+page.ts b/frontend/src/routes/(app)/swarm/services/+page.ts
index 76d107c28..aaa4df284 100644
--- a/frontend/src/routes/(app)/swarm/services/+page.ts
+++ b/frontend/src/routes/(app)/swarm/services/+page.ts
@@ -1,19 +1,12 @@
import { swarmService } from '$lib/services/swarm-service';
-import type { SearchPaginationSortRequest } from '$lib/types/shared';
-import { resolveInitialTableRequest } from '$lib/utils/tables';
+import { resolveInitialListPageRequest } from '$lib/utils/tables';
import type { PageLoad } from './$types';
export const load: PageLoad = async () => {
- const requestOptions = resolveInitialTableRequest('arcane-swarm-services-table', {
- pagination: {
- page: 1,
- limit: 20
- },
- sort: {
- column: 'name',
- direction: 'asc'
- }
- } satisfies SearchPaginationSortRequest);
+ const requestOptions = resolveInitialListPageRequest('arcane-swarm-services-table', {
+ column: 'name',
+ direction: 'asc'
+ });
const services = await swarmService.getServices(requestOptions);
diff --git a/frontend/src/routes/(app)/swarm/services/components/ServiceLogsPanel.svelte b/frontend/src/routes/(app)/swarm/services/components/ServiceLogsPanel.svelte
index 61868bd31..1e041bbca 100644
--- a/frontend/src/routes/(app)/swarm/services/components/ServiceLogsPanel.svelte
+++ b/frontend/src/routes/(app)/swarm/services/components/ServiceLogsPanel.svelte
@@ -3,6 +3,7 @@
import LogViewer from '$lib/components/logs/log-viewer.svelte';
import LogControls from '$lib/components/logs/log-controls.svelte';
import { m } from '$lib/paraglide/messages';
+ import { refreshLogViewerStream, startLogViewerStream, stopLogViewerStream } from '$lib/utils/log-viewer';
import { FileTextIcon } from '$lib/icons';
let {
@@ -18,15 +19,15 @@
let showParsedJson = $state(false);
function handleStart() {
- viewer?.startLogStream();
+ startLogViewerStream(viewer);
}
function handleStop() {
- viewer?.stopLogStream();
+ stopLogViewerStream(viewer);
}
async function handleRefresh() {
- await viewer?.clearLogs({ hard: true, restart: true });
+ await refreshLogViewerStream(viewer);
}
function handleStreamStart() {
diff --git a/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte b/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte
index d028d1963..4e04160d5 100644
--- a/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte
+++ b/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte
@@ -5,6 +5,7 @@
import { m } from '$lib/paraglide/messages';
import { swarmService } from '$lib/services/swarm-service';
import type { SwarmTaskSummary } from '$lib/types/swarm';
+ import { getSwarmTaskStateVariant, sortSwarmTasks } from '$lib/utils/swarm-tasks';
import { JobsIcon, ConnectionIcon } from '$lib/icons';
let {
@@ -19,42 +20,13 @@
let isLoading = $state(false);
let hasLoaded = $state(false);
- const STATE_ORDER: Record<string, number> = {
- running: 0,
- starting: 1,
- pending: 2,
- ready: 3,
- complete: 4,
- shutdown: 5,
- failed: 6,
- rejected: 7,
- orphaned: 8,
- remove: 9
- };
-
- function stateVariant(state: string): 'green' | 'amber' | 'red' | 'gray' {
- if (state === 'running') return 'green';
- if (state === 'pending' || state === 'starting') return 'amber';
- if (state === 'failed' || state === 'rejected' || state === 'shutdown') return 'red';
- return 'gray';
- }
-
- function sortTasks(raw: SwarmTaskSummary[]): SwarmTaskSummary[] {
- return [...raw].sort((a, b) => {
- const stateA = STATE_ORDER[a.currentState] ?? 99;
- const stateB = STATE_ORDER[b.currentState] ?? 99;
- if (stateA !== stateB) return stateA - stateB;
- return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
- });
- }
-
async function loadTasks() {
isLoading = true;
try {
const result = await swarmService.getServiceTasks(serviceId, {
pagination: { page: 1, limit: 100 }
});
- tasks = sortTasks(result.data ?? []);
+ tasks = sortSwarmTasks(result.data ?? []);
} catch (err) {
console.error(m.swarm_service_tasks_load_failed_log(), err);
} finally {
@@ -108,7 +80,7 @@
</div>
<div class="text-muted-foreground font-mono text-xs">{task.id.slice(0, 12)}</div>
</div>
- <StatusBadge text={task.currentState} variant={stateVariant(task.currentState)} />
+ <StatusBadge text={task.currentState} variant={getSwarmTaskStateVariant(task.currentState)} />
</div>
<div class="grid grid-cols-2 gap-2">
<div>
@@ -124,7 +96,7 @@
<div class="text-muted-foreground mb-1 text-xs font-semibold">
{m.swarm_desired_state()}
</div>
- <StatusBadge text={task.desiredState} variant={stateVariant(task.desiredState)} size="sm" />
+ <StatusBadge text={task.desiredState} variant={getSwarmTaskStateVariant(task.desiredState)} size="sm" />
</div>
{#if task.error}
<div class="col-span-2">
diff --git a/frontend/src/routes/(app)/swarm/stacks/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/+page.svelte
index 22f32d73d..1fb20e79c 100644
--- a/frontend/src/routes/(app)/swarm/stacks/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/stacks/+page.svelte
@@ -3,9 +3,10 @@
import { m } from '$lib/paraglide/messages';
import { swarmService } from '$lib/services/swarm-service';
import { untrack } from 'svelte';
- import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
+ import { ResourcePageLayout, type StatCardConfig } from '$lib/layouts/index.js';
import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';
import { parallelRefresh } from '$lib/utils/api';
+ import { createRefreshActionButtons } from '$lib/utils/resource-actions';
import SwarmStacksTable from './stacks-table.svelte';
import { goto } from '$app/navigation';
import { hasPermission } from '$lib/utils/auth';
@@ -39,26 +40,16 @@
const currentEnvId = $derived(environmentStore.selected?.id);
const canCreateStack = $derived(hasPermission('swarm:stacks', currentEnvId));
- const actionButtons: ActionButton[] = $derived.by(() => {
- const buttons: ActionButton[] = [];
- if (canCreateStack) {
- buttons.push({
- id: 'create',
- action: 'create',
- label: m.common_create_button({ resource: m.swarm_stack() }),
- onclick: () => goto('/swarm/stacks/new')
- });
- }
- buttons.push({
- id: 'refresh',
- action: 'restart',
- label: m.common_refresh(),
- onclick: refresh,
- loading: isLoading.refresh,
- disabled: isLoading.refresh
- });
- return buttons;
- });
+ const actionButtons = $derived.by(() =>
+ createRefreshActionButtons({
+ canCreate: canCreateStack,
+ createLabel: m.common_create_button({ resource: m.swarm_stack() }),
+ onCreate: () => goto('/swarm/stacks/new'),
+ refreshLabel: m.common_refresh(),
+ onRefresh: refresh,
+ refreshing: isLoading.refresh
+ })
+ );
const statCards: StatCardConfig[] = $derived([
{
diff --git a/frontend/src/routes/(app)/swarm/stacks/+page.ts b/frontend/src/routes/(app)/swarm/stacks/+page.ts
index cd0269f20..519d8e207 100644
--- a/frontend/src/routes/(app)/swarm/stacks/+page.ts
+++ b/frontend/src/routes/(app)/swarm/stacks/+page.ts
@@ -1,19 +1,12 @@
import { swarmService } from '$lib/services/swarm-service';
-import type { SearchPaginationSortRequest } from '$lib/types/shared';
-import { resolveInitialTableRequest } from '$lib/utils/tables';
+import { resolveInitialListPageRequest } from '$lib/utils/tables';
import type { PageLoad } from './$types';
export const load: PageLoad = async () => {
- const requestOptions = resolveInitialTableRequest('arcane-swarm-stacks-table', {
- pagination: {
- page: 1,
- limit: 20
- },
- sort: {
- column: 'name',
- direction: 'asc'
- }
- } satisfies SearchPaginationSortRequest);
+ const requestOptions = resolveInitialListPageRequest('arcane-swarm-stacks-table', {
+ column: 'name',
+ direction: 'asc'
+ });
const stacks = await swarmService.getStacks(requestOptions);
diff --git a/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte
index b4fd16efd..0bd078bf3 100644
--- a/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte
@@ -1,64 +1,52 @@
<script lang="ts">
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import { Spinner } from '$lib/components/ui/spinner/index.js';
- import { Label } from '$lib/components/ui/label/index.js';
import { goto, invalidateAll } from '$app/navigation';
import { toast } from 'svelte-sonner';
import { preventDefault, createForm } from '$lib/utils/settings';
- import { tryCatch } from '$lib/utils/api';
- import { handleApiResultWithCallbacks } from '$lib/utils/api';
- import { Textarea } from '$lib/components/ui/textarea/index.js';
- import * as Dialog from '$lib/components/ui/dialog/index.js';
import * as ArcaneTooltip from '$lib/components/arcane-tooltip';
import TemplateSelectionDialog from '$lib/components/dialogs/template-selection-dialog.svelte';
- import type { Template } from '$lib/types/swarm';
- import { z } from 'zod/v4';
- import { arcaneButtonVariants, actionConfigs } from '$lib/components/arcane-button/variants';
import { m } from '$lib/paraglide/messages';
import { swarmService } from '$lib/services/swarm-service.js';
- import { systemService } from '$lib/services/system-service.js';
- import { templateService } from '$lib/services/template-service.js';
import * as ButtonGroup from '$lib/components/ui/button-group/index.js';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
- import {
- ArrowLeftIcon,
- TerminalIcon,
- CopyIcon,
- TemplateIcon,
- AddIcon,
- ArrowDownIcon as ChevronDown,
- GitBranchIcon
- } from '$lib/icons';
+ import { ArrowLeftIcon, TerminalIcon, TemplateIcon, AddIcon, ArrowDownIcon as ChevronDown, GitBranchIcon } from '$lib/icons';
import CodePanel from '../../../projects/components/CodePanel.svelte';
import EditableName from '../../../projects/components/EditableName.svelte';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { ComposeEditorSplit } from '$lib/components/compose';
+ import DockerRunConverterDialog from '$lib/components/compose/docker-run-converter-dialog.svelte';
+ import { globalVariablesToMap } from '$lib/utils/template-load';
+ import {
+ createComposeEditorSchema,
+ createComposeTemplateDialogFlow,
+ dropdownContentClass,
+ dropdownItemClass,
+ submitComposeResourceForm,
+ templateBtnClass,
+ templateNameSlug
+ } from '$lib/utils/compose-flow';
let { data } = $props();
- let saving = $state(false);
- let converting = $state(false);
- let creatingTemplate = $state(false);
- let showTemplateDialog = $state(false);
- let showConverterDialog = $state(false);
- let isLoadingTemplateContent = $state(false);
+ let ui = $state({
+ saving: false,
+ converting: false,
+ creatingTemplate: false,
+ showTemplateDialog: false,
+ showConverterDialog: false,
+ isLoadingTemplateContent: false
+ });
const isEditMode = $derived(data.isEditMode === true);
- const formSchema = z.object({
- name: z
- .string()
- .min(1, m.common_name_required())
- .regex(/^[a-z0-9-_]+$/i, m.compose_project_name_invalid()),
- composeContent: z.string().min(1, m.compose_compose_content_required()),
- envContent: z.string().optional().default('')
- });
+ const formSchema = createComposeEditorSchema(m.common_name_required());
function getInitialName() {
if (data.sourceStackName) {
return data.sourceStackName;
}
if (data.selectedTemplate) {
- return data.selectedTemplate.name.toLowerCase().replace(/[^a-z0-9-_]/g, '-');
+ return templateNameSlug(data.selectedTemplate.name);
}
return '';
}
@@ -78,14 +66,11 @@
const { inputs, ...form } = createForm<typeof formSchema>(formSchema, getInitialFormData());
- let dockerRunCommand = $state('');
let composeOpen = $state(true);
let envOpen = $state(true);
let nameInputRef = $state<HTMLInputElement | null>(null);
- const globalVariableMap = $derived.by(() =>
- Object.fromEntries((data.globalVariables ?? []).map((item) => [item.key, item.value]))
- );
+ const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));
async function handleSubmit() {
if (isEditMode) {
@@ -96,16 +81,12 @@
}
async function handleDeployStack() {
- const validated = form.validate();
- if (!validated) return;
-
- const { name, composeContent, envContent } = validated;
-
- handleApiResultWithCallbacks({
- result: await tryCatch(swarmService.deployStack({ name, composeContent, envContent })),
- message: m.common_create_failed({ resource: `${m.swarm_stack()} "${name}"` }),
- setLoadingState: (value) => (saving = value),
- onSuccess: async () => {
+ await submitComposeResourceForm({
+ validate: form.validate,
+ setLoading: (value) => (ui.saving = value),
+ submit: ({ name, composeContent, envContent }) => swarmService.deployStack({ name, composeContent, envContent }),
+ failureMessage: (name) => m.common_create_failed({ resource: `${m.swarm_stack()} "${name}"` }),
+ onSuccess: async (_result, { name }) => {
toast.success(m.common_create_success({ resource: `${m.swarm_stack()} "${name}"` }));
goto('/swarm/stacks', { invalidateAll: true });
}
@@ -113,102 +94,28 @@
}
async function handleSaveStackSource() {
- const validated = form.validate();
- if (!validated) return;
-
- const { name, composeContent, envContent } = validated;
-
- handleApiResultWithCallbacks({
- result: await tryCatch(swarmService.deployStack({ name, composeContent, envContent })),
- message: m.common_update_failed({ resource: `${m.swarm_stack()} "${name}"` }),
- setLoadingState: (value) => (saving = value),
- onSuccess: async () => {
+ await submitComposeResourceForm({
+ validate: form.validate,
+ setLoading: (value) => (ui.saving = value),
+ submit: ({ name, composeContent, envContent }) => swarmService.deployStack({ name, composeContent, envContent }),
+ failureMessage: (name) => m.common_update_failed({ resource: `${m.swarm_stack()} "${name}"` }),
+ onSuccess: async (_result, { name }) => {
toast.success(m.common_update_success({ resource: `${m.swarm_stack()} "${name}"` }));
goto(`/swarm/stacks/${encodeURIComponent(name)}`, { invalidateAll: true });
}
});
}
- async function handleConvertDockerRun() {
- if (!dockerRunCommand.trim()) {
- toast.error(m.compose_enter_docker_run_command());
- return;
- }
-
- handleApiResultWithCallbacks({
- result: await tryCatch(systemService.convert(dockerRunCommand)),
- message: m.compose_convert_failed(),
- setLoadingState: (value) => (converting = value),
- onSuccess: (data) => {
- $inputs.composeContent.value = data.dockerCompose;
- $inputs.envContent.value = data.envVars;
- $inputs.name.value = data.serviceName;
-
- toast.success(m.compose_convert_success());
- dockerRunCommand = '';
- showConverterDialog = false;
- }
- });
- }
-
- async function handleTemplateSelect(template: Template) {
- showTemplateDialog = false;
-
- $inputs.composeContent.value = template.content ?? '';
- $inputs.envContent.value = template.envContent ?? '';
-
- if (!$inputs.name.value?.trim()) {
- $inputs.name.value = template.name.toLowerCase().replace(/[^a-z0-9-_]/g, '-');
- }
- toast.success(m.compose_template_loaded({ name: template.name }));
- }
-
- const exampleCommands = [m.compose_example_command_1(), m.compose_example_command_2(), m.compose_example_command_3()];
-
- function useExample(command: string) {
- dockerRunCommand = command;
- }
-
- async function handleCreateTemplate() {
- const validated = form.validate();
- if (!validated) return;
-
- const { name, composeContent, envContent } = validated;
-
- handleApiResultWithCallbacks({
- result: await tryCatch(
- templateService.createTemplate({
- name,
- content: composeContent,
- envContent
- })
- ),
- message: m.common_create_failed({ resource: `${m.resource_template()} "${name}"` }),
- setLoadingState: (value) => (creatingTemplate = value),
- onSuccess: async () => {
- toast.success(m.common_create_success({ resource: `${m.resource_template()} "${name}"` }));
- }
- });
- }
-
- const templateBtnClass = arcaneButtonVariants({
- tone: actionConfigs.template?.tone ?? 'outline-primary',
- size: 'default',
- hoverEffect: 'none'
+ const { composeHandlers, handleCreateTemplate } = createComposeTemplateDialogFlow({
+ getInputs: () => $inputs,
+ setInputValue: (key, value) => form.setValue(key, value),
+ closeTemplateDialog: () => (ui.showTemplateDialog = false),
+ validate: form.validate,
+ setLoading: (value) => (ui.creatingTemplate = value)
});
- const dropdownContentClass =
- 'arcane-dd-content min-w-[220px] overflow-visible rounded-lg border border-primary/30 bg-background/95 ' +
- 'backdrop-blur supports-[backdrop-filter]:bg-background/80 ring-1 ring-inset ring-primary/20 shadow-sm p-1';
-
- const dropdownItemClass =
- 'flex cursor-pointer select-none items-center gap-2 rounded-md px-3 py-2 text-sm ' +
- 'text-foreground/90 outline-none transition-colors ' +
- 'hover:bg-primary/10 focus:bg-primary/10 ' +
- 'data-[disabled]:opacity-50 data-[disabled]:pointer-events-none';
-
const canSubmit = $derived(
- !!$inputs.name.value && !!$inputs.composeContent.value && !saving && !converting && !isLoadingTemplateContent
+ !!$inputs.name.value && !!$inputs.composeContent.value && !ui.saving && !ui.converting && !ui.isLoadingTemplateContent
);
</script>
@@ -234,7 +141,7 @@
error={$inputs.name.error ?? undefined}
originalValue={initialName}
placeholder={m.compose_project_name_placeholder?.() || 'Enter name...'}
- canEdit={!isEditMode && !saving && !isLoadingTemplateContent}
+ canEdit={!isEditMode && !ui.saving && !ui.isLoadingTemplateContent}
class="hidden sm:block"
/>
</div>
@@ -243,7 +150,7 @@
<div class="flex items-center gap-2">
<ButtonGroup.Root>
<ArcaneTooltip.Root
- open={!$inputs.name.value && !saving && !converting && !isLoadingTemplateContent ? undefined : false}
+ open={!$inputs.name.value && !ui.saving && !ui.converting && !ui.isLoadingTemplateContent ? undefined : false}
>
<ArcaneTooltip.Trigger>
<span>
@@ -253,7 +160,7 @@
disabled={!canSubmit}
onclick={() => handleSubmit()}
class={`${templateBtnClass} gap-2 rounded-r-none`}
- loading={saving}
+ loading={ui.saving}
customLabel={submitLabel}
loadingLabel={submitLoadingLabel}
/>
@@ -286,13 +193,13 @@
<DropdownMenu.Group>
<DropdownMenu.Item
class={dropdownItemClass}
- disabled={saving || converting || isLoadingTemplateContent}
- onclick={() => (showTemplateDialog = true)}
+ disabled={ui.saving || ui.converting || ui.isLoadingTemplateContent}
+ onclick={() => (ui.showTemplateDialog = true)}
>
<TemplateIcon class="size-4" />
{m.common_use_template()}
</DropdownMenu.Item>
- <DropdownMenu.Item class={dropdownItemClass} onclick={() => (showConverterDialog = true)}>
+ <DropdownMenu.Item class={dropdownItemClass} onclick={() => (ui.showConverterDialog = true)}>
<TerminalIcon class="size-4" />
{m.compose_convert_from_docker_run()}
</DropdownMenu.Item>
@@ -309,10 +216,10 @@
<DropdownMenu.Separator />
<DropdownMenu.Item
class={dropdownItemClass}
- disabled={!canSubmit || creatingTemplate}
+ disabled={!canSubmit || ui.creatingTemplate}
onclick={handleCreateTemplate}
>
- {#if creatingTemplate}
+ {#if ui.creatingTemplate}
<Spinner class="size-4" />
{:else}
<AddIcon class="size-4" />
@@ -338,7 +245,7 @@
error={$inputs.name.error ?? undefined}
originalValue={initialName}
placeholder={m.compose_project_name_placeholder()}
- canEdit={!isEditMode && !saving && !isLoadingTemplateContent}
+ canEdit={!isEditMode && !ui.saving && !ui.isLoadingTemplateContent}
/>
</div>
@@ -383,60 +290,15 @@
</div>
</div>
-<Dialog.Root bind:open={showConverterDialog}>
- <Dialog.Content class="max-h-[80vh] sm:max-w-[800px]">
- <Dialog.Header>
- <Dialog.Title>{m.compose_converter_title()}</Dialog.Title>
- <Dialog.Description>{m.compose_converter_description()}</Dialog.Description>
- </Dialog.Header>
-
- <div class="max-h-[60vh] space-y-4 overflow-y-auto">
- <div class="space-y-2">
- <Label for="dockerRunCommand">{m.compose_docker_run_command_label()}</Label>
- <Textarea
- id="dockerRunCommand"
- bind:value={dockerRunCommand}
- placeholder={m.compose_docker_run_placeholder()}
- rows={3}
- disabled={converting}
- class="font-mono text-sm"
- />
- </div>
-
- <div class="space-y-2">
- <Label class="text-muted-foreground text-xs">{m.compose_example_commands_label()}</Label>
- <div class="space-y-1">
- {#each exampleCommands as command (command)}
- <ArcaneButton
- action="base"
- tone="ghost"
- size="sm"
- class="h-auto w-full justify-start p-2 text-left font-mono text-xs break-all whitespace-normal"
- onclick={() => useExample(command)}
- icon={CopyIcon}
- customLabel={command}
- />
- {/each}
- </div>
- </div>
- </div>
-
- <div class="flex w-full justify-end pt-4">
- <ArcaneButton
- action="create"
- disabled={!dockerRunCommand.trim() || converting}
- onclick={handleConvertDockerRun}
- loading={converting}
- customLabel={m.compose_convert_action()}
- loadingLabel={m.compose_converting()}
- />
- </div>
- </Dialog.Content>
-</Dialog.Root>
+<DockerRunConverterDialog
+ bind:open={ui.showConverterDialog}
+ bind:converting={ui.converting}
+ onConverted={composeHandlers.handleDockerRunConverted}
+/>
<TemplateSelectionDialog
- bind:open={showTemplateDialog}
+ bind:open={ui.showTemplateDialog}
templates={data.composeTemplates || []}
- onSelect={handleTemplateSelect}
+ onSelect={composeHandlers.handleTemplateSelect}
onDownloadSuccess={invalidateAll}
/>
diff --git a/frontend/src/routes/(app)/swarm/tasks/tasks-table.svelte b/frontend/src/routes/(app)/swarm/tasks/tasks-table.svelte
index 195dcc750..689531f88 100644
--- a/frontend/src/routes/(app)/swarm/tasks/tasks-table.svelte
+++ b/frontend/src/routes/(app)/swarm/tasks/tasks-table.svelte
@@ -8,6 +8,7 @@
import type { SwarmTaskSummary } from '$lib/types/swarm';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { getSwarmTaskIconVariant, getSwarmTaskStateVariant } from '$lib/utils/swarm-tasks';
let {
tasks = $bindable(),
@@ -21,20 +22,6 @@
persistKey?: string;
} = $props();
- function stateVariant(state: string): 'green' | 'amber' | 'red' | 'gray' {
- if (state === 'running') return 'green';
- if (state === 'pending' || state === 'starting') return 'amber';
- if (state === 'failed' || state === 'rejected' || state === 'shutdown') return 'red';
- return 'gray';
- }
-
- function iconVariant(state: string): 'emerald' | 'amber' | 'red' | 'gray' {
- if (state === 'running') return 'emerald';
- if (state === 'pending' || state === 'starting') return 'amber';
- if (state === 'failed' || state === 'rejected' || state === 'shutdown') return 'red';
- return 'gray';
- }
-
const columns = [
{ accessorKey: 'id', title: m.common_id(), hidden: true },
{ accessorKey: 'name', title: m.common_name(), sortable: true },
@@ -55,11 +42,11 @@
</script>
{#snippet StateCell({ value }: { value: unknown })}
- <StatusBadge text={String(value ?? m.common_unknown())} variant={stateVariant(String(value ?? ''))} />
+ <StatusBadge text={String(value ?? m.common_unknown())} variant={getSwarmTaskStateVariant(String(value ?? ''))} />
{/snippet}
{#snippet DesiredStateCell({ value }: { value: unknown })}
- <StatusBadge text={String(value ?? m.common_unknown())} variant={stateVariant(String(value ?? ''))} />
+ <StatusBadge text={String(value ?? m.common_unknown())} variant={getSwarmTaskStateVariant(String(value ?? ''))} />
{/snippet}
{#snippet TaskMobileCardSnippet({
@@ -73,14 +60,14 @@
{item}
icon={() => ({
component: JobsIcon,
- variant: iconVariant(item.currentState)
+ variant: getSwarmTaskIconVariant(item.currentState)
})}
title={(item: SwarmTaskSummary) => item.name}
subtitle={(item: SwarmTaskSummary) => ((mobileFieldVisibility['serviceName'] ?? true) ? item.serviceName : null)}
badges={[
(item: SwarmTaskSummary) =>
(mobileFieldVisibility['currentState'] ?? true)
- ? { variant: stateVariant(item.currentState), text: item.currentState }
+ ? { variant: getSwarmTaskStateVariant(item.currentState), text: item.currentState }
: null
]}
fields={[
diff --git a/frontend/src/routes/(app)/updates/container-updates-table.svelte b/frontend/src/routes/(app)/updates/container-updates-table.svelte
index 37afce6cb..a8e71c06d 100644
--- a/frontend/src/routes/(app)/updates/container-updates-table.svelte
+++ b/frontend/src/routes/(app)/updates/container-updates-table.svelte
@@ -1,22 +1,17 @@
<script lang="ts">
- import { format } from 'date-fns';
import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { openConfirmDialog } from '$lib/components/confirm-dialog';
import { UniversalMobileCard, type ColumnSpec, type MobileFieldVisibility } from '$lib/components/arcane-table';
import { m } from '$lib/paraglide/messages';
- import { toast } from 'svelte-sonner';
import type { SearchPaginationSortRequest, Paginated } from '$lib/types/shared';
import type { ContainerSummaryDto } from '$lib/types/docker';
import type { ImageUpdateInfoDto } from '$lib/types/docker';
- import {
- containerService,
- type ContainersPaginatedResponse,
- type ContainerListRequestOptions
- } from '$lib/services/container-service';
+ import type { ContainersPaginatedResponse, ContainerListRequestOptions } from '$lib/services/container-service';
import { ContainersIcon, UpdateIcon } from '$lib/icons';
import { getContainerDisplayName } from '../containers/container-table.helpers';
import IfPermitted from '$lib/components/if-permitted.svelte';
+ import { confirmAndUpdateContainer } from '$lib/utils/container-actions';
+ import { formatImageUpdateCheckedAt, formatImageUpdateValue } from '$lib/utils/image-updates';
type ContainerUpdateRow = {
id: string;
@@ -42,33 +37,14 @@
let mobileFieldVisibility = $state<MobileFieldVisibility>({});
let updatingContainerIds = $state<Record<string, boolean>>({});
- function formatUpdateValue(updateInfo: ImageUpdateInfoDto | undefined, mode: 'current' | 'latest') {
- if (!updateInfo) return '-';
-
- const digest = mode === 'current' ? updateInfo.currentDigest : updateInfo.latestDigest;
- if (digest?.trim()) return digest.trim();
-
- const version = mode === 'current' ? updateInfo.currentVersion : updateInfo.latestVersion;
- if (version?.trim()) return version.trim();
-
- return '-';
- }
-
- function formatCheckedAt(value: string) {
- if (!value) return '-';
- const parsed = new Date(value);
- if (Number.isNaN(parsed.getTime())) return '-';
- return format(parsed, 'PP p');
- }
-
function mapContainerRow(container: ContainerSummaryDto): ContainerUpdateRow {
return {
id: container.id,
containerId: container.id,
name: getContainerDisplayName(container),
imageRef: container.image,
- currentValue: formatUpdateValue(container.updateInfo, 'current'),
- latestValue: formatUpdateValue(container.updateInfo, 'latest'),
+ currentValue: formatImageUpdateValue(container.updateInfo, 'current'),
+ latestValue: formatImageUpdateValue(container.updateInfo, 'latest'),
checkedAt: container.updateInfo?.checkTime ?? '',
updateInfo: container.updateInfo,
container
@@ -100,39 +76,16 @@
async function handleUpdateContainer(container: ContainerSummaryDto) {
const containerName = getContainerDisplayName(container);
- openConfirmDialog({
- title: m.containers_update_confirm_title(),
- message: m.containers_update_confirm_message({ name: containerName }),
- confirm: {
- label: m.containers_update_container(),
- destructive: false,
- action: async () => {
- updatingContainerIds = { ...updatingContainerIds, [container.id]: true };
- try {
- toast.info(m.containers_update_pulling_image());
-
- const result = await containerService.updateContainer(container.id);
-
- if (result.failed > 0) {
- const failedItem = result.items?.find((item: { status?: string; error?: string }) => item.status === 'failed');
- toast.error(
- m.containers_update_failed({ name: containerName }) + (failedItem?.error ? `: ${failedItem.error}` : '')
- );
- } else if (result.updated > 0) {
- toast.success(m.containers_update_success({ name: containerName }));
- } else {
- toast.info(m.image_update_up_to_date_title());
- }
-
- const next = await onRefreshData(requestOptions as ContainerListRequestOptions);
- containers = next;
- } catch (error) {
- console.error('Container update failed:', error);
- toast.error(m.containers_update_failed({ name: containerName }));
- } finally {
- updatingContainerIds = { ...updatingContainerIds, [container.id]: false };
- }
- }
+ confirmAndUpdateContainer({
+ containerId: container.id,
+ containerName,
+ showPullingToast: true,
+ setLoading: (loading) => {
+ updatingContainerIds = { ...updatingContainerIds, [container.id]: loading };
+ },
+ onRefresh: async () => {
+ const next = await onRefreshData(requestOptions as ContainerListRequestOptions);
+ containers = next;
}
});
}
@@ -156,7 +109,7 @@
{/snippet}
{#snippet CheckedAtCell({ value }: { value: unknown })}
- <span class="text-sm">{formatCheckedAt(typeof value === 'string' ? value : '')}</span>
+ <span class="text-sm">{formatImageUpdateCheckedAt(typeof value === 'string' ? value : '')}</span>
{/snippet}
{#snippet ActionsCell({ item }: { item: ContainerUpdateRow })}
@@ -193,7 +146,7 @@
},
{
label: m.common_updated(),
- getValue: (item: ContainerUpdateRow) => formatCheckedAt(item.checkedAt)
+ getValue: (item: ContainerUpdateRow) => formatImageUpdateCheckedAt(item.checkedAt)
},
{
label: m.common_actions(),
diff --git a/frontend/src/routes/(app)/updates/project-updates-table.svelte b/frontend/src/routes/(app)/updates/project-updates-table.svelte
index be48e2823..fc5407f5e 100644
--- a/frontend/src/routes/(app)/updates/project-updates-table.svelte
+++ b/frontend/src/routes/(app)/updates/project-updates-table.svelte
@@ -1,5 +1,4 @@
<script lang="ts">
- import { format } from 'date-fns';
import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';
import { UniversalMobileCard, type ColumnSpec, type MobileFieldVisibility } from '$lib/components/arcane-table';
import { m } from '$lib/paraglide/messages';
@@ -7,6 +6,7 @@
import type { Project } from '$lib/types/swarm';
import type { ImageUpdateInfoDto } from '$lib/types/docker';
import { ProjectsIcon, ImagesIcon } from '$lib/icons';
+ import { formatImageUpdateCheckedAt, formatImageUpdateValue } from '$lib/utils/image-updates';
type ProjectUpdateRow = {
id: string;
@@ -31,13 +31,6 @@
let selectedIds = $state<string[]>([]);
let mobileFieldVisibility = $state<MobileFieldVisibility>({});
- function formatCheckedAt(value: string) {
- if (!value) return '-';
- const parsed = new Date(value);
- if (Number.isNaN(parsed.getTime())) return '-';
- return format(parsed, 'PP p');
- }
-
function summarizeImageRefs(imageRefs: string[]): string {
if (imageRefs.length === 0) return '-';
if (imageRefs.length === 1) return imageRefs[0] ?? '-';
@@ -55,13 +48,7 @@
const info = firstRef ? updateInfoByRef[firstRef] : undefined;
if (!info) return '-';
- const digest = mode === 'current' ? info.currentDigest : info.latestDigest;
- if (digest?.trim()) return digest.trim();
-
- const version = mode === 'current' ? info.currentVersion : info.latestVersion;
- if (version?.trim()) return version.trim();
-
- return '-';
+ return formatImageUpdateValue(info, mode);
}
function resolveCheckedAt(project: Project) {
@@ -135,7 +122,7 @@
{/snippet}
{#snippet CheckedAtCell({ value }: { value: unknown })}
- <span class="text-sm">{formatCheckedAt(typeof value === 'string' ? value : '')}</span>
+ <span class="text-sm">{formatImageUpdateCheckedAt(typeof value === 'string' ? value : '')}</span>
{/snippet}
{#snippet ProjectUpdatesMobileCard({ item }: { item: ProjectUpdateRow })}
@@ -158,7 +145,7 @@
},
{
label: m.common_updated(),
- getValue: (item: ProjectUpdateRow) => formatCheckedAt(item.checkedAt)
+ getValue: (item: ProjectUpdateRow) => formatImageUpdateCheckedAt(item.checkedAt)
}
]}
onclick={(item: ProjectUpdateRow) => {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7cd959a4b..441d0ae09 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -103,9 +103,6 @@ importers:
'@lezer/highlight':
specifier: ^1.2.3
version: 1.2.3
- '@sveltejs/adapter-static':
- specifier: ^3.0.10
'@sveltejs/kit':
specifier: ^2.61.1
@@ -176,6 +173,9 @@ importers:
'@prettier/plugin-oxc':
specifier: ^0.1.4
version: 0.1.4
+ '@sveltejs/adapter-static':
+ specifier: ^3.0.10
'@sveltejs/vite-plugin-svelte':
specifier: ^7.1.2
@@ -197,15 +197,15 @@ importers:
clsx:
specifier: ^2.1.1
version: 2.1.1
+ fallow:
+ specifier: ^2.89.0
+ version: 2.89.0
formsnap:
specifier: ^2.0.1
isomorphic-dompurify:
specifier: ^3.15.0
version: 3.15.0
- knip:
- specifier: ^6.15.0
- version: 6.15.0
mode-watcher:
specifier: ^1.1.0
version: 1.1.0([email protected])
@@ -594,6 +594,46 @@ packages:
'@exodus/[email protected]':
resolution: {integrity: sha512-5Aap/GaRupgNx/feGBwLLTVv8OQFfv3pq2lPRzPg9R+IOBnDgghTGW7l7EuVXOvg5cc/xSAlRW8rBrjIC3Nvqw==}
+ '@fallow-cli/[email protected]':
+ resolution: {integrity: sha512-moS850FVnDP4ZXY+79O7TA54s2ZmUe/bQpwsu+hkyOKAFeOqlHAoMM12IDiA+P/UBr4N2F+mEzMR65HgShdztQ==}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@fallow-cli/[email protected]':
+ resolution: {integrity: sha512-x3P4NEsLE71convKyFHIfuqXwyN9R7fzYCeMVAwHupB+gmIJyZfl+BiGJx4v1VXCS6pbUYn7X1UxHYhk1T/MPg==}
+ cpu: [x64]
+ os: [darwin]
+
+ '@fallow-cli/[email protected]':
+ resolution: {integrity: sha512-Nb6anWSulLkB0KDOEiqkbDn3VoSBQqfPyB3fUorPBMF+EJ6fOgwK8B/wenTEJf2Y4gy7ynUNJ1yITep1FJhqRA==}
+ cpu: [arm64]
+ os: [linux]
+
+ '@fallow-cli/[email protected]':
+ resolution: {integrity: sha512-jkIwb53aG4OO0sXeqbF+WLKtAd1sAykQ9qhcVICu08/BVuISShkUL69T0jKBvAw0S4mfvaIitHvCmlsaBUQ0Ig==}
+ cpu: [arm64]
+ os: [linux]
+
+ '@fallow-cli/[email protected]':
+ resolution: {integrity: sha512-QLHmh0NRnAhELreLOZtcU4PJbHMFUoBq3J1DUSPfqQj6SqXsxAnARolsMGsg6bOEF3erj51ZWN22JUWYNOW76A==}
+ cpu: [x64]
+ os: [linux]
+
+ '@fallow-cli/[email protected]':
+ resolution: {integrity: sha512-wwvq/1/eiAJwLGuOlN4oF84Pp6RVKgIVGlIPBnXm5jyj5E+Iym8Ng1eGBBu2vtbUEZxumT6bexySIYMRSe+53g==}
+ cpu: [x64]
+ os: [linux]
+
+ '@fallow-cli/[email protected]':
+ resolution: {integrity: sha512-QyR0x2TVfkTxObZRC0gNTXXjiRbHeNyM0gBy1w5g/foos33lx2qdm9wrhM+/jmdDJZZME5DmXvGtnUoT4U+hug==}
+ cpu: [arm64]
+ os: [win32]
+
+ '@fallow-cli/[email protected]':
+ resolution: {integrity: sha512-+3nT9JrQRSVQf67TlzzSRJWFE1hfxti8Sv719aVHcuzZhA/dcDEr4+fKQ5cBJc9eap75JAiRWUNzc69J2lVong==}
+ cpu: [x64]
+ os: [win32]
+
'@floating-ui/[email protected]':
resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==}
@@ -693,84 +733,42 @@ packages:
cpu: [arm]
os: [android]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-l/44caGse+VpnY9gx0yvvc5QnnG3yG1FO3KZgYvNL1GZrfK86zIwAOgGEVlxDyRymzrU/KHiblPFpevKOmJmUA==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm]
- os: [android]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-rh72O8ackqp0HC+3W38oCTkCFmOpXrHRrbP+4xrX8O1UmCWcyb5pIbA/+0ATPGVVl9NcHt/CgqI8rBuw4Y9kMg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-KUHmPMziLBp4u+zbrLdB7iWS7KshuZe+RAp7ELnY9SI9nNXBZ+dp8fiBqWOxhXqn+FQg3a4UcQhwmsJOKV8Jjg==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [android]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-14Q74TMQA/eO0N5dz5Tel25qma9vVJEpmrmqXnx0R7jMXhqFxkSSy40NOtCQijWUfeD5ho5+NuXDl5WSxyifJQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-q8dWmnU/8ea2tga9w2f1PinQ5rcMPDUGkF64T189b65YMjUomET4oy5oRldOr4AwOQkneOG/Zttnz1Dvrc62wg==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [darwin]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-qWQDphAaIS6qXeuYcWm4jta8qFZpjjim2WxiPwZmHi77COS8i0Jct8tBcNIOZ/JaVh+hCL2it228m2Lr9GOL6A==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-cOKeIELIB2bJnCKwqx4Rdj+1Lss/U6uCbLxRySZrhyOOQa1flKhwZFjEHRHxk8fU1NKmhK5OnTdPQ4CpjuFuVw==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [darwin]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-PTATC/j2MvDP8lejoCC7PFWNoYV2NsVzzM0WgBqZDFAkFdKsW0wfbQWochfY3fHNUN1QhZNetrd/K4Pdo6cIHQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-OpaSv4pW3KgFrMYQxTaS0aOE4T1DQF3qZE/4B6uqqv1KgPWWd4UQhJALi8PJPX1RRV5K7ThKXRfF7qGg2+3l1A==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [freebsd]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-Colj5agHBAMKZrkyPcCEelfKuh8sNi1lWpJf1TiEeEmbREQ6I2ytG+ccfdDaiUV7Z0Vw5FyJbnqEPgHo8kF3RQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-JGK1wlGrGwxBIlVSF7KWTX1/ru6BEtf28fRROztDRkLfiW+Kxa4onnriezMIiogfn9hVw2KzYcKiLjkLR2ns8A==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm]
- os: [linux]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-BxQ8o082+/qtjAFK6WUV+/bi0y3M0RPvPQNm8JSY7/7LfhbWq6NykgZiGayrtauO1nowpmGlnpJXXMp9q0oT1A==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-yuZO533Ftonxn/iyoqQzURzLQHMspvsIyfiCSNi1t/ER4eIQaR0SsmUOUm5b/lmSig7IWIUa5/BrbEkAPwcilQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm]
- os: [linux]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-qR0dOth+4whygUwoNnfews8jMC78gjhIBfcy9AFzvxoh7PFGdferRp3KV/4kkeaVk2kOS/5grlAeJevpA+/Pfg==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -778,13 +776,6 @@ packages:
os: [linux]
libc: [glibc]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-hvpbqT5pN2rR+3+xtWeizwfR/aZ0vGceg6TqYMl+ToxMpk9/tmnX7kSvQnfEUkoua8mhogzvIKsAkn0wxgblBA==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [linux]
- libc: [glibc]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-eIXyzpA12/+maKjMSsXdHfpzwQcoRfzokT+/ZhVEo6u/9RcXQrZZmZ70MmmJqwVcLez6U4ScjB/eiYlsEs7p0g==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -792,13 +783,6 @@ packages:
os: [linux]
libc: [musl]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-wJQGamIosQBoJHW9+S5XxrtKRo3eyJxsnS1XCPrqN0LHi8uw1pTqqTfn3t/NVuvbBg7Pumn4ez9Eidgcn0xbEg==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [linux]
- libc: [musl]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-w7ir5OuqSJUKLadmsSAWwTNso/ZGem2bPT/1LSU7l+ecmKPyegIvU+wzY0ADhZ/t/goaedqyp24SDRxyLxO9zg==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -806,13 +790,6 @@ packages:
os: [linux]
libc: [glibc]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-Koaz32/O5+abIfrNGdyndgRvdOZ9jEf5/z3Ep9h3h2QWpdDiUQpVwgH0OcMXCs+l9aXxPLtkupqyVig9W6FDKw==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [ppc64]
- os: [linux]
- libc: [glibc]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-2KPTfWorcW8RNE8aEMHKbPSjHDBjFVYqg8nSLRBp7pe7VBqHsmkO9jpK8YmaYA5d5GcUy+J++5O4EgxkrQBEtw==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -820,13 +797,6 @@ packages:
os: [linux]
libc: [glibc]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-R4vOjWzxhnNWHnVLeiB6jNuIifdy9vcMXZGPc7StXcxBovI+U2zg1QhZ9o8OjV80oGivs1lX5NfPLzk4IPqlRA==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [riscv64]
- os: [linux]
- libc: [glibc]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-Vsl8dmQdKtDsQiDPHP5VFjXOuVGcZQcziYMkU/yPnlaKHMqoX/q+bxt7K+BwResi9Cc8pnZ6oYGTgPcjAtt5QQ==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -834,13 +804,6 @@ packages:
os: [linux]
libc: [musl]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-iwgBNUTHiMdxARLYuM0SBlnYeb19iw1Ea5M+4ERZupCsBMLArti6FyZ6UfFjJxIiTDr2oW2DGQFxlQVQ/dW9rA==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [riscv64]
- os: [linux]
- libc: [musl]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-HwY5kuM818r/kHdHG2TZqzqxyF7fz90prPg85R/2VmgRWk8cMyGZo+8BNZDQAMJ6aGSTRvn2sdGXv3sZ5bsUWw==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -848,13 +811,6 @@ packages:
os: [linux]
libc: [glibc]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-ZwZNo8FZmB/gVfboQl+wXilBigGl+6nQQs+nITOeAP/HcAOjiHl6XZJL9F/KXNEspODQcbjAiyjUbeCJd9a0fA==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [s390x]
- os: [linux]
- libc: [glibc]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-o7k6+xAI2pIkjBsCqM0elI4q+qY/3TexH6cpIlGm+nJze1tvx7QEHCKdiy6wnRacFvUYmySEZ5hWFBc9MbxrIA==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -862,13 +818,6 @@ packages:
os: [linux]
libc: [glibc]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-govCvWx1dBlED3uu4qXctxpRcouu9I8Kn+DBktGCl760JtlGJzc9l/OmPJKlYWSbrRqKkMZehNeZ/4Wfma7uSA==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [linux]
- libc: [glibc]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-vksRynFD6vytE1sDZCaeIk6y6rCsq0a18T4kcXbfGHBq2q/qSyDogWLk3A3S3hl/ikNfse7yrEwAuQ8ldIJeAg==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -876,180 +825,41 @@ packages:
os: [linux]
libc: [musl]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-ssTlpXD5Mq9uCssDJPzlRWqBt4Y7Zzd9i+XZhWmK/9Y6KUIuAxVYTYiI8lxcGWi0+3/Cz4A8q9UrD4NK9Y2j7g==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [linux]
- libc: [musl]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-AAtg4pnKvrKsay2ldZZRY98ALFBOgbyy3Gyxo658z6aecM0Zr5mI9BOHRCchSVKUHqMqmjhCA4wIdZvz02VrAw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-51aByfXhPtLEdWG4a2Ihdw6cPWV1ei1AarALpFdDP8MLWDLE2NuUMgbo3DERR2Kt8fT/ok1GUvBiLxVGke9uUQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [openharmony]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-FkIQFrwlBXoFsazb9NQpQPP4YI9sWWXUOLkIPYlQb+hPwr+VY6d0B7l26yMBR2ktf2h3qyAMOW6Pd+mX9rtOJg==}
engines: {node: '>=14.0.0'}
cpu: [wasm32]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-2e16tkKp+wDO2GTAmXfxbBcCmGEaFPIJEIRBBmVKNVXSc8/fJsSIaBGyFTPHM9ST5GNWgJcYIt94rDTks+PLwA==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [wasm32]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-bi4RY9oktNm3kQ3qRCJgBKtwqSg+mtnt5W9l33rdiTyiXlL8a1LQQy1x7aym/ArHDE+19kSWSr2YDd2ExxzbfQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [win32]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-KPTNDKbxH1cglrqTyVeXHb4Pk4oksz8EcE1/v8zqU7N4UXbiHfA/IwtXZ2U77fnRAWBbgVkl/lZbL7o3hRdejg==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [win32]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-ZhvL2vK+9rzjk1US2d2u6NeI1/jtkzsm//ilFac+Kn3klTpJJlKNZwF23CUiAu+B3rdQUbPItm/BHlL6f/5uPA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ia32]
os: [win32]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-Una1bNYv9zCavQrfnDR9wuZVB3itLjCEH4Oz7i6CwAJN/Xq9b+zbbcxmvdkKvvJt4Ngc/MBmIYlbLo3zS4TQ0A==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [ia32]
- os: [win32]
-
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-P4ywUSCYIg44Y82wF3e0ns1BV1dNn+ZhfjNDwm0FTPtBKXedOCRPrvmjXn7Qb+IDGGHAA68lmDLCjGxuKUwXPw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [win32]
- '@oxc-parser/[email protected]':
- resolution: {integrity: sha512-kjBhCiOGSYTwDJQuuZa7a94JbP8htWu7J0X1KwH74kV2K5eYf6eyJRYmkpCDvr0XEL8tMxYI4WU1VekblFCLgg==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [win32]
-
'@oxc-project/[email protected]':
resolution: {integrity: sha512-s9RKLJbRR+3kEFB3mmJVPWah3cZUAl0Jzmthx6Pb/QXnlNkRwTP75tK4uVahp/ifiiTmNYMXI1+NnGP1rNurXg==}
'@oxc-project/[email protected]':
resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==}
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-IjfWOXRgJFNdORDl+Uf1aibNgZY2guOD3zmOhx1BGVb/MIiqlFTdmjpQNplSN58lhWehnX4UNqC3QwpUo8pjJg==}
- cpu: [arm]
- os: [android]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-QqslZAuFQG8Q9xm7JuIn8JUbvywhSBMVhuQHtYW+auirZJloS41oxUUaBXk7uUhZJgp44c5zQLeVvmFaDQB+2Q==}
- cpu: [arm64]
- os: [android]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-MUcavykj2ewlR+kc5arpg4tC2RvzJkUxWtNv74pf7lcNk00GpIpN43vXMj+j6r4eMmfZhlb8hueKoIb8e9kAGQ==}
- cpu: [arm64]
- os: [darwin]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-BGB16nRUK5Etiv//ihPyzj8Lj1px0mhh4YIfe0FDf045ywknfSm0GEbiRESpr6Q4K82AvnyaRIhhluHByvS4bg==}
- cpu: [x64]
- os: [darwin]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-JZgtePaqj3qmD5XFHJaSLWzHRxQu0LaPkdoM1KJXYADvAaa83ijXHclV3ej3CueeW0wxfIAbGCZVP45J0CA7uQ==}
- cpu: [x64]
- os: [freebsd]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-hOQ/p3ry3v3SchUBXicrrnszaI/UmYzM4wtS4RGfwgVUX7a+HbyQSzJ5aOzu+o6XZkFkS3ZXN4PZAzhOb77OSg==}
- cpu: [arm]
- os: [linux]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-2ArPksaw0AqeuGBfoS715VF+JvJQAhD2niWgjE5hVO+L+nAfikVQopvngCMX9x4BD8itWoQ3dnikrQyl5Ho5Jg==}
- cpu: [arm]
- os: [linux]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-0bJnmYFp62JdZ4nVMDUZ/C58BCZOCcqgKtnUlp7L9Ojf/czIN+3j72YlLPeWLkzlr6SlYvIQA4SGV/HyO0d+qg==}
- cpu: [arm64]
- os: [linux]
- libc: [glibc]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-wKHHzPKZo7Ufhv/Bt6yxT7FOgnIgW4gwXcJUipkShGp68W3wGVqvr1Sr0fY65lN0Oy6y41+g2kIDvkgZaMMUkw==}
- cpu: [arm64]
- os: [linux]
- libc: [musl]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-RN8goF7Ie0B79L4i4G6OeBocTgSC56vJbQ65VJje+oXnldVpLnOU7j/AQ/dP94TcCS+Yh6WG8u3Qt4ETteXFNQ==}
- cpu: [ppc64]
- os: [linux]
- libc: [glibc]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-5l1yU6/xQEqLZRzxqmMxJfWPslpwCmBsdDGaBvABPehxquCXDC7dd7oraNdKSJUMDXSM7VvVj8H2D2FTjU7oWw==}
- cpu: [riscv64]
- os: [linux]
- libc: [glibc]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-xHEvkbgz6UC+A3JOyDQy76LkUaxsNSfIr3/GV8slwZsnuooJiIB34gzJfsyvR4JdCYNUUPsRJc/w/oWkODu+hg==}
- cpu: [riscv64]
- os: [linux]
- libc: [musl]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-aWPDUUmSeyHvlW+SoEUd+JIJsQhVhu6a5tBpDRMu058naPAchTgAVGCFy35zjbnFlt0i8hLWziff6HX0D3LU4g==}
- cpu: [s390x]
- os: [linux]
- libc: [glibc]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-x2YeSimvhJjKLVD8KSu8f/rqU1potcdEMkApIPJqjZWN7c2Fpt4g2X32WDg1p+XDAmyT7nuQGe0vnhvXeLbH+g==}
- cpu: [x64]
- os: [linux]
- libc: [glibc]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-kcRLEIxpZefeYfLChjpgFf3ilBzRDZ+yobMrpRsQlSrxuFGtm3U6PMU7AaEpMqo3NfDGVyJJseAjnRLzMFHjwQ==}
- cpu: [x64]
- os: [linux]
- libc: [musl]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-HHcfnApSZGtKhTiHqe8OZruOZe5XuFQH5/E0Yhj3u8fnFvzkM4/k6WjacUf4SvA0SPEAbfbgYmVPuo0VX/fIBQ==}
- cpu: [arm64]
- os: [openharmony]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-Tn0y1XOFYHNfK1wp1Z5QK8Rcld/bsOwRISQXfqAZ5IBpv8Gz1IvV39fUWNprqNdRizgcvFhOzWwFun2zkJsyBg==}
- engines: {node: '>=14.0.0'}
- cpu: [wasm32]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-qPi25YNPe4YenS8MgsQU2+bIFHxxpLx1LVna2444cEHqNPhNjvWf9zqj4aWE43H9LpAsTmkkAlA3eL5ElBU3mA==}
- cpu: [arm64]
- os: [win32]
-
- '@oxc-resolver/[email protected]':
- resolution: {integrity: sha512-Wb14jWEW8huH6It9F6sXd9vrYmIS7pMrgkU6sxpLxkP+9z+wRgs71hUEhRpcn8FOXAFa27FVWfY2tRpbfTzfLw==}
- cpu: [x64]
- os: [win32]
-
resolution: {integrity: sha512-XfVM8AmIovBTKXCt14Op5wbfcoM8418nttd+nhMgM3RAVaJg1MtJc73FyWfUt0oxLyBGVwfniNVUsbV/b3VmPg==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -1988,6 +1798,11 @@ packages:
resolution: {integrity: sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==}
+ resolution: {integrity: sha512-q5gKY084d6ycCanOMVhdw5wXfWR7+octSD8EMh+UsJdKlt8vr7EaCPX37CPdJ4Rj1SDf2fVThpdmeBgLi4XsrQ==}
+ engines: {node: '>=16'}
+ hasBin: true
+
resolution: {integrity: sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==}
engines: {node: '>=8.0.0'}
@@ -1998,9 +1813,6 @@ packages:
resolution: {integrity: sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==}
- resolution: {integrity: sha512-jKmm9YtsNXN789RS/0mSzOC1NUq9mkVd65vbSSVsKdjGvYXBuE4oWe2QOEoFeRmJg+lPuZxpmrfFclNhoRMneQ==}
-
resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
engines: {node: '>=12.0.0'}
@@ -2010,11 +1822,6 @@ packages:
picomatch:
optional: true
- resolution: {integrity: sha512-9XNj/o4wrRFyhSMJOvsuyMwy8aUfBaZ1VrqHVfohyXf0Sw0e+yfKG+xZaY3arGCOMdwFsqObtzVOc1gU9KiT9w==}
- engines: {node: '>=18.3.0'}
- hasBin: true
-
resolution: {integrity: sha512-iJSe4YKd/W6WhLwKDVJU9FQeaJRpEFuolhju7ZXlRpUVyDdqFdMP8AUBICgnVvQPyP41IPAlBa/v0Eo35iE6wQ==}
engines: {node: '>=18', pnpm: '>=8.7.0'}
@@ -2036,9 +1843,6 @@ packages:
resolution: {integrity: sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==}
-
resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==}
engines: {node: 18 || 20 || >=22}
@@ -2148,11 +1952,6 @@ packages:
resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-uBaKFEGcu/HG4EY2gWFBMr+fBF43Jftoc2riJX51TKME1Z46C8UQIbNEusenYbEWihphxe2PY0Kns0yPvPYz4A==}
- engines: {node: ^20.19.0 || >=22.12.0}
- hasBin: true
-
resolution: {integrity: sha512-/GmXpo9F9W+f8n4Ivr2iH+7h7wL7jLbLKWkMlpflcCRb6kGjBfTlASEXaZ9qUgNTn4VgS0P2pwxxzQ4EM6Ulgg==}
engines: {node: '>=22'}
@@ -2375,13 +2174,6 @@ packages:
resolution: {integrity: sha512-6M0gEDDVMGGy+Ckg/mlLh4PL87sfKRMlkQJTVTxdcEREwDa4usWjM9n4jC6Jxa5+nc3YlZTecUs4hHjoTVWKaw==}
engines: {node: ^20.19.0 || >=22.12.0}
- resolution: {integrity: sha512-661RSx+ZcjBmjBYid+Fpp/2F5EbtildpeoZh5HdgnGs+jZ03nqQEQW8yGkt4BGyOC3OMPDQQRl8M5kqD2/g6jw==}
- engines: {node: ^20.19.0 || >=22.12.0}
-
- resolution: {integrity: sha512-CblytBiV/a/ZXY34dsVU2NxhIOxMXst8CvDCtyBelVITgd7PLrKzbEbA6oKLdPjvDKDzCiW48qzmzZ+mYaqn+g==}
-
resolution: {integrity: sha512-9cB5glS3Ip6NMuZ+6NYTao9FCWkDhRtPYCtR3QBu/NxHoFbgzzTvi41N4jxz/GqGfuLKspui1qb/LlSu2IbMcw==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -2563,9 +2355,6 @@ packages:
resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==}
-
resolution: {integrity: sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==}
engines: {node: '>=18'}
@@ -2656,10 +2445,6 @@ packages:
resolution: {integrity: sha512-stxByr12oeeOyY2BlviTNQlYV5xOj47GirPr4yA1hE9JCtxfQN0+tVbkxwCtYDQWhEKWFHsEK48ORg5jrouCAg==}
engines: {node: '>=20'}
- resolution: {integrity: sha512-dWUG8F5sIIARXih1DTaQAX4SsiTXhInKf1buxdY9DIg4ZYPZK5nGM1VRIYmEbDbsHt7USo99xSLFu5Q1IqTmsg==}
- engines: {node: '>= 18'}
-
resolution: {integrity: sha512-e0LyK91f3cUxTmv95/KzoLg47+zF+s/sbxRGDNsyG4dmIP8ZSX8ax6byOxfJXeNNtS/8AZlfD+uP7gBeR7DLlg==}
@@ -2700,10 +2485,6 @@ packages:
resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==}
engines: {node: '>=4'}
- resolution: {integrity: sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==}
- engines: {node: '>=14.16'}
-
resolution: {integrity: sha512-Y0AvSwDw8y+nlSNFXMm2g6L51rBGdAQT20J3YSOqxC53Lo3bjWRtr2BKcfYoAf352WYpsZSTURrA0tqhfgudPA==}
@@ -2883,10 +2664,6 @@ packages:
resolution: {integrity: sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-FeFPZ/WFT0mbRCuydiZzpPFlrYN8ZUpphQKoq4EeElVIYjYyGzPMxQR/simUwCOJIyVhpFk4RbtyO7RuMpMnHA==}
- engines: {node: '>=14'}
-
resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}
@@ -3002,10 +2779,6 @@ packages:
resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A==}
- engines: {node: 20 || >=22}
-
resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==}
engines: {node: '>=20'}
@@ -3374,6 +3147,30 @@ snapshots:
'@exodus/[email protected]':
optional: true
+ '@fallow-cli/[email protected]':
+ optional: true
+
+ '@fallow-cli/[email protected]':
+ optional: true
+
+ '@fallow-cli/[email protected]':
+ optional: true
+
+ '@fallow-cli/[email protected]':
+ optional: true
+
+ '@fallow-cli/[email protected]':
+ optional: true
+
+ '@fallow-cli/[email protected]':
+ optional: true
+
+ '@fallow-cli/[email protected]':
+ optional: true
+
+ '@fallow-cli/[email protected]':
+ optional: true
+
'@floating-ui/[email protected]':
dependencies:
'@floating-ui/utils': 0.2.11
@@ -3510,99 +3307,51 @@ snapshots:
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
dependencies:
'@emnapi/core': 1.9.2
@@ -3610,96 +3359,19 @@ snapshots:
'@napi-rs/wasm-runtime': 1.1.4(@emnapi/[email protected])(@emnapi/[email protected])
optional: true
- '@oxc-parser/[email protected]':
- dependencies:
- '@emnapi/core': 1.10.0
- '@emnapi/runtime': 1.10.0
- '@napi-rs/wasm-runtime': 1.1.4(@emnapi/[email protected])(@emnapi/[email protected])
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-parser/[email protected]':
optional: true
- '@oxc-parser/[email protected]':
- optional: true
-
'@oxc-project/[email protected]': {}
'@oxc-project/[email protected]': {}
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- dependencies:
- '@emnapi/core': 1.10.0
- '@emnapi/runtime': 1.10.0
- '@napi-rs/wasm-runtime': 1.1.4(@emnapi/[email protected])(@emnapi/[email protected])
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
- '@oxc-resolver/[email protected]':
- optional: true
-
optional: true
@@ -4496,6 +4168,19 @@ snapshots:
+ dependencies:
+ detect-libc: 2.1.2
+ optionalDependencies:
+ '@fallow-cli/darwin-arm64': 2.89.0
+ '@fallow-cli/darwin-x64': 2.89.0
+ '@fallow-cli/linux-arm64-gnu': 2.89.0
+ '@fallow-cli/linux-arm64-musl': 2.89.0
+ '@fallow-cli/linux-x64-gnu': 2.89.0
+ '@fallow-cli/linux-x64-musl': 2.89.0
+ '@fallow-cli/win32-arm64-msvc': 2.89.0
+ '@fallow-cli/win32-x64-msvc': 2.89.0
+
dependencies:
pure-rand: 6.1.0
@@ -4505,18 +4190,10 @@ snapshots:
- dependencies:
- walk-up-path: 4.0.0
-
optionalDependencies:
picomatch: 4.0.4
- dependencies:
- fd-package-json: 2.0.0
-
dependencies:
svelte: 5.56.1
@@ -4531,10 +4208,6 @@ snapshots:
- dependencies:
- resolve-pkg-maps: 1.0.0
-
dependencies:
minimatch: 10.2.5
@@ -4655,23 +4328,6 @@ snapshots:
- dependencies:
- fdir: 6.5.0([email protected])
- formatly: 0.3.0
- get-tsconfig: 4.14.0
- jiti: 2.7.0
- minimist: 1.2.8
- oxc-parser: 0.133.0
- oxc-resolver: 11.20.0
- picomatch: 4.0.4
- smol-toml: 1.6.1
- strip-json-comments: 5.0.3
- tinyglobby: 0.2.17
- unbash: 3.0.0
- yaml: 2.9.0
- zod: 4.4.3
-
@@ -4871,53 +4527,6 @@ snapshots:
'@oxc-parser/binding-win32-ia32-msvc': 0.125.0
'@oxc-parser/binding-win32-x64-msvc': 0.125.0
- dependencies:
- '@oxc-project/types': 0.133.0
- optionalDependencies:
- '@oxc-parser/binding-android-arm-eabi': 0.133.0
- '@oxc-parser/binding-android-arm64': 0.133.0
- '@oxc-parser/binding-darwin-arm64': 0.133.0
- '@oxc-parser/binding-darwin-x64': 0.133.0
- '@oxc-parser/binding-freebsd-x64': 0.133.0
- '@oxc-parser/binding-linux-arm-gnueabihf': 0.133.0
- '@oxc-parser/binding-linux-arm-musleabihf': 0.133.0
- '@oxc-parser/binding-linux-arm64-gnu': 0.133.0
- '@oxc-parser/binding-linux-arm64-musl': 0.133.0
- '@oxc-parser/binding-linux-ppc64-gnu': 0.133.0
- '@oxc-parser/binding-linux-riscv64-gnu': 0.133.0
- '@oxc-parser/binding-linux-riscv64-musl': 0.133.0
- '@oxc-parser/binding-linux-s390x-gnu': 0.133.0
- '@oxc-parser/binding-linux-x64-gnu': 0.133.0
- '@oxc-parser/binding-linux-x64-musl': 0.133.0
- '@oxc-parser/binding-openharmony-arm64': 0.133.0
- '@oxc-parser/binding-wasm32-wasi': 0.133.0
- '@oxc-parser/binding-win32-arm64-msvc': 0.133.0
- '@oxc-parser/binding-win32-ia32-msvc': 0.133.0
- '@oxc-parser/binding-win32-x64-msvc': 0.133.0
-
- optionalDependencies:
- '@oxc-resolver/binding-android-arm-eabi': 11.20.0
- '@oxc-resolver/binding-android-arm64': 11.20.0
- '@oxc-resolver/binding-darwin-arm64': 11.20.0
- '@oxc-resolver/binding-darwin-x64': 11.20.0
- '@oxc-resolver/binding-freebsd-x64': 11.20.0
- '@oxc-resolver/binding-linux-arm-gnueabihf': 11.20.0
- '@oxc-resolver/binding-linux-arm-musleabihf': 11.20.0
- '@oxc-resolver/binding-linux-arm64-gnu': 11.20.0
- '@oxc-resolver/binding-linux-arm64-musl': 11.20.0
- '@oxc-resolver/binding-linux-ppc64-gnu': 11.20.0
- '@oxc-resolver/binding-linux-riscv64-gnu': 11.20.0
- '@oxc-resolver/binding-linux-riscv64-musl': 11.20.0
- '@oxc-resolver/binding-linux-s390x-gnu': 11.20.0
- '@oxc-resolver/binding-linux-x64-gnu': 11.20.0
- '@oxc-resolver/binding-linux-x64-musl': 11.20.0
- '@oxc-resolver/binding-openharmony-arm64': 11.20.0
- '@oxc-resolver/binding-wasm32-wasi': 11.20.0
- '@oxc-resolver/binding-win32-arm64-msvc': 11.20.0
- '@oxc-resolver/binding-win32-x64-msvc': 11.20.0
-
dependencies:
tinypool: 2.1.0
@@ -5074,8 +4683,6 @@ snapshots:
-
dependencies:
onetime: 7.0.0
@@ -5177,8 +4784,6 @@ snapshots:
ansi-styles: 6.2.3
is-fullwidth-code-point: 5.1.0
-
dependencies:
debug: 4.4.3
@@ -5235,8 +4840,6 @@ snapshots:
-
dependencies:
stubborn-utils: 1.0.2
@@ -5437,8 +5040,6 @@ snapshots:
-
@@ -5505,8 +5106,6 @@ snapshots:
dependencies:
xml-name-validator: 5.0.0
-
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 950768442..1eb0fbfb6 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -33,3 +33,12 @@ allowBuilds:
sharp: true
minimumReleaseAgeExclude:
+ - '@fallow-cli/[email protected]'
+ - '@fallow-cli/[email protected]'
+ - '@fallow-cli/[email protected]'
+ - '@fallow-cli/[email protected]'
+ - '@fallow-cli/[email protected]'
+ - '@fallow-cli/[email protected]'
+ - '@fallow-cli/[email protected]'
+ - '@fallow-cli/[email protected]'
diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.ts
index 068bb1f37..3cdb0aaac 100644
--- a/tests/spec/project.spec.ts
+++ b/tests/spec/project.spec.ts
@@ -676,12 +676,25 @@ test.describe('New Compose Project Page', () => {
.toBe('running');
expect(projectPullRequestCount).toBe(0);
+ const projectReloadResponse = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'GET' &&
+ getPathname(response.url()) === `/api/environments/0/projects/${projectId}` &&
+ response.ok(),
+ { timeout: 30000 }
+ );
await page.reload();
- await page.waitForLoadState('load');
- await expect(page.getByText('Running', { exact: true }).first()).toBeVisible({
- timeout: 20000
+ await projectReloadResponse;
+ await expect(page).toHaveURL(new RegExp(`/projects/${projectId}`));
+ await expect
+ .poll(async () => (await fetchProjectDetail(page, projectId))?.status, {
+ message: 'Expected project to still be running after reload',
+ timeout: 30000
+ })
+ .toBe('running');
+ await expect(page.getByRole('button', { name: 'Down', exact: true })).toBeVisible({
+ timeout: 30000
});
- await expect(page.getByRole('button', { name: 'Down', exact: true })).toBeVisible();
});
test('should send selected deploy split-button options in the up request', async ({ page }) => {