Skip to content

Modern Docker Management, Designed for Everyone

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

	import AddTemplateRegistrySheet from '#lib/components/sheets/add-template-registry-sheet.svelte';
	import { TabBar, type TabItem } from '#lib/components/tab-bar/index.js';
	import * as Tabs from '#lib/components/ui/tabs/index.js';
	import { useUrlTab } from '#lib/hooks/use-url-tab.svelte.js';
	import { RegistryIcon, TemplateIcon, FolderOpenIcon } from '#lib/icons/index.js';
	import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';
	import { m } from '#lib/paraglide/messages.js';
	import { templateService } from '#lib/services/template-service.js';
	import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
	import type { TemplateRegistry } from '#lib/types/swarm.js';
	import { hasPermission } from '#lib/utils/auth.js';
	import { tryCatch } from '#lib/utils/try-catch.js';

	import RegistryManager from './components/registry-manager.svelte';
	import TemplateGallery from './components/template-gallery.svelte';

	let { data } = $props();

	let templates = $derived(data.templates);
	let registries = $derived<TemplateRegistry[]>(data.registries);
	let requestOptions = $derived<SearchPaginationSortRequest>(data.templateRequestOptions);
	const tabItems: TabItem[] = [
		{
			value: 'browse',
			label: m.templates_browse_templates(),
			icon: TemplateIcon
		},
		{
			value: 'registries',
			label: m.templates_manage_registries(),
			icon: RegistryIcon
		}
	];
	const urlTab = useUrlTab({
		validTabs: () => tabItems.map((tab) => tab.value),
		defaultTab: () => 'browse'
	});
	const activeView = $derived(urlTab.value);

	let isLoading = $state({
		addingRegistry: false,
		removing: {} as Record<string, boolean>,
		updating: {} as Record<string, boolean>
	});

	let showAddRegistrySheet = $state(false);

	async function updateRegistry(id: string, updates: { enabled?: boolean }) {
		if (isLoading.updating[id]) return;
		isLoading.updating[id] = true;

		try {
			const operationResult = await tryCatch(
				(async () => {
					const registry = registries.find((r) => r.id === id);
					if (!registry) {
						toast.error(m.templates_registry_not_found());
						delete isLoading.updating[id];
						return;
					}

					await templateService.updateRegistry(id, {
						name: registry.name,
						url: registry.url,
						description: registry.description,
						enabled: updates.enabled ?? registry.enabled
					});

					registries = await templateService.getRegistries();
					templates = await templateService.getTemplates(requestOptions);
					toast.success(m.common_update_success({ resource: m.resource_registry() }));
				})()
			);
			if (operationResult.error !== null) {
				const error = operationResult.error;
				console.error('Error updating registry:', error);
				toast.error(error instanceof Error ? error.message : m.registries_save_failed());
			}
		} finally {
			delete isLoading.updating[id];
		}
	}

	async function removeRegistry(id: string) {
		if (isLoading.removing[id]) return;
		isLoading.removing[id] = true;

		try {
			const operationResult = await tryCatch(
				(async () => {
					const reg = registries.find((r) => r.id === id);
					await templateService.deleteRegistry(id);
					registries = registries.filter((r) => r.id !== id);
					registries = await templateService.getRegistries();
					templates = await templateService.getTemplates(requestOptions);
					toast.success(
						reg
							? m.common_delete_success({ resource: `${m.resource_registry()} "${reg.url}"` })
							: m.templates_registry_removed_success()
					);
				})()
			);
			if (operationResult.error !== null) {
				const error = operationResult.error;

				console.error('Error removing registry:', error);
				toast.error(error instanceof Error ? error.message : m.registries_save_failed());
			}
		} finally {
			delete isLoading.removing[id];
		}
	}

	async function refreshTemplates() {
		const operationResult = await tryCatch(
			(async () => {
				templates = await templateService.getTemplates(requestOptions);
				toast.success(m.templates_refreshed());
			})()
		);
		if (operationResult.error !== null) {
			const error = operationResult.error;

			console.error('Error refreshing templates:', error);
			toast.error(m.common_refresh_failed({ resource: m.templates_title() }));
		}
	}

	async function handleRegistrySubmit(registry: { name: string; url: string; description?: string; enabled: boolean }) {
		isLoading.addingRegistry = true;

		try {
			const operationResult = await tryCatch(
				(async () => {
					await templateService.addRegistry({
						name: registry.name.trim(),
						url: registry.url.trim(),
						description: registry.description?.trim() || undefined,
						enabled: registry.enabled
					});

					registries = await templateService.getRegistries();
					templates = await templateService.getTemplates(requestOptions);
					showAddRegistrySheet = false;

					toast.success(m.common_create_success({ resource: m.resource_registry() }));
				})()
			);
			if (operationResult.error !== null) {
				const error = operationResult.error;

				console.error('Error adding registry:', error);
				toast.error(error instanceof Error ? error.message : m.registries_save_failed());
			}
		} finally {
			isLoading.addingRegistry = false;
		}
	}

	const canCreateTemplate = $derived(hasPermission('templates:create'));
	const canUpdateTemplate = $derived(hasPermission('templates:update'));

	const actionButtons: ActionButton[] = $derived.by(() => {
		const buttons: ActionButton[] = [];
		if (canCreateTemplate) {
			buttons.push({
				id: 'create',
				action: 'create',
				placement: 'primary',
				label: m.templates_create_template(),
				onclick: () => goto('/customize/templates/create')
			});
		}
		if (canUpdateTemplate) {
			buttons.push({
				id: 'default',
				action: 'edit',
				label: m.templates_edit_default(),
				onclick: () => goto('/customize/templates/default')
			});
		}
		buttons.push({
			id: 'refresh',
			action: 'refresh',
			placement: 'secondary',
			iconOnly: true,
			label: m.common_refresh(),
			onclick: refreshTemplates
		});
		return buttons;
	});

	const localTemplatesCount = $derived(templates.data?.filter((t) => !t.isRemote).length ?? 0);
	const remoteTemplatesCount = $derived(templates.data?.filter((t) => t.isRemote).length ?? 0);

	const statCards: StatCardConfig[] = $derived([
		{
			title: m.templates_local_templates(),
			value: localTemplatesCount,
			icon: FolderOpenIcon,
			iconColor: 'text-info'
		},
		{
			title: m.templates_remote_templates(),
			value: remoteTemplatesCount,
			icon: RegistryIcon,
			iconColor: 'text-success'
		},
		{
			title: m.templates_registries(),
			value: registries.length,
			icon: TemplateIcon,
			iconColor: 'text-purple'
		}
	]);
</script>

<ResourcePageLayout title={m.templates_title()} subtitle={m.templates_subtitle()} {actionButtons} {statCards}>
	{#snippet mainContent()}
		<div class="space-y-6">
			<Tabs.Root value={activeView}>
				<div class="pb-6">
					<div class="w-fit">
						<TabBar items={tabItems} value={activeView} onValueChange={urlTab.select} />
					</div>
				</div>

				<Tabs.Content value="browse">
					<TemplateGallery bind:templates bind:requestOptions />
				</Tabs.Content>

				<Tabs.Content value="registries">
					<RegistryManager
						{registries}
						{isLoading}
						onAddRegistry={() => (showAddRegistrySheet = true)}
						onUpdateRegistry={updateRegistry}
						onRemoveRegistry={removeRegistry}
					/>
				</Tabs.Content>
			</Tabs.Root>
		</div>
	{/snippet}

	{#snippet additionalContent()}
		<AddTemplateRegistrySheet
			bind:open={showAddRegistrySheet}
			onSubmit={handleRegistrySubmit}
			isLoading={isLoading.addingRegistry}
		/>
	{/snippet}
</ResourcePageLayout>