Skip to content

Modern Docker Management, Designed for Everyone

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

	import { ArcaneButton } from '#lib/components/arcane-button/index.js';
	import SwitchWithLabel from '#lib/components/form/labeled-switch.svelte';
	import SearchInput from '#lib/components/form/search-input.svelte';
	import IconImage from '#lib/components/icon-image.svelte';
	import EmptyState from '#lib/components/states/empty-state.svelte';
	import { Badge } from '#lib/components/ui/badge/index.js';
	import { Card } from '#lib/components/ui/card/index.js';
	import * as Collapsible from '#lib/components/ui/collapsible/index.js';
	import { Label } from '#lib/components/ui/label/index.js';
	import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';
	import { ScrollArea } from '#lib/components/ui/scroll-area/index.js';
	import * as Select from '#lib/components/ui/select/index.js';
	import {
		ArrowDownIcon,
		ArrowRightIcon,
		RegistryIcon,
		ProjectsIcon,
		DownloadIcon,
		SettingsIcon,
		FileTextIcon,
		SearchIcon
	} from '#lib/icons/index.js';
	import { m } from '#lib/paraglide/messages.js';
	import { templateService } from '#lib/services/template-service.js';
	import type { Template } from '#lib/types/swarm.js';
	import { hasPermission } from '#lib/utils/auth.js';
	import { tryCatch } from '#lib/utils/try-catch.js';

	interface Props {
		open: boolean;
		templates?: Template[];
		onSelect: (template: Template) => void;
		onDownloadSuccess?: () => void;
	}

	let { open = $bindable(), templates = [], onSelect, onDownloadSuccess }: Props = $props();
	void open;

	const loadingStates = new SvelteSet<string>();
	const canCreateTemplate = $derived(hasPermission('templates:create'));
	let sortBy = $state<'name-asc' | 'name-desc'>('name-asc');
	let groupByRegistry = $state(true);
	let searchQuery = $state('');
	let searchInput = $state<HTMLInputElement | null>(null);
	const selectTemplateMutation = createMutation(() => ({
		mutationFn: (template: Template) => templateService.getTemplateContent(template.id)
	}));
	const downloadTemplateMutation = createMutation(() => ({
		mutationFn: (template: Template) => templateService.download(template.id)
	}));

	const allTemplates = $derived(templates ?? []);
	const normalizedQuery = $derived(searchQuery.trim().toLowerCase());

	// Case-insensitive substring match against name, description, tags and registry label.
	const filteredTemplates = $derived.by(() => {
		if (!normalizedQuery) return allTemplates;
		return allTemplates.filter((template) =>
			[template.name, template.description ?? '', registryLabel(template), ...normalizeTags(template.metadata?.tags)].some(
				(field) => field.toLowerCase().includes(normalizedQuery)
			)
		);
	});

	const sortedTemplates = $derived.by(() => {
		const sorted = [...filteredTemplates];
		sorted.sort((a, b) => (sortBy === 'name-asc' ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name)));
		return sorted;
	});

	const groupedTemplates = $derived.by(() => {
		if (!groupByRegistry) return [];

		const groups = new Map<string, Template[]>();
		for (const template of sortedTemplates) {
			const key = registryLabel(template);
			const items = groups.get(key) ?? [];
			items.push(template);
			groups.set(key, items);
		}

		return Array.from(groups.entries())
			.map(([name, items]) => ({ name, items }))
			.sort((a, b) => a.name.localeCompare(b.name));
	});

	const filters = {
		'name-asc': m.templates_sort_name_asc(),
		'name-desc': m.templates_sort_name_desc()
	};

	function registryLabel(template: Template): string {
		return template.registry?.name ?? (template.isRemote ? m.templates_remote() : m.local());
	}

	function clearSearch() {
		searchQuery = '';
		searchInput?.focus();
	}

	// The dialog stays mounted while closed, so drop the query rather than showing stale results on reopen.
	function closeDialog() {
		searchQuery = '';
		open = false;
	}

	function normalizeTags(tags: unknown): string[] {
		if (!tags || tags === null || tags === undefined) return [];

		let list: unknown = tags;
		if (typeof tags === 'string') {
			const trimmed = tags.trim();
			if (!trimmed) return [];
			if (trimmed.startsWith('[')) {
				try {
					list = JSON.parse(trimmed);
				} catch {
					list = trimmed.split(',');
				}
			} else {
				list = trimmed.split(',');
			}
		}

		if (!Array.isArray(list)) return [];

		return list
			.map((t) => {
				if (t === null || t === undefined) return '';
				return String(t)
					.trim()
					.replace(/^["']|["']$/g, '');
			})
			.filter(Boolean)
			.map((t) => t.charAt(0).toUpperCase() + t.slice(1));
	}

	async function handleSelect(template: Template) {
		const loadingKey = template.id;
		loadingStates.add(loadingKey);

		try {
			const requestResult1 = await tryCatch(
				(async () => {
					const details = await selectTemplateMutation.mutateAsync(template);
					if (!details) {
						toast.error(m.templates_load_failed());
						return;
					}

					onSelect({
						...details.template,
						content: details.content,
						envContent: details.envContent
					});
					closeDialog();
					toast.success(m.templates_loaded_success({ name: template.name }));
				})()
			);
			if (requestResult1.error !== null) {
				const error = requestResult1.error;

				console.error('Error loading template:', error);
				toast.error(error instanceof Error ? error.message : m.templates_load_failed());
			}
		} finally {
			loadingStates.delete(loadingKey);
		}
	}

	async function handleDownload(template: Template) {
		if (!template.isRemote) return;

		const loadingKey = `download-${template.id}`;
		loadingStates.add(loadingKey);

		try {
			const operationResult1 = await tryCatch(
				(async () => {
					const result = await downloadTemplateMutation.mutateAsync(template);
					if (result) {
						toast.success(m.templates_downloaded_success({ name: template.name }));
						onDownloadSuccess?.();
					} else {
						toast.error(m.templates_download_failed());
					}
				})()
			);
			if (operationResult1.error !== null) {
				const error = operationResult1.error;

				console.error('Error downloading template:', error);
				toast.error(error instanceof Error ? error.message : m.templates_download_failed());
			}
		} finally {
			loadingStates.delete(loadingKey);
		}
	}
</script>

{#snippet templateCard(template: Template, showRegistry: boolean = false)}
	<Card interactive>
		<div class="p-4">
			<div class="mb-2 flex items-start justify-between gap-2">
				<div class="flex min-w-0 items-start gap-3">
					<IconImage
						src={template.metadata?.iconUrl}
						alt={template.name}
						fallback={template.isRemote ? RegistryIcon : ProjectsIcon}
						class="size-5"
						containerClass="size-9"
					/>
					<h4 class="min-w-0 truncate pr-2 font-semibold">{template.name}</h4>
				</div>
				<div class="ml-2 flex flex-shrink-0 flex-wrap items-center gap-1">
					{#if template.metadata?.version}
						<Badge variant="outline">v{template.metadata.version}</Badge>
					{/if}
					{#if template.metadata?.envUrl || template.envContent}
						<Badge variant="secondary">
							<SettingsIcon class="mr-1 size-3" />
							ENV
						</Badge>
					{/if}
				</div>
			</div>

			{#if showRegistry}
				<div class="mb-2">
					<Badge variant="secondary">
						{#if template.isRemote}
							<RegistryIcon class="size-3" />
						{:else}
							<ProjectsIcon class="size-3" />
						{/if}
						{registryLabel(template)}
					</Badge>
				</div>
			{/if}

			<p class="mb-3 line-clamp-2 text-sm text-muted-foreground">
				{template.description}
			</p>

			{#if normalizeTags(template.metadata?.tags).length > 0}
				<div class="mb-3 flex flex-wrap gap-1">
					<!-- Template metadata may contain duplicate tags; badges have no local state. -->
					{#each normalizeTags(template.metadata?.tags) as tag}
						<Badge variant="outline" size="sm">{tag}</Badge>
					{/each}
				</div>
			{/if}

			<div class="flex items-center justify-between gap-2">
				<div class="text-xs text-muted-foreground">
					{template.isRemote ? m.templates_remote_template_label() : m.templates_local_template_label()}
				</div>
				<div class="flex gap-2">
					{#if template.isRemote && canCreateTemplate}
						<ArcaneButton
							action="base"
							tone="outline"
							size="sm"
							onclick={() => handleDownload(template)}
							disabled={loadingStates.has(`download-${template.id}`)}
							loading={loadingStates.has(`download-${template.id}`)}
							icon={DownloadIcon}
							customLabel={m.templates_download()}
							loadingLabel={m.common_action_downloading()}
						/>
					{/if}
					<ArcaneButton
						action="base"
						size="sm"
						onclick={() => handleSelect(template)}
						disabled={loadingStates.has(template.id)}
						loading={loadingStates.has(template.id)}
						customLabel={m.templates_use_now()}
						loadingLabel={m.common_loading()}
					/>
				</div>
			</div>
		</div>
	</Card>
{/snippet}

{#snippet groupGrid(items: Template[])}
	<div class="px-6 pb-6">
		<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
			{#each items as template (template.id)}
				{@render templateCard(template)}
			{/each}
		</div>
	</div>
{/snippet}

<ResponsiveDialog
	bind:open
	title={m.templates_choose_title()}
	description={m.templates_choose_description()}
	contentClass="sm:max-w-225"
	onOpenChange={(next) => {
		if (!next) searchQuery = '';
	}}
>
	{#snippet children()}
		<div class="space-y-4">
			<SearchInput
				onClear={clearSearch}
				placeholder={m.templates_search_placeholder()}
				aria-label={m.common_search()}
				bind:value={searchQuery}
				bind:ref={searchInput}
			/>

			<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
				<div class="flex items-center gap-3">
					<SwitchWithLabel
						id="groupByRegistrySwitch"
						label={m.templates_group_by_registry_label()}
						description={m.templates_group_by_registry_description()}
						bind:checked={groupByRegistry}
					/>
				</div>
				<div class="flex items-center gap-3">
					<Label for="sortBy" class="whitespace-nowrap">{m.common_sort_by()}</Label>
					<Select.Root bind:value={sortBy} type="single">
						<Select.Trigger id="sortBy" class="h-9">
							{filters[sortBy]}
						</Select.Trigger>
						<Select.Content>
							{#each Object.entries(filters) as [value, label] (value)}
								<Select.Item {value}>{label}</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
				</div>
			</div>

			<ScrollArea class="max-h-(--max-height-screen-70)">
				{#if allTemplates.length === 0}
					<div class="py-10 text-center text-muted-foreground">
						<FileTextIcon class="mx-auto mb-4 size-12 opacity-50" />
						<p class="mb-2">{m.templates_no_templates()}</p>
						<p class="text-sm">
							{m.templates_add_registry_prompt_part1()}
							<a href="/customize/templates" class="text-primary hover:underline">{m.templates_template_settings()}</a>
							{m.templates_add_registry_prompt_part2()}
						</p>
					</div>
				{:else if filteredTemplates.length === 0}
					<EmptyState
						icon={SearchIcon}
						title={m.common_no_results_found()}
						description={m.common_no_results_hint()}
						actionLabel={m.common_clear_search()}
						onAction={clearSearch}
					/>
				{:else if groupByRegistry}
					<div class="space-y-3">
						{#each groupedTemplates as group (group.name)}
							{#if normalizedQuery}
								<!-- Static headings while searching so matches are never hidden in a collapsed group. -->
								<Card>
									<div class="flex items-center gap-2 px-4 py-3">
										<span class="font-semibold">{group.name}</span>
										<Badge variant="secondary" class="ml-2">{group.items.length}</Badge>
									</div>
									{@render groupGrid(group.items)}
								</Card>
							{:else}
								<Collapsible.Root class="w-full">
									<Card>
										<Collapsible.Trigger>
											{#snippet child({ props })}
												<button {...props} type="button" class="flex w-full items-center justify-between px-4 py-3 text-left">
													<div class="flex items-center gap-2">
														<ArrowDownIcon class="hidden size-4 data-[state=open]:block" />
														<ArrowRightIcon class="block size-4 data-[state=open]:hidden" />
														<span class="font-semibold">{group.name}</span>
														<Badge variant="secondary" class="ml-2">{group.items.length}</Badge>
													</div>
												</button>
											{/snippet}
										</Collapsible.Trigger>
										<Collapsible.Content>
											{@render groupGrid(group.items)}
										</Collapsible.Content>
									</Card>
								</Collapsible.Root>
							{/if}
						{/each}
					</div>
				{:else}
					<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
						{#each sortedTemplates as template (template.id)}
							{@render templateCard(template, true)}
						{/each}
					</div>
				{/if}
			</ScrollArea>
		</div>
	{/snippet}

	{#snippet footer()}
		<ArcaneButton action="cancel" onclick={closeDialog} />
	{/snippet}
</ResponsiveDialog>

<style>
	.line-clamp-2 {
		display: -webkit-box;
		line-clamp: 2;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}
</style>