Skip to content

Modern Docker Management, Designed for Everyone

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

	import { ArcaneButton } from '#lib/components/arcane-button/index.js';
	import CreateFolderDialog from '#lib/components/file-browser/create-folder-dialog.svelte';
	import FileBreadcrumb from '#lib/components/file-browser/file-breadcrumb.svelte';
	import FileList from '#lib/components/file-browser/file-list.svelte';
	import FileUploadDialog from '#lib/components/file-browser/file-upload-dialog.svelte';
	import { sortFileEntries, type FileProvider } from '#lib/components/file-browser/index.js';
	import { EmptyState } from '#lib/components/states/index.js';
	import * as Dialog from '#lib/components/ui/dialog/index.js';
	import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
	import { Label } from '#lib/components/ui/label/index.js';
	import { Spinner } from '#lib/components/ui/spinner/index.js';
	import { Textarea } from '#lib/components/ui/textarea/index.js';
	import { UseClipboard } from '#lib/hooks/use-clipboard.svelte.js';
	import { UploadIcon, MoveToFolderIcon, EllipsisIcon, CopyIcon, AlertTriangleIcon } from '#lib/icons/index.js';
	import { m } from '#lib/paraglide/messages.js';
	import { queryKeys } from '#lib/query/query-keys.js';
	import type { UploadProgressCallback } from '#lib/services/upload-service.js';
	import type { FileEntry } from '#lib/types/shared.js';
	import { extractApiErrorMessage } from '#lib/utils/api.js';
	import { hasPermission } from '#lib/utils/auth.js';
	import { tryCatch } from '#lib/utils/try-catch.js';

	let {
		provider,
		rootLabel = '/builds',
		rootPath,
		persistKey = 'arcane-build-workspace-table',
		onSelectContext,
		environmentId: envId
	}: {
		provider: FileProvider;
		rootLabel?: string;
		rootPath?: string;
		persistKey?: string;
		onSelectContext?: (path: string) => void;
		environmentId: string;
	} = $props();

	let currentPath = $state('/');
	const canBuildImage = $derived(hasPermission('images:build', envId));
	const queryClient = useQueryClient();

	const filesQuery = createQuery(() => ({
		queryKey: queryKeys.buildWorkspace.list(envId, currentPath),
		queryFn: () => provider.list(currentPath)
	}));

	const files = $derived.by<FileEntry[]>(() => {
		const result = (filesQuery.data ?? []).slice();
		return sortFileEntries(result);
	});

	const loading = $derived(filesQuery.isPending);
	const error = $derived(filesQuery.error ? extractApiErrorMessage(filesQuery.error) : null);
	const canOpenBuildSettings = $derived(hasPermission('settings:read'));

	let showCreateFolder = $state(false);
	let showUpload = $state(false);

	let editorOpen = $state(false);
	let editorFile = $state<FileEntry | null>(null);
	let editorDraft = $state<{ envId: string; path: string; content: string } | null>(null);
	let editorSaving = $state(false);

	const editorContentQuery = createQuery(() => ({
		queryKey: editorFile
			? queryKeys.buildWorkspace.content(envId, editorFile.path)
			: (['build-workspace', envId, 'content', 'none'] as const),
		queryFn: () => provider.getContent(editorFile!.path),
		enabled: !!editorFile && editorOpen
	}));

	const editorContent = $derived.by(() => {
		if (editorDraft?.envId === envId && editorDraft.path === editorFile?.path) return editorDraft.content;
		if (!editorContentQuery.data) return '';
		return b64DecodeUnicode(editorContentQuery.data.content);
	});

	const editorLoading = $derived(editorContentQuery.isPending || editorContentQuery.isFetching);
	const editorError = $derived.by(() => {
		const err = editorContentQuery.error as any;
		if (!err) return null;
		return err.message || 'Failed to load file';
	});

	const mkdirMutation = createMutation(() => ({
		mutationKey: ['build-workspace', 'mkdir', envId],
		mutationFn: (path: string) => provider.mkdir(path),
		onSuccess: async () => {
			await queryClient.invalidateQueries({ queryKey: queryKeys.buildWorkspace.listPrefix(envId) });
		}
	}));

	const uploadMutation = createMutation(() => ({
		mutationKey: ['build-workspace', 'upload', envId],
		mutationFn: ({ path, file, onProgress }: { path: string; file: File; onProgress?: UploadProgressCallback }) =>
			provider.upload(path, file, onProgress),
		onSuccess: async () => {
			await queryClient.invalidateQueries({ queryKey: queryKeys.buildWorkspace.listPrefix(envId) });
		}
	}));

	const deleteMutation = createMutation(() => ({
		mutationKey: ['build-workspace', 'delete', envId],
		mutationFn: (path: string) => provider.delete(path),
		onSuccess: async () => {
			await queryClient.invalidateQueries({ queryKey: queryKeys.buildWorkspace.listPrefix(envId) });
		}
	}));

	const downloadMutation = createMutation(() => ({
		mutationKey: ['build-workspace', 'download', envId],
		mutationFn: (path: string) => provider.download(path)
	}));

	const clipboard = new UseClipboard();

	const absoluteCurrentPath = $derived.by(() => {
		const root = (rootPath ?? '').trim();
		if (!root) return currentPath;
		const normalizedRoot = root.endsWith('/') ? root.slice(0, -1) : root;
		if (currentPath === '/' || currentPath === '') return normalizedRoot;
		return `${normalizedRoot}${currentPath.startsWith('/') ? '' : '/'}${currentPath}`;
	});

	function b64DecodeUnicode(str: string) {
		try {
			return decodeURIComponent(
				atob(str)
					.split('')
					.map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
					.join('')
			);
		} catch {
			return atob(str);
		}
	}

	function handleNavigate(path: string) {
		currentPath = path;
		onSelectContext?.(path);
	}

	async function handleCopyPath() {
		const status = await clipboard.copy(absoluteCurrentPath);
		if (status === 'success') {
			toast.success(m.common_copied_path());
			return;
		}
		toast.error(m.common_copy_path_error());
	}

	async function openEditor(file: FileEntry) {
		if (file.isDirectory) return;
		editorFile = file;
		editorOpen = true;
		editorDraft = null;
	}

	async function handleSaveFile() {
		if (!editorFile) return;
		editorSaving = true;
		try {
			const operationResult = await tryCatch(
				(async () => {
					const dirPath = editorFile.path.split('/').slice(0, -1).join('/') || '/';
					const file = new File([editorContent], editorFile.name, { type: 'text/plain' });
					await uploadMutation.mutateAsync({ path: dirPath, file });
					await queryClient.invalidateQueries({ queryKey: queryKeys.buildWorkspace.content(envId, editorFile.path) });
					toast.success(m.common_file_saved());
					editorOpen = false;
					await filesQuery.refetch();
				})()
			);
			if (operationResult.error !== null) {
				const e = operationResult.error;

				toast.error(e.message || 'Failed to save file');
			}
		} finally {
			editorSaving = false;
		}
	}
</script>

<div class="flex h-full min-h-0 flex-col gap-5">
	<div class="flex flex-wrap items-start justify-between gap-4 border-b border-border/40 pt-1 pb-4">
		<div class="min-w-0 flex-1 space-y-3">
			<FileBreadcrumb path={currentPath} {rootLabel} onNavigate={handleNavigate} />
			<div class="flex min-w-0 items-center gap-3">
				<div class="min-w-0 flex-1 truncate font-mono text-2xs text-muted-foreground" title={absoluteCurrentPath}>
					{absoluteCurrentPath}
				</div>
			</div>
		</div>

		<div class="flex shrink-0 flex-wrap items-center justify-end gap-3">
			<DropdownMenu.Root>
				<DropdownMenu.Trigger>
					{#snippet child({ props })}
						<ArcaneButton
							{...props}
							action="base"
							tone="outline"
							size="icon"
							class="size-9"
							icon={EllipsisIcon}
							customLabel={m.common_actions()}
						/>
					{/snippet}
				</DropdownMenu.Trigger>
				<DropdownMenu.Content align="end" class="min-w-45">
					<DropdownMenu.Item onclick={handleCopyPath}>
						<CopyIcon class="size-4" />
						Copy current path
					</DropdownMenu.Item>
					{#if canBuildImage}
						<DropdownMenu.Separator />
						<DropdownMenu.Item onclick={() => (showCreateFolder = true)}>
							<MoveToFolderIcon class="size-4" />
							{m.new_folder()}
						</DropdownMenu.Item>
						<DropdownMenu.Item onclick={() => (showUpload = true)}>
							<UploadIcon class="size-4" />
							{m.workspace_upload_files()}
						</DropdownMenu.Item>
					{/if}
				</DropdownMenu.Content>
			</DropdownMenu.Root>
		</div>
	</div>

	{#if loading}
		<div class="flex flex-1 items-center justify-center p-8">
			<Spinner tone="muted" class="size-8" />
		</div>
	{:else if error}
		<EmptyState
			icon={AlertTriangleIcon}
			title={m.build_workspace_unavailable_title()}
			description={m.build_workspace_unavailable_description()}
		>
			<p class="max-w-md text-xs break-words text-muted-foreground">{error}</p>
			<div class="flex flex-wrap justify-center gap-2">
				<ArcaneButton action="refresh" customLabel={m.common_retry()} onclick={() => filesQuery.refetch()} />
				{#if canOpenBuildSettings}
					<ArcaneButton action="base" tone="outline" customLabel={m.build_workspace_open_settings()} href="/settings/builds" />
				{:else}
					<p class="text-xs text-muted-foreground">{m.build_workspace_ask_admin()}</p>
				{/if}
			</div>
		</EmptyState>
	{:else}
		<div class="min-h-0 flex-1 overflow-hidden">
			<FileList
				{files}
				{currentPath}
				{persistKey}
				minimal
				onNavigate={handleNavigate}
				onRefresh={() => filesQuery.refetch()}
				onDelete={canBuildImage
					? async (file) => {
							await deleteMutation.mutateAsync(file.path);
							await filesQuery.refetch();
						}
					: undefined}
				onDownload={async (file) => {
					await downloadMutation.mutateAsync(file.path);
				}}
				onPreview={openEditor}
			/>
		</div>
	{/if}
</div>

<CreateFolderDialog
	bind:open={showCreateFolder}
	{currentPath}
	onCreate={async (name) => {
		const fullPath = currentPath === '/' ? `/${name}` : `${currentPath}/${name}`;
		await mkdirMutation.mutateAsync(fullPath);
		await filesQuery.refetch();
	}}
/>

<FileUploadDialog
	bind:open={showUpload}
	{currentPath}
	onUpload={async (file, onProgress) => {
		await uploadMutation.mutateAsync({ path: currentPath, file, onProgress });
		await filesQuery.refetch();
	}}
/>

<Dialog.Root bind:open={editorOpen}>
	<Dialog.Content class="max-w-3xl">
		<Dialog.Header>
			<Dialog.Title>{editorFile?.name ?? 'File'}</Dialog.Title>
			<Dialog.Description class="break-all">{editorFile?.path}</Dialog.Description>
		</Dialog.Header>
		<div class="space-y-4 py-2">
			{#if editorLoading}
				<div class="flex items-center justify-center py-8">
					<Spinner tone="muted" class="size-8" />
				</div>
			{:else if editorError}
				<div class="rounded-lg border border-destructive/20 bg-destructive/10 p-4 text-sm text-destructive">
					{editorError}
				</div>
			{:else}
				<div class="space-y-2">
					<Label>{m.build_file_contents()}</Label>
					<Textarea
						rows={18}
						bind:value={
							() => editorContent,
							(content) => {
								editorDraft = { envId, path: editorFile?.path ?? '', content };
							}
						}
						mono
						size="sm"
					/>
					<p class="text-xs text-muted-foreground">{m.build_saving_overwrite()}</p>
				</div>
			{/if}
		</div>
		<Dialog.Footer class="flex flex-col-reverse sm:flex-row sm:justify-end">
			<ArcaneButton action="cancel" tone="outline" type="button" onclick={() => (editorOpen = false)} />
			{#if canBuildImage}
				<ArcaneButton
					action="save"
					type="button"
					onclick={handleSaveFile}
					disabled={editorLoading || editorSaving || !!editorError}
					loading={editorSaving}
				/>
			{/if}
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>