Skip to content

Modern Docker Management, Designed for Everyone

7.3 KB
Raw Blame
<script lang="ts">
	import { createQuery } from '@tanstack/svelte-query';
	import { toast } from 'svelte-sonner';

	import ContainerRegistryFormSheet from '#lib/components/sheets/container-registry-sheet.svelte';
	import { EmptyState } from '#lib/components/states/index.js';
	import * as Dialog from '#lib/components/ui/dialog/index.js';
	import { RegistryIcon } from '#lib/icons/index.js';
	import { ResourcePageLayout, type ActionButton } from '#lib/layouts/index.js';
	import { m } from '#lib/paraglide/messages.js';
	import { queryKeys } from '#lib/query/query-keys.js';
	import { containerRegistryService } from '#lib/services/container-registry-service.js';
	import type { ContainerRegistry, ContainerRegistryPullUsage } from '#lib/types/docker.js';
	import type { ContainerRegistryCreateDto, ContainerRegistryUpdateDto } from '#lib/types/docker.js';
	import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
	import { hasPermission } from '#lib/utils/auth.js';
	import { tryCatch } from '#lib/utils/try-catch.js';

	import RegistryTable from './components/registry-table.svelte';

	let { data } = $props();

	let registries = $derived(data.registries);
	let selectedIds = $state<string[]>([]);
	let isRegistryDialogOpen = $state(false);
	let isInfoDialogOpen = $state(false);
	let registryToEdit = $state<ContainerRegistry | null>(null);
	let requestOptions = $derived(data.registryRequestOptions);
	const pullUsageQuery = createQuery(() => ({
		queryKey: queryKeys.containerRegistries.pullUsage(),
		queryFn: () => containerRegistryService.getPullUsage(),
		initialData: data.pullUsage ?? undefined
	}));
	const pullUsageByRegistry = $derived.by<Record<string, ContainerRegistryPullUsage>>(() => {
		const entries = pullUsageQuery.data?.registries ?? [];
		return Object.fromEntries(entries.map((usage) => [usage.registryId, usage]));
	});

	let isLoading = $state({
		create: false,
		edit: false,
		refresh: false
	});

	async function refreshRegistries() {
		isLoading.refresh = true;
		await handleApiResultWithCallbacks({
			result: await tryCatch(containerRegistryService.getRegistries(requestOptions)),
			message: m.common_refresh_failed({ resource: m.registries_title() }),
			setLoadingState: (value) => (isLoading.refresh = value),
			onSuccess: async (newRegistries) => {
				registries = newRegistries;
				await pullUsageQuery.refetch();
				toast.success(m.registries_refreshed());
			}
		});
	}

	function openCreateRegistryDialog() {
		registryToEdit = null;
		isRegistryDialogOpen = true;
	}

	function openEditRegistryDialog(registry: ContainerRegistry) {
		registryToEdit = registry;
		isRegistryDialogOpen = true;
	}

	async function handleRegistryDialogSubmit(detail: {
		registry: ContainerRegistryCreateDto | ContainerRegistryUpdateDto;
		isEditMode: boolean;
	}) {
		const { registry, isEditMode } = detail;
		const loadingKey = isEditMode ? 'edit' : 'create';
		isLoading[loadingKey] = true;

		try {
			const operationResult = await tryCatch(
				(async () => {
					if (isEditMode && registryToEdit?.id) {
						await containerRegistryService.updateRegistry(registryToEdit.id, registry as ContainerRegistryUpdateDto);
						toast.success(m.common_update_success({ resource: m.resource_registry() }));
					} else {
						await containerRegistryService.createRegistry(registry as ContainerRegistryCreateDto);
						toast.success(m.common_create_success({ resource: m.resource_registry() }));
					}

					[registries] = await Promise.all([containerRegistryService.getRegistries(requestOptions), pullUsageQuery.refetch()]);
					isRegistryDialogOpen = false;
				})()
			);
			if (operationResult.error !== null) {
				const error = operationResult.error;

				console.error('Error saving registry:', error);
				toast.error(error instanceof Error ? error.message : m.registries_save_failed());
			}
		} finally {
			isLoading[loadingKey] = false;
		}
	}

	const canCreateRegistry = $derived(hasPermission('registries:create'));

	const actionButtons: ActionButton[] = $derived.by(() => {
		const buttons: ActionButton[] = [
			{
				id: 'info',
				action: 'inspect',
				label: m.registries_info_title(),
				onclick: () => (isInfoDialogOpen = true)
			}
		];
		if (canCreateRegistry) {
			buttons.push({
				id: 'create',
				action: 'create',
				placement: 'primary',
				label: m.common_add_button({ resource: m.common_registry() }),
				onclick: openCreateRegistryDialog
			});
		}
		buttons.push({
			id: 'refresh',
			action: 'refresh',
			placement: 'secondary',
			iconOnly: true,
			label: m.common_refresh(),
			onclick: refreshRegistries,
			loading: isLoading.refresh,
			disabled: isLoading.refresh
		});
		return buttons;
	});
</script>

{#snippet registriesEmptyState()}
	<EmptyState
		variant="plain"
		icon={RegistryIcon}
		title={m.registries_empty_title()}
		description={m.registries_empty_description()}
		actionLabel={canCreateRegistry ? m.common_add_button({ resource: m.common_registry() }) : undefined}
		onAction={openCreateRegistryDialog}
	/>
{/snippet}

<ResourcePageLayout title={m.registries_title()} subtitle={m.registries_subtitle()} {actionButtons}>
	{#snippet mainContent()}
		<RegistryTable
			emptyState={registriesEmptyState}
			bind:registries
			bind:selectedIds
			bind:requestOptions
			{pullUsageByRegistry}
			onEditRegistry={openEditRegistryDialog}
		/>
	{/snippet}

	{#snippet additionalContent()}
		<ContainerRegistryFormSheet
			bind:open={isRegistryDialogOpen}
			bind:registryToEdit
			onSubmit={handleRegistryDialogSubmit}
			isLoading={isLoading.create || isLoading.edit}
		/>

		<Dialog.Root bind:open={isInfoDialogOpen}>
			<Dialog.Content class="max-w-2xl">
				<Dialog.Header>
					<Dialog.Title>{m.registries_info_title()}</Dialog.Title>
					<Dialog.Description>{m.registries_info_description()}</Dialog.Description>
				</Dialog.Header>
				<div class="grid grid-cols-1 gap-6 py-4 md:grid-cols-2">
					<div class="space-y-3">
						<h4 class="text-sm font-medium">{m.registries_popular_public_title()}</h4>
						<div class="space-y-2 text-sm">
							<div class="flex justify-between">
								<span class="text-muted-foreground">{m.registry_docker_hub()}</span>
								<code class="rounded bg-muted px-2 py-1 text-xs">{m.registry_docker_hub_url()}</code>
							</div>
							<div class="flex justify-between">
								<span class="text-muted-foreground">{m.registry_github_container_registry()}</span>
								<code class="rounded bg-muted px-2 py-1 text-xs">{m.registry_github_url()}</code>
							</div>
							<div class="flex justify-between">
								<span class="text-muted-foreground">{m.registry_google_container_registry()}</span>
								<code class="rounded bg-muted px-2 py-1 text-xs">{m.registry_google_url()}</code>
							</div>
							<div class="flex justify-between">
								<span class="text-muted-foreground">{m.registry_quay_io()}</span>
								<code class="rounded bg-muted px-2 py-1 text-xs">{m.registry_quay_url()}</code>
							</div>
						</div>
					</div>
					<div class="space-y-3">
						<h4 class="text-sm font-medium">{m.registries_auth_notes_title()}</h4>
						<div class="space-y-1 text-sm text-muted-foreground">
							<p>• {m.registries_auth_notes_bullet_docker_hub()}</p>
							<p>• {m.registries_auth_notes_bullet_github()}</p>
							<p>• {m.registries_auth_notes_bullet_anonymous()}</p>
							<p>• {m.registries_auth_notes_bullet_encrypted()}</p>
						</div>
					</div>
				</div>
			</Dialog.Content>
		</Dialog.Root>
	{/snippet}
</ResourcePageLayout>