Skip to content

Modern Docker Management, Designed for Everyone

15.4 KB
Raw Blame
<script lang="ts">
	import { goto } from '$app/navigation';
	import { toast } from 'svelte-sonner';

	import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
	import type { FilterOption } from '#lib/components/arcane-table/arcane-table.types.svelte.js';
	import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '#lib/components/arcane-table/index.js';
	import { UniversalMobileCard } from '#lib/components/arcane-table/index.js';
	import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
	import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
	import UpdateCenterDialog from '#lib/components/dialogs/update-center-dialog.svelte';
	import { Badge } from '#lib/components/ui/badge/index.js';
	import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
	import { useEasyJoinCandidates } from '#lib/hooks/use-easy-join-candidates.svelte.js';
	import {
		EyeOnIcon,
		TrashIcon,
		EnvironmentsIcon,
		InspectIcon,
		StatsIcon,
		EyeOffIcon,
		TestIcon,
		ConnectionIcon
	} from '#lib/icons/index.js';
	import { m } from '#lib/paraglide/messages.js';
	import { environmentManagementService } from '#lib/services/env-mgmt-service.js';
	import { environmentStore } from '#lib/stores/environment.store.svelte.js';
	import type { Environment } from '#lib/types/environment.js';
	import type { AppVersionInformation } from '#lib/types/settings.js';
	import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
	import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
	import { hasPermission } from '#lib/utils/auth.js';
	import { getEnvironmentStatusVariant, isEnvironmentOnline, resolveEnvironmentStatus } from '#lib/utils/docker.js';
	import { capitalizeFirstLetter } from '#lib/utils/formatting.js';
	import { tryCatch } from '#lib/utils/try-catch.js';
	import { applyEnvironmentUpgrade } from '#lib/utils/update-actions.js';

	import EasyJoinDialog from '../../swarm/cluster/components/easy-join-dialog.svelte';
	import EnvironmentUpgradeMenuItem from './environment-upgrade-menu-item.svelte';
	import EnvironmentVersionCell from './environment-version-cell.svelte';

	let {
		environments = $bindable(),
		selectedIds = $bindable(),
		requestOptions = $bindable(),
		onDeleteSelected,
		bulkDeleteLoading = false
	}: {
		environments: Paginated<Environment>;
		selectedIds: string[];
		requestOptions: SearchPaginationSortRequest;
		onDeleteSelected: (ids: string[]) => void;
		bulkDeleteLoading?: boolean;
	} = $props();

	let isLoading = $state({ removing: false, testing: false, upgrading: false, toggling: false });
	let upgradingEnvironmentId = $state<string | null>(null);
	let showUpgradeDialog = $state(false);
	let selectedEnvironmentForUpgrade = $state<Environment | null>(null);
	let selectedVersionInfoForUpgrade = $state<AppVersionInformation | null>(null);
	let easyJoinDialogOpen = $state(false);
	let easyJoinSession = $state(0);
	let easyJoinTarget = $state<Environment | null>(null);
	const easyJoinCandidates = useEasyJoinCandidates();

	const canInstallUpdates = $derived(hasPermission('environments:update'));

	const environmentTypeFilters: FilterOption[] = [
		{ value: 'http', label: m.environments_edge_http_label(), icon: EnvironmentsIcon },
		{ value: 'edge', label: m.environments_edge_label(), icon: EnvironmentsIcon },
		{ value: 'websocket', label: m.environments_edge_websocket_label(), icon: EnvironmentsIcon },
		{ value: 'grpc', label: m.environments_edge_grpc_label(), icon: EnvironmentsIcon }
	];

	function resolveEnvironmentTransport(item: Environment): 'grpc' | 'websocket' | undefined {
		// Prefer the live tunnel transport; fall back to the last one used so
		// disconnected or poll-only agents still show what they connect with.
		return (item.connected ? item.edgeTransport : undefined) ?? item.lastEdgeTransport;
	}

	function getEnvironmentTypeLabel(item: Environment): string {
		if (!item.isEdge) return m.environments_edge_http_label();
		const transport = resolveEnvironmentTransport(item);
		if (!transport) return m.environments_edge_label();
		if (transport === 'websocket') return m.environments_edge_websocket_label();
		return m.environments_edge_grpc_label();
	}

	function canEasyJoin(item: Environment): boolean {
		return item.id !== '0' && item.enabled && isEnvironmentOnline(item) && easyJoinCandidates.isCandidate(item.id);
	}

	function openEasyJoin(item: Environment) {
		easyJoinSession += 1;
		easyJoinTarget = item;
		easyJoinDialogOpen = true;
	}

	async function handleDeleteOne(id: string, hostname: string) {
		openConfirmDialog({
			title: m.common_delete_title({ resource: m.resource_environment() }),
			message: m.environments_delete_message({ name: hostname }),
			confirm: {
				label: m.common_remove(),
				destructive: true,
				action: async () => {
					isLoading.removing = true;
					const result = await tryCatch(environmentManagementService.delete(id));
					await handleApiResultWithCallbacks({
						result,
						message: m.environments_delete_failed({ name: hostname }),
						setLoadingState: () => {},
						onSuccess: async () => {
							toast.success(m.common_delete_success({ resource: `${m.resource_environment()} "${hostname}"` }));
							environments = await environmentManagementService.getEnvironments(requestOptions);
							await environmentStore.initialize(environments.data);
						}
					});
					isLoading.removing = false;
				}
			}
		});
	}

	async function handleTest(id: string) {
		isLoading.testing = true;
		const result = await tryCatch(environmentManagementService.testConnection(id));
		await handleApiResultWithCallbacks({
			result,
			message: m.environments_test_connection_failed(),
			setLoadingState: () => {},
			onSuccess: async (resp) => {
				const status = (resp as { status: string; message?: string }).status;
				if (status === 'online') toast.success(m.environments_test_connection_success());
				else toast.error(m.environments_test_connection_error());
				// Refresh to get updated status from backend
				environments = await environmentManagementService.getEnvironments(requestOptions);
				await environmentStore.initialize(environments.data);
			}
		});
		isLoading.testing = false;
	}

	function handleUpgradeSelected(environment: Environment, versionInfo: AppVersionInformation) {
		selectedEnvironmentForUpgrade = environment;
		selectedVersionInfoForUpgrade = versionInfo;
		showUpgradeDialog = true;
	}

	async function handleConfirmUpgrade() {
		if (!selectedEnvironmentForUpgrade) return;

		const envId = selectedEnvironmentForUpgrade.id;
		upgradingEnvironmentId = envId;

		return applyEnvironmentUpgrade(envId, () => m.upgrade_failed({ error: m.common_unknown() }));
	}

	async function handleToggleEnabled(environment: Environment) {
		const newEnabled = !environment.enabled;
		isLoading.toggling = true;

		const result = await tryCatch(environmentManagementService.update(environment.id, { enabled: newEnabled }));

		await handleApiResultWithCallbacks({
			result,
			message: m.common_update_failed({ resource: m.resource_environment() }),
			setLoadingState: () => {},
			onSuccess: async () => {
				toast.success(
					m.common_update_success({
						resource: `${m.resource_environment()} "${environment.name}"`
					})
				);
				environments = await environmentManagementService.getEnvironments(requestOptions);
				await environmentStore.initialize(environments.data);
			}
		});

		isLoading.toggling = false;
	}

	const columns = [
		{ accessorKey: 'id', title: m.common_id(), hidden: true },
		{
			id: 'name',
			title: m.common_name(),
			sortable: true,
			accessorFn: (row) => row.name,
			cell: EnvironmentCell
		},
		{
			accessorKey: 'status',
			title: m.common_status(),
			sortable: true,
			cell: StatusCell
		},
		{
			id: 'type',
			title: m.common_type(),
			accessorFn: (row) => row,
			filterOptions: environmentTypeFilters,
			cell: TypeCell
		},
		{
			accessorKey: 'enabled',
			title: m.common_enabled(),
			sortable: true,
			cell: EnabledCell
		},
		{
			id: 'version',
			title: m.common_version(),
			accessorFn: (row) => row,
			cell: VersionCell
		}
	] satisfies ColumnSpec<Environment>[];

	const mobileFields = [
		{ id: 'id', label: m.common_id(), defaultVisible: false },
		{ id: 'status', label: m.common_status(), defaultVisible: true },
		{ id: 'type', label: m.common_type(), defaultVisible: true },
		{ id: 'enabled', label: m.common_enabled(), defaultVisible: true },
		{ id: 'apiUrl', label: m.environments_api_url(), defaultVisible: true }
	];

	const bulkActions = $derived.by<BulkAction[]>(() => [
		{
			id: 'remove',
			label: m.common_remove_selected_count({ count: selectedIds?.length ?? 0 }),
			action: 'remove',
			onClick: onDeleteSelected,
			loading: bulkDeleteLoading,
			disabled: bulkDeleteLoading || isLoading.removing,
			icon: TrashIcon
		}
	]);

	let mobileFieldVisibility = $state<Record<string, boolean>>({});
</script>

{#snippet EnvironmentCell({ item }: { item: Environment })}
	{@const statusValue = resolveEnvironmentStatus(item)}
	<div class="flex items-center gap-3">
		<div class="relative">
			<div class="flex size-8 items-center justify-center rounded-lg bg-muted">
				<EnvironmentsIcon class="size-4 text-muted-foreground" />
			</div>
			<div
				class="absolute -top-1 -right-1 size-3 rounded-full border-2 border-background {statusValue === 'online'
					? 'bg-success'
					: statusValue === 'standby'
						? 'bg-info'
						: statusValue === 'pending'
							? 'bg-warning'
							: 'bg-destructive'}"
			></div>
		</div>
		{#if environmentStore.selected?.id === item.id}
			<Badge variant="blue">
				{m.common_current()}
			</Badge>
		{/if}
		<div class="flex flex-col gap-0.5 leading-tight">
			<button
				class="h-auto min-h-0 cursor-pointer p-0 text-left text-sm leading-tight font-medium text-foreground hover:underline"
				onclick={() => goto(`/environments/${item.id}`)}
			>
				{item.name}
			</button>
			<span class="font-mono text-xs leading-tight text-muted-foreground">{item.apiUrl}</span>
		</div>
	</div>
{/snippet}

{#snippet StatusCell({ value }: { value: unknown })}
	{@const statusValue = String(value)}
	{@const variant = getEnvironmentStatusVariant(statusValue as Environment['status'])}
	<Badge {variant} minWidth="20">{capitalizeFirstLetter(statusValue) || m.common_unknown()}</Badge>
{/snippet}

{#snippet TypeCell({ value }: { value: unknown })}
	{@const env = value as Environment}
	{@const typeLabel = getEnvironmentTypeLabel(env)}
	{@const transport = resolveEnvironmentTransport(env)}
	{@const typeVariant = !env.isEdge || !transport ? 'gray' : transport === 'websocket' ? 'purple' : 'blue'}
	<Badge variant={typeVariant} minWidth="20">{typeLabel}</Badge>
{/snippet}

{#snippet VersionCell({ item }: { item: Environment })}
	<EnvironmentVersionCell environment={item} isOnline={isEnvironmentOnline(item)} />
{/snippet}

{#snippet EnabledCell({ value }: { value: unknown })}
	<Badge variant={value ? 'green' : 'red'} minWidth="20">{value ? m.common_enabled() : m.common_disabled()}</Badge>
{/snippet}

{#snippet EnvironmentMobileCardSnippet({
	item,
	mobileFieldVisibility
}: {
	item: Environment;
	mobileFieldVisibility: MobileFieldVisibility;
})}
	<UniversalMobileCard
		{item}
		icon={{ component: StatsIcon, variant: 'emerald' }}
		title={(item: Environment) => item.name || item.id}
		subtitle={(item: Environment) => ((mobileFieldVisibility['id'] ?? true) ? item.id : null)}
		badges={[
			{ variant: 'green', text: m.resource_environment_cap() },
			...(environmentStore.selected?.id === item.id ? [{ variant: 'blue' as const, text: m.common_current() }] : [])
		]}
		fields={[
			{
				label: m.common_status(),
				getValue: (item: Environment) => capitalizeFirstLetter(resolveEnvironmentStatus(item)),
				icon: StatsIcon,
				iconVariant: 'gray' as const,
				show: mobileFieldVisibility['status'] ?? true
			},
			{
				label: m.common_type(),
				getValue: (item: Environment) => getEnvironmentTypeLabel(item),
				icon: StatsIcon,
				iconVariant: 'gray' as const,
				show: mobileFieldVisibility['type'] ?? true
			},
			{
				label: m.environments_api_url(),
				getValue: (item: Environment) => item.apiUrl,
				icon: StatsIcon,
				iconVariant: 'gray' as const,
				show: (mobileFieldVisibility['apiUrl'] ?? true) && !!item.apiUrl
			}
		]}
		rowActions={RowActions}
		onclick={(item: Environment) => goto(`/environments/${item.id}`)}
	/>
{/snippet}

{#snippet RowActions({ item }: { item: Environment })}
	<RowActionsMenu>
		<DropdownMenu.Item
			onclick={async () => {
				if (!item.enabled) {
					toast.error(m.environments_cannot_switch_disabled());
					return;
				}
				await handleApiResultWithCallbacks({
					result: await tryCatch(environmentStore.setEnvironment(item)),
					message: m.environments_connect_error(),
					onSuccess: () => {
						toast.success(m.environments_switched_to({ name: item.name }));
					}
				});
			}}
			disabled={!item.enabled || environmentStore.selected?.id === item.id}
		>
			<EnvironmentsIcon class="size-4" />
			{environmentStore.selected?.id === item.id ? m.environments_current_environment() : m.environments_use_environment()}
		</DropdownMenu.Item>

		<DropdownMenu.Item onclick={() => goto(`/environments/${item.id}`)}>
			<InspectIcon class="size-4" />
			{m.common_view_details()}
		</DropdownMenu.Item>

		{#if canEasyJoin(item)}
			<DropdownMenu.Item onclick={() => openEasyJoin(item)}>
				<ConnectionIcon class="size-4" />
				{m.swarm_easy_join_action()}
			</DropdownMenu.Item>
		{/if}

		<DropdownMenu.Item onclick={() => handleTest(item.id)} disabled={isLoading.testing}>
			<TestIcon class="size-4" />
			{m.test_connection()}
		</DropdownMenu.Item>

		{#if item.id !== '0'}
			<DropdownMenu.Separator />

			<EnvironmentUpgradeMenuItem
				environment={item}
				isOnline={isEnvironmentOnline(item)}
				disabled={isLoading.upgrading}
				isUpgradingThis={upgradingEnvironmentId === item.id}
				onSelect={handleUpgradeSelected}
			/>

			<DropdownMenu.Item onclick={() => handleToggleEnabled(item)} disabled={isLoading.toggling}>
				{#if item.enabled}
					<EyeOffIcon class="size-4" />
					{m.common_disable()}
				{:else}
					<EyeOnIcon class="size-4" />
					{m.common_enable()}
				{/if}
			</DropdownMenu.Item>

			<DropdownMenu.Separator />

			<DropdownMenu.Item variant="destructive" onclick={() => handleDeleteOne(item.id, item.name)} disabled={isLoading.removing}>
				<TrashIcon class="size-4" />
				{m.common_delete()}
			</DropdownMenu.Item>
		{/if}
	</RowActionsMenu>
{/snippet}

<ArcaneTable
	persistKey="arcane-environments-table"
	items={environments}
	bind:requestOptions
	bind:selectedIds
	bind:mobileFieldVisibility
	{bulkActions}
	onRefresh={async (options) => {
		environments = await environmentManagementService.getEnvironments(options);
		await environmentStore.initialize(environments.data);
		return environments;
	}}
	{columns}
	{mobileFields}
	rowActions={RowActions}
	mobileCard={EnvironmentMobileCardSnippet}
/>

<UpdateCenterDialog
	bind:open={
		() => showUpgradeDialog,
		(open) => {
			showUpgradeDialog = open;
			if (!open) upgradingEnvironmentId = null;
		}
	}
	onConfirm={handleConfirmUpgrade}
	versionInformation={selectedVersionInfoForUpgrade ?? undefined}
	canInstall={canInstallUpdates}
	environmentName={selectedEnvironmentForUpgrade?.name}
	environmentId={selectedEnvironmentForUpgrade?.id}
	bind:upgrading={isLoading.upgrading}
/>

{#key `${easyJoinSession}:${easyJoinCandidates.managerEnvironmentId}`}
	<EasyJoinDialog
		bind:open={easyJoinDialogOpen}
		managerEnvironmentId={easyJoinCandidates.managerEnvironmentId ?? undefined}
		targetEnvironmentId={easyJoinTarget?.id}
		onComplete={easyJoinCandidates.refresh}
	/>
{/key}