Skip to content

Modern Docker Management, Designed for Everyone

12.0 KB
Raw Blame
<script lang="ts">
	import { goto } from '$app/navigation';
	import { useQueryClient } from '@tanstack/svelte-query';
	import { tick, untrack } from 'svelte';
	import { toast } from 'svelte-sonner';

	import { ArcaneButton } from '#lib/components/arcane-button/index.js';
	import SearchInput from '#lib/components/form/search-input.svelte';
	import IfPermitted from '#lib/components/if-permitted.svelte';
	import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';
	import { Spinner } from '#lib/components/ui/spinner/index.js';
	import { EnvironmentsIcon, RemoteEnvironmentIcon, AddIcon, SettingsIcon } from '#lib/icons/index.js';
	import { m } from '#lib/paraglide/messages.js';
	import { queryKeys } from '#lib/query/query-keys.js';
	import { environmentManagementService } from '#lib/services/env-mgmt-service.js';
	import settingsStore from '#lib/stores/config-store.svelte.js';
	import { allEnvironmentsPreview, environmentStore } from '#lib/stores/environment.store.svelte.js';
	import type { Environment } from '#lib/types/environment.js';
	import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
	import { cn } from '#lib/utils.js';
	import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
	import { tryCatch } from '#lib/utils/try-catch.js';
	import { saveUserPreferences } from '#lib/utils/user-preferences.js';
	import { debounced } from '#lib/utils/ws.js';

	type Props = {
		open: boolean;
	};

	let { open = $bindable(false) }: Props = $props();
	const queryClient = useQueryClient();

	let searchQuery = $state('');
	let environments = $state<Environment[]>([]);
	let isLoading = $state(false);
	let isLoadingMore = $state(false);
	let currentPage = $state(1);
	let totalPages = $state(1);
	let scrollContainer = $state<HTMLDivElement | null>(null);
	let lastScrollTop = $state(0);
	let loadError = $state<string | null>(null);
	let currentRequestId = 0;

	const PAGE_SIZE = 10;

	const DEFAULT_REQUEST_OPTIONS: SearchPaginationSortRequest = {
		pagination: { page: 1, limit: PAGE_SIZE },
		sort: { column: 'name', direction: 'asc' },
		search: undefined
	};

	let requestOptions = $state<SearchPaginationSortRequest>(DEFAULT_REQUEST_OPTIONS);

	async function resetScrollToTop() {
		await tick();
		if (scrollContainer) scrollContainer.scrollTop = 0;
		lastScrollTop = 0;
	}

	function normalizeSearch(query: string): string | undefined {
		const trimmed = query.trim();
		return trimmed ? trimmed : undefined;
	}

	async function fetchEnvironments(options: SearchPaginationSortRequest, append: boolean, throwOnError = false) {
		currentRequestId++;
		const requestId = currentRequestId;
		loadError = null;
		requestOptions = options;

		if (append) {
			isLoadingMore = true;
		} else {
			isLoading = true;
			isLoadingMore = false;
		}

		try {
			const requestResult1 = await tryCatch(
				(async () => {
					const result = await queryClient.query({
						queryKey: queryKeys.environments.switcher(options),
						queryFn: () => environmentManagementService.getEnvironments(options),
						staleTime: 0
					});
					if (requestId !== currentRequestId) return;

					environments = append ? [...environments, ...result.data] : result.data;
					currentPage = result.pagination.currentPage;
					totalPages = result.pagination.totalPages;
				})()
			);
			if (requestResult1.error !== null) {
				const error = requestResult1.error;

				if (requestId !== currentRequestId) return;
				console.error('Failed to load environments:', error);
				loadError = 'Failed to load environments';
				toast.error(loadError);
				if (throwOnError) throw error;
			}
		} finally {
			if (requestId !== currentRequestId) return;
			isLoading = false;
			isLoadingMore = false;
		}
	}

	async function loadInitial() {
		environments = [];
		currentPage = 1;
		totalPages = 1;
		await resetScrollToTop();
		const options: SearchPaginationSortRequest = {
			...requestOptions,
			search: normalizeSearch(searchQuery),
			pagination: { page: 1, limit: PAGE_SIZE },
			sort: { column: 'name', direction: 'asc' }
		};
		await fetchEnvironments(options, false, true);
	}

	function resetDialogState() {
		// Invalidate any inflight request
		currentRequestId++;
		searchQuery = '';
		requestOptions = DEFAULT_REQUEST_OPTIONS;
		lastScrollTop = 0;
		loadError = null;
		// Keep environments around or clear? Clear so reopening always shows a clean slate
		environments = [];
		currentPage = 1;
		totalPages = 1;
	}

	function startInitialLoad() {
		void loadInitial();
	}

	function closeDialog() {
		open = false;
		resetDialogState();
	}

	function openSession(_node: HTMLElement) {
		untrack(startInitialLoad);
		return resetDialogState;
	}

	const debouncedSearch = debounced((query: string) => {
		// Prevent stale debounced callbacks from re-applying an old query (e.g. after clearing the input)
		if (query !== searchQuery) return;
		const options: SearchPaginationSortRequest = {
			...requestOptions,
			search: normalizeSearch(query),
			pagination: { page: 1, limit: PAGE_SIZE },
			sort: { column: 'name', direction: 'asc' }
		};
		void (async () => {
			if (query !== searchQuery) return;
			await resetScrollToTop();
			await fetchEnvironments(options, false, true);
		})();
	}, 300);

	function clearSearch() {
		searchQuery = '';
		const options: SearchPaginationSortRequest = {
			...requestOptions,
			search: undefined,
			pagination: { page: 1, limit: PAGE_SIZE },
			sort: { column: 'name', direction: 'asc' }
		};
		void (async () => {
			await resetScrollToTop();
			await fetchEnvironments(options, false, true);
		})();
	}

	function handleScroll(e: Event) {
		const target = e.target as HTMLDivElement;
		const { scrollTop, scrollHeight, clientHeight } = target;

		// If content isn't scrollable yet, don't auto-fetch more pages.
		if (scrollHeight <= clientHeight) return;

		// Only react to downward scrolling; prevents programmatic scrollTop resets from triggering load-more loops.
		if (scrollTop <= lastScrollTop) return;
		lastScrollTop = scrollTop;

		// Load more when user scrolls near the bottom (within 50px)
		if (scrollHeight - scrollTop - clientHeight < 50) {
			if (!isLoadingMore && currentPage < totalPages) {
				loadMoreEnvironments();
			}
		}
	}

	async function loadMoreEnvironments() {
		if (isLoading || isLoadingMore) return;
		if (currentPage >= totalPages) return;
		isLoadingMore = true;
		try {
			const operationResult1 = await tryCatch(
				(async () => {
					const options: SearchPaginationSortRequest = {
						...requestOptions,
						search: normalizeSearch(searchQuery),
						pagination: { page: currentPage + 1, limit: PAGE_SIZE },
						sort: { column: 'name', direction: 'asc' }
					};
					await fetchEnvironments(options, true, false);
				})()
			);
			if (operationResult1.error !== null) {
				// fetchEnvironments already handles toasts/errors (and stale-response protection)
			}
		} finally {
			// fetchEnvironments controls isLoadingMore; this is only a safety net.
			isLoadingMore = false;
		}
	}

	async function handleSelect(env: Environment) {
		if (!env || !env.enabled) return;

		await handleApiResultWithCallbacks({
			result: await tryCatch(environmentStore.setEnvironment(env)),
			message: m.environments_connect_error(),
			onSuccess: () => {
				closeDialog();
				toast.success(m.environments_switched_to({ name: env.name }));
			}
		});
	}

	function handleOpenSettings(env: Environment) {
		closeDialog();
		goto(`/environments/${env.id}`);
	}

	function getConnectionString(env: Environment): string {
		if (env.id === '0') {
			const host = settingsStore.current ? settingsStore.current?.dockerHost : 'unix:///var/run/docker.sock';
			return host || 'unix:///var/run/docker.sock';
		} else {
			return env.apiUrl;
		}
	}
</script>

<ResponsiveDialog bind:open title={m.sidebar_select_environment()} contentClass="max-w-2xl">
	<div class="m-2 flex flex-col gap-4">
		{#if open}
			<div class="hidden" {@attach openSession} aria-hidden="true"></div>
		{/if}
		<SearchInput
			onClear={clearSearch}
			placeholder={m.common_search()}
			value={searchQuery}
			oninput={(e) => {
				searchQuery = (e.target as HTMLInputElement).value;
				debouncedSearch(searchQuery);
			}}
		/>

		<div bind:this={scrollContainer} onscroll={handleScroll} class="max-h-screen-50 min-h-50 overflow-y-auto">
			{#if isLoading}
				<div class="flex items-center justify-center py-10">
					<Spinner class="size-6" />
				</div>
			{:else if loadError}
				<div class="py-10 text-center text-destructive">
					<p>{m.error_generic()}</p>
				</div>
			{:else if environments.length === 0}
				<div class="py-10 text-center text-muted-foreground">
					<EnvironmentsIcon class="mx-auto mb-4 size-12 opacity-50" />
					<p>{m.sidebar_no_environments()}</p>
				</div>
			{:else}
				<div class="space-y-1">
					{#if allEnvironmentsPreview.current}
						<div class="flex w-full items-center gap-3 rounded-lg border border-primary bg-primary/10 p-3 font-medium">
							<div class="flex size-8 shrink-0 items-center justify-center rounded-md border border-primary bg-primary">
								<EnvironmentsIcon class="size-4 text-primary-foreground" />
							</div>
							<span class="flex-1 truncate">{m.all_environments()}</span>
							<ArcaneButton
								action="base"
								tone="outline"
								size="sm"
								customLabel={m.all_environments_preview_turn_off()}
								onclick={() => saveUserPreferences({ allEnvironmentsPreview: false })}
							/>
						</div>
					{/if}
					{#each environments as env (env.id)}
						{@const isActive = !allEnvironmentsPreview.current && environmentStore.selected?.id === env.id}
						{@const isDisabled = !env.enabled || allEnvironmentsPreview.current}
						<div
							class={cn(
								'flex items-center gap-2 rounded-lg border p-1 transition-colors',
								isActive && 'border-primary bg-primary/10 font-medium',
								!isActive && !isDisabled && 'hover:bg-muted/50',
								!isActive && isDisabled && 'opacity-50'
							)}
						>
							<button
								type="button"
								onclick={() => !isActive && !isDisabled && handleSelect(env)}
								disabled={isDisabled}
								class={cn('flex min-w-0 flex-1 items-center gap-3 rounded-md p-2 text-left', isDisabled && 'cursor-not-allowed')}
							>
								<div
									class={cn(
										'flex size-8 shrink-0 items-center justify-center rounded-md border',
										isActive ? 'border-primary bg-primary' : 'border-border'
									)}
								>
									{#if env.id === '0'}
										<EnvironmentsIcon class={cn('size-4', isActive && 'text-primary-foreground')} />
									{:else}
										<RemoteEnvironmentIcon class={cn('size-4', isActive && 'text-primary-foreground')} />
									{/if}
								</div>
								<div class="flex min-w-0 flex-1 flex-col">
									<span class="truncate">{env.name}</span>
									<span class={cn('truncate text-xs', isActive ? 'text-primary/70' : 'text-muted-foreground')}>
										{getConnectionString(env)}
									</span>
								</div>
							</button>
							<div class="flex shrink-0 items-center gap-2 pr-2">
								{#if isActive}
									<span class="hidden text-xs font-medium text-primary sm:inline">
										{m.environments_current_environment()}
									</span>
								{/if}
								<ArcaneButton
									action="base"
									tone="ghost"
									size="icon"
									class="size-8"
									icon={SettingsIcon}
									showLabel={false}
									customLabel={m.settings()}
									onclick={() => handleOpenSettings(env)}
								/>
							</div>
						</div>
					{/each}

					{#if isLoadingMore}
						<div class="flex items-center justify-center py-4">
							<Spinner class="size-5" />
						</div>
					{/if}
				</div>
			{/if}
		</div>
	</div>

	{#snippet footer()}
		<div class="flex w-full items-center justify-between gap-2">
			<IfPermitted perm="environments:create">
				<ArcaneButton
					action="base"
					tone="outline"
					icon={AddIcon}
					customLabel={m.sidebar_manage_environments()}
					onclick={() => {
						closeDialog();
						goto('/environments');
					}}
				/>
				{#snippet fallback()}
					<div></div>
				{/snippet}
			</IfPermitted>
			<ArcaneButton action="base" tone="outline" customLabel={m.common_close()} onclick={closeDialog} />
		</div>
	{/snippet}
</ResponsiveDialog>