import { useCallback, useEffect, useRef, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { ChevronDown, FileIcon, FolderOpen, RotateCcw } from "lucide-react"; import { Button } from "~/client/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/client/components/ui/card"; import { Input } from "~/client/components/ui/input"; import { Label } from "~/client/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~/client/components/ui/select"; import { AlertDialog, AlertDialogAction, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "~/client/components/ui/alert-dialog"; import { PathSelector } from "~/client/components/path-selector"; import { FileTree } from "~/client/components/file-tree"; import { RestoreProgress } from "~/client/components/restore-progress"; import { listSnapshotFilesOptions, restoreSnapshotMutation } from "~/client/api-client/@tanstack/react-query.gen"; import { useFileBrowser } from "~/client/hooks/use-file-browser"; import { type RestoreCompletedEvent, useServerEvents } from "~/client/hooks/use-server-events"; import { OVERWRITE_MODES, type OverwriteMode } from "~/schemas/restic"; import type { Repository, Snapshot } from "~/client/lib/types"; import { handleRepositoryError } from "~/client/lib/errors"; import { useNavigate } from "@tanstack/react-router"; type RestoreLocation = "original" | "custom"; interface RestoreFormProps { snapshot: Snapshot; repository: Repository; snapshotId: string; returnPath: string; } export function RestoreForm({ snapshot, repository, snapshotId, returnPath }: RestoreFormProps) { const navigate = useNavigate(); const { addEventListener } = useServerEvents(); const queryClient = useQueryClient(); const volumeBasePath = snapshot.paths[0]?.match(/^(.*?_data)(\/|$)/)?.[1] || "/"; const [restoreLocation, setRestoreLocation] = useState("original"); const [customTargetPath, setCustomTargetPath] = useState(""); const [overwriteMode, setOverwriteMode] = useState("always"); const [showAdvanced, setShowAdvanced] = useState(false); const [excludeXattr, setExcludeXattr] = useState(""); const [isRestoreActive, setIsRestoreActive] = useState(false); const [restoreResult, setRestoreResult] = useState(null); const [showRestoreResultAlert, setShowRestoreResultAlert] = useState(false); const restoreCompletedRef = useRef(false); const [selectedPaths, setSelectedPaths] = useState>(new Set()); useEffect(() => { const unsubscribeStarted = addEventListener("restore:started", (startedData) => { if (startedData.repositoryId === repository.id && startedData.snapshotId === snapshotId) { restoreCompletedRef.current = false; setIsRestoreActive(true); setRestoreResult(null); setShowRestoreResultAlert(false); } }); const unsubscribeProgress = addEventListener("restore:progress", (progressData) => { if (progressData.repositoryId === repository.id && progressData.snapshotId === snapshotId) { if (restoreCompletedRef.current) { return; } setIsRestoreActive(true); } }); const unsubscribeCompleted = addEventListener("restore:completed", (completedData) => { if (completedData.repositoryId === repository.id && completedData.snapshotId === snapshotId) { restoreCompletedRef.current = true; setIsRestoreActive(false); setRestoreResult(completedData); setShowRestoreResultAlert(true); } }); return () => { unsubscribeStarted(); unsubscribeProgress(); unsubscribeCompleted(); }; }, [addEventListener, repository.id, snapshotId]); const { data: filesData, isLoading: filesLoading } = useQuery({ ...listSnapshotFilesOptions({ path: { id: repository.id, snapshotId }, query: { path: volumeBasePath }, }), }); const stripBasePath = useCallback( (path: string): string => { if (!volumeBasePath) return path; if (path === volumeBasePath) return "/"; if (path.startsWith(`${volumeBasePath}/`)) { const stripped = path.slice(volumeBasePath.length); return stripped; } return path; }, [volumeBasePath], ); const addBasePath = useCallback( (displayPath: string): string => { const vbp = volumeBasePath === "/" ? "" : volumeBasePath; if (!vbp) return displayPath; if (displayPath === "/") return vbp; return `${vbp}${displayPath}`; }, [volumeBasePath], ); const fileBrowser = useFileBrowser({ initialData: filesData, isLoading: filesLoading, fetchFolder: async (path, offset = 0) => { return await queryClient.ensureQueryData( listSnapshotFilesOptions({ path: { id: repository.id, snapshotId }, query: { path, offset: offset.toString(), limit: "500" }, }), ); }, prefetchFolder: (path) => { void queryClient.prefetchQuery( listSnapshotFilesOptions({ path: { id: repository.id, snapshotId }, query: { path, offset: "0", limit: "500" }, }), ); }, pathTransform: { strip: stripBasePath, add: addBasePath, }, }); const { mutate: restoreSnapshot, isPending: isRestoring } = useMutation({ ...restoreSnapshotMutation(), onError: (error) => { restoreCompletedRef.current = true; setIsRestoreActive(false); handleRepositoryError("Restore failed", error, repository.id); }, }); const handleRestore = useCallback(() => { const excludeXattrArray = excludeXattr ?.split(",") .map((s) => s.trim()) .filter(Boolean); const isCustomLocation = restoreLocation === "custom"; const targetPath = isCustomLocation && customTargetPath.trim() ? customTargetPath.trim() : undefined; const pathsArray = Array.from(selectedPaths); const includePaths = pathsArray.map((path) => addBasePath(path)); restoreCompletedRef.current = false; setIsRestoreActive(true); setRestoreResult(null); setShowRestoreResultAlert(false); restoreSnapshot({ path: { id: repository.id }, body: { snapshotId, include: includePaths.length > 0 ? includePaths : undefined, excludeXattr: excludeXattrArray && excludeXattrArray.length > 0 ? excludeXattrArray : undefined, targetPath, overwrite: overwriteMode, }, }); }, [ repository.id, snapshotId, excludeXattr, restoreLocation, customTargetPath, selectedPaths, addBasePath, overwriteMode, restoreSnapshot, ]); const acknowledgeRestoreResult = useCallback(() => { setShowRestoreResultAlert(false); setRestoreResult(null); }, []); const handleResultAlertOpenChange = useCallback((open: boolean) => { if (open) { setShowRestoreResultAlert(true); } }, []); const canRestore = restoreLocation === "original" || customTargetPath.trim(); const isRestoreRunning = isRestoring || isRestoreActive; return (

Restore Snapshot

{repository.name} / {snapshotId}

{isRestoreRunning && } Restore Location Choose where to restore the files
{restoreLocation === "custom" && (

Files will be restored directly to this path

)}
Overwrite Mode How to handle existing files

{overwriteMode === OVERWRITE_MODES.always && "Existing files will always be replaced with the snapshot version."} {overwriteMode === OVERWRITE_MODES.ifChanged && "Files are only replaced if their content differs from the snapshot."} {overwriteMode === OVERWRITE_MODES.ifNewer && "Files are only replaced if the snapshot version has a newer modification time."} {overwriteMode === OVERWRITE_MODES.never && "Existing files will never be replaced, only missing files are restored."}

setShowAdvanced(!showAdvanced)}>
Advanced options
{showAdvanced && (
setExcludeXattr(e.target.value)} />

Exclude specific extended attributes during restore (comma-separated)

)}
Select Files to Restore {selectedPaths.size > 0 ? `${selectedPaths.size} ${selectedPaths.size === 1 ? "item" : "items"} selected` : "Select specific files or folders, or leave empty to restore everything"} {fileBrowser.isLoading && (

Loading files...

)} {fileBrowser.isEmpty && (

No files in this snapshot

)} {!fileBrowser.isLoading && !fileBrowser.isEmpty && (
)}
{restoreResult?.status === "success" ? "Restore completed" : "Restore failed"} {restoreResult?.status === "success" ? `Snapshot ${snapshotId} was restored successfully.` : restoreResult?.error || `Snapshot ${snapshotId} could not be restored.`} OK
); }