Skip to content

Modern Docker Management, Designed for Everyone

6.4 KB
Raw Blame
<script lang="ts">
	import { toast } from 'svelte-sonner';

	import { ArcaneButton } from '#lib/components/arcane-button/index.js';
	import EnvironmentDestinationSelect from '#lib/components/form/environment-destination-select.svelte';
	import * as InputGroup from '#lib/components/ui/input-group/index.js';
	import { Label } from '#lib/components/ui/label/index.js';
	import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';
	import { SearchIcon, DownloadIcon, VerifiedCheckIcon } from '#lib/icons/index.js';
	import { m } from '#lib/paraglide/messages.js';
	import { imageService } from '#lib/services/image-service.js';
	import type { ImageSearchResultDto } from '#lib/types/docker.js';
	import { destinationEnvironmentId } from '#lib/utils/environments.js';
	import { tryCatch } from '#lib/utils/try-catch.js';

	type Props = {
		open: boolean;
		onOpenChange?: (open: boolean) => void;
		onPullFinished?: (success: boolean, imageName?: string, error?: string) => Promise<void> | void;
	};

	let { open = $bindable(false), onOpenChange, onPullFinished = () => {} }: Props = $props();

	let query = $state('');
	let tag = $state('latest');
	let results = $state<ImageSearchResultDto[]>([]);
	let hasSearched = $state(false);
	let isSearching = $state(false);
	let pullingImageName = $state<string | null>(null);
	let pickedEnvironmentId = $state('');
	const environmentId = $derived(destinationEnvironmentId(pickedEnvironmentId, 'images:pull'));

	const normalizedTag = $derived(tag.trim() || 'latest');
	const canSearch = $derived(query.trim().length > 0 && !isSearching);

	function resetDialog() {
		query = '';
		tag = 'latest';
		results = [];
		hasSearched = false;
		pickedEnvironmentId = '';
	}

	function handleOpenChange(nextOpen: boolean) {
		if (!nextOpen && pullingImageName) return;
		open = nextOpen;
		onOpenChange?.(nextOpen);
		if (!nextOpen) {
			resetDialog();
		}
	}

	async function handleSearch() {
		const term = query.trim();
		if (!term) {
			toast.error(m.images_image_required());
			return;
		}
		isSearching = true;
		hasSearched = true;
		try {
			const operationResult1 = await tryCatch(
				(async () => {
					results = await imageService.searchImages(term, environmentId);
				})()
			);
			if (operationResult1.error !== null) {
				const error = operationResult1.error;

				console.error('Failed to search images:', error);
				toast.error(m.images_search_failed());
			}
		} finally {
			isSearching = false;
		}
	}

	function buildPullRef(name: string) {
		const trimmedName = name.trim();
		if (!trimmedName) return '';
		if (trimmedName.includes(':')) return trimmedName;
		return `${trimmedName}:${normalizedTag}`;
	}

	async function pullImage(name: string) {
		const imageRef = buildPullRef(name);
		if (!imageRef || pullingImageName) return;

		pullingImageName = imageRef;
		const targetEnvironmentId = environmentId;
		open = false;
		onOpenChange?.(false);
		resetDialog();

		const result = await imageService.pullImageStream(imageRef, undefined, targetEnvironmentId);
		pullingImageName = null;
		if (result.cancelled) return;
		if (!result.success) {
			const message = result.error || m.images_pull_failed();
			toast.error(message);
			await onPullFinished(false, imageRef, message);
			return;
		}

		toast.success(m.images_pull_success({ repoTag: imageRef }));
		await onPullFinished(true, imageRef);
	}
</script>

<ResponsiveDialog.Root
	{open}
	onOpenChange={handleOpenChange}
	title={m.images_search_registry()}
	description={m.images_search_registry_description()}
	contentClass="sm:max-w-180"
>
	{#snippet children()}
		<div class="grid gap-4 py-4">
			<EnvironmentDestinationSelect
				bind:value={() => environmentId, (value) => (pickedEnvironmentId = value)}
				permission="images:pull"
				variant="field"
			/>
			<div class="grid gap-3 sm:grid-cols-content-36-action">
				<div class="space-y-2">
					<Label for="image-registry-search-query">{m.images_search_query()}</Label>
					<InputGroup.Root>
						<InputGroup.Addon>
							<SearchIcon class="size-4" />
						</InputGroup.Addon>
						<InputGroup.Input
							id="image-registry-search-query"
							placeholder={m.images_search_query_placeholder()}
							bind:value={query}
							disabled={isSearching || !!pullingImageName}
							onkeydown={(event) => {
								if (event.key === 'Enter') {
									event.preventDefault();
									void handleSearch();
								}
							}}
						/>
					</InputGroup.Root>
				</div>

				<div class="space-y-2">
					<Label for="image-registry-search-tag">{m.tag()}</Label>
					<InputGroup.Root>
						<InputGroup.Input
							id="image-registry-search-tag"
							placeholder={m.images_tag_latest()}
							bind:value={tag}
							disabled={isSearching || !!pullingImageName}
						/>
					</InputGroup.Root>
				</div>

				<div class="flex items-end">
					<ArcaneButton
						action="inspect"
						type="button"
						customLabel={m.images_search_registry()}
						loading={isSearching}
						disabled={!canSearch}
						onclick={handleSearch}
					/>
				</div>
			</div>

			{#if results.length > 0}
				<div class="max-h-105 overflow-auto rounded-lg border border-border">
					{#each results as result (result.name)}
						<div class="grid gap-3 border-b p-3 last:border-b-0 sm:grid-cols-content-action sm:items-center">
							<div class="min-w-0 space-y-1">
								<div class="flex flex-wrap items-center gap-2">
									<span class="font-mono text-sm font-medium break-all">{result.name}</span>
									{#if result.official}
										<span class="text-success" title={m.common_verified()} aria-label={m.common_verified()}>
											<VerifiedCheckIcon class="size-3.5" aria-hidden="true" />
										</span>
									{/if}
								</div>
								<p class="line-clamp-2 text-sm text-muted-foreground">
									{result.description || m.common_no_description()}
								</p>
								<p class="text-xs text-muted-foreground">{m.images_search_stars({ count: result.starCount })}</p>
							</div>
							<ArcaneButton
								action="pull"
								type="button"
								size="sm"
								icon={DownloadIcon}
								customLabel={m.pull()}
								loading={pullingImageName === buildPullRef(result.name)}
								disabled={!!pullingImageName}
								onclick={() => pullImage(result.name)}
							/>
						</div>
					{/each}
				</div>
			{:else if hasSearched && !isSearching}
				<div class="rounded-lg border border-border bg-muted/30 px-4 py-8 text-center text-sm text-muted-foreground">
					{m.images_search_empty()}
				</div>
			{/if}
		</div>
	{/snippet}
</ResponsiveDialog.Root>