Skip to content

A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.

feat: adds the ability to browse snapshot files

towfiqid8313af6f2de
diff --git a/backend/src/services/BackupServices.ts b/backend/src/services/BackupServices.ts
index 4357c97..7e17e56 100644
--- a/backend/src/services/BackupServices.ts
+++ b/backend/src/services/BackupServices.ts
@@ -20,6 +20,7 @@ import { SnapShotFile } from '../types/restic';
import { Backup } from '../db/schema/backups';
import { BackupMirror } from '../types/backups';
import { PlanStats } from '../types/plans';
+import { AppError, NotFoundError } from '../utils/AppError';
export class BackupService {
constructor(
@@ -203,18 +204,25 @@ export class BackupService {
}
return progressResult.result;
}
-
async getSnapshotFiles(backupId: string, replicationId?: string): Promise<SnapShotFile[]> {
const backup = await this.backupStore.getById(backupId);
if (!backup) {
throw new Error('Backup not found');
}
const backupDevice = backup.sourceId ? backup.sourceId : 'main';
- const strategy = this.getSnapshotStrategy(backupDevice);
+ const backupMethod = backup.method;
+
// If replicationId is provided, browse from mirror storage
let effectiveStorageId = backup.storageId as string;
let effectiveStoragePath = backup.storagePath as string;
if (replicationId) {
+ //if replicationId is passed, its a replication storage ID, so find the storage path and name from the backup's mirrors
+ if (backup.mirrors && backup.mirrors.length > 0) {
+ const planReplicationStorage = backup.mirrors.find(s => s.replicationId === replicationId);
+ if (!planReplicationStorage) {
+ throw new NotFoundError('Replication Storage not found in Plan settings');
+ }
+ }
const mirrors = (backup.mirrors || []) as BackupMirror[];
const mirror = mirrors.find(m => m.replicationId === replicationId);
if (mirror) {
@@ -223,23 +231,20 @@ export class BackupService {
}
}
const storageName = await this.getStorageName(effectiveStorageId);
- const snapshotFilesResult = await strategy.getSnapshotFiles(
- backup.planId as string,
- backup.id as string,
- {
- storageName,
- storagePath: effectiveStoragePath,
- encryption: backup.encryption as boolean,
- }
- );
- if (!snapshotFilesResult.success || !Array.isArray(snapshotFilesResult.result)) {
- throw new Error(
- typeof snapshotFilesResult.result === 'string'
- ? snapshotFilesResult.result
- : 'Failed to get Snapshot Files'
+ const strategy = this.getSnapshotStrategy(backupDevice, backupMethod);
+ const browseRes = await strategy.getSnapshotFiles(backup.planId as string, backup.id, {
+ storagePath: effectiveStoragePath || '',
+ storageName: storageName,
+ encryption: backup.encryption || false,
+ skipCache: !!replicationId,
+ });
+ if (!browseRes.success || !browseRes.result || typeof browseRes.result === 'string') {
+ throw new AppError(
+ 500,
+ typeof browseRes.result === 'string' ? browseRes.result : 'Browse snapshot failed'
);
}
- return snapshotFilesResult.result;
+ return browseRes.result;
}
async updateBackup(backupId: string, data: Partial<Backup>): Promise<any> {
diff --git a/backend/src/strategies/snapshot/SnapshotStrategy.ts b/backend/src/strategies/snapshot/SnapshotStrategy.ts
index 5729cbd..63fe07d 100644
--- a/backend/src/strategies/snapshot/SnapshotStrategy.ts
+++ b/backend/src/strategies/snapshot/SnapshotStrategy.ts
@@ -37,7 +37,13 @@ export interface SnapshotStrategy {
getSnapshotFiles(
planId: string,
backupId: string,
- options: { storagePath: string; storageName: string; encryption: boolean }
+ options: {
+ storagePath: string;
+ storageName: string;
+ encryption: boolean;
+ isSrc?: boolean;
+ skipCache?: boolean;
+ }
): Promise<{ success: boolean; result: SnapShotFile[] | string }>;
retryFailedReplication(
planId: string,
diff --git a/frontend/src/components/Plan/Backups/Backups.tsx b/frontend/src/components/Plan/Backups/Backups.tsx
index 9e8d44e..b8545bc 100644
--- a/frontend/src/components/Plan/Backups/Backups.tsx
+++ b/frontend/src/components/Plan/Backups/Backups.tsx
@@ -6,7 +6,14 @@ import { formatBytes, formatDateTime, formatDuration, formatNumberToK, timeAgo }
import Icon from '../../common/Icon/Icon';
import classes from './Backups.module.scss';
import ActionModal from '../../common/ActionModal/ActionModal';
-import { useCancelBackupDownload, useDeleteBackup, useDownloadBackup, useGetBackupDownload, useUpdateBackup } from '../../../services/backups';
+import {
+ useCancelBackupDownload,
+ useDeleteBackup,
+ useDownloadBackup,
+ useGetBackupDownload,
+ useUpdateBackup,
+ useBrowseSnapshot,
+} from '../../../services/backups';
import { useQueryClient } from '@tanstack/react-query';
import RestoreWizard from '../../Restore/RestoreWizard/RestoreWizard';
import StatusLabel from '../../common/StatusLabel/StatusLabel';
@@ -14,6 +21,7 @@ import BackupEvents from '../BackupEvents/BackupEvents';
import Input from '../../common/form/Input/Input';
import MirrorStatusBadge from '../Mirrors/MirrorStatusBadge';
import MirrorStorageSelectorModal from '../Mirrors/MirrorStorageSelectorModal';
+import { SidePanel, SnapshotViewer } from '../..';
const DownloadLabel = ({ download, downloadBackup }: { download: Backup['download']; downloadBackup: () => void }) => {
if (download?.status === 'started') {
@@ -92,6 +100,7 @@ const Backups = ({
const [showDeleteModal, setShowDeleteModal] = useState<Backup | false>(false);
const [showRestoreModal, setShowRestoreModal] = useState<Backup | false>(false);
const [showBackupEvents, setShowBackupEvents] = useState<false | string>(false);
+ const [showSnapshotViewer, setShowSnapshotViewer] = useState<Backup | false>(false);
const [showEditModal, setShowEditModal] = useState<Backup | false>(false);
const [showStorageSelector, setShowStorageSelector] = useState<Backup | false>(false);
const queryClient = useQueryClient();
@@ -100,8 +109,11 @@ const Backups = ({
const downloadBackupMutation = useDownloadBackup();
const cancelDownloadMutation = useCancelBackupDownload();
const getDownloadMutation = useGetBackupDownload();
+ const browseSnapshotMutation = useBrowseSnapshot();
const isSync = method === 'sync';
+ const snapshotFiles = browseSnapshotMutation.data?.result;
+
console.log('backups :', backups);
const removeBackup = (backup: Backup) => {
@@ -289,6 +301,20 @@ const Backups = ({
<Icon type={isDownloading ? 'close' : 'download'} size={14} /> {isDownloading ? 'Cancel Download' : 'Download'}
</button>
)}
+ {!isSync && status === 'completed' && active && (
+ <button
+ onClick={() => {
+ toast.promise(browseSnapshotMutation.mutateAsync({ backupId: id }), {
+ pending: 'Getting Snapshot Data...',
+ error: 'Failed to Get Snapshot Data.',
+ });
+ setShowSnapOptions(false);
+ setShowSnapshotViewer(snapshot);
+ }}
+ >
+ <Icon type="folders" size={14} /> Browse
+ </button>
+ )}
{status === 'completed' && active && (
<button
className={isDownloading ? 'notAllowed' : ''}
@@ -414,6 +440,19 @@ const Backups = ({
onClose={() => setShowStorageSelector(false)}
/>
)}
+ {showSnapshotViewer && showSnapshotViewer.id && browseSnapshotMutation.isSuccess && (
+ <SidePanel width="100%" title="Browse Snapshot" icon={<Icon type={'folders'} size={20} />} close={() => setShowSnapshotViewer(false)}>
+ <SnapshotViewer
+ files={snapshotFiles || []}
+ backup={showSnapshotViewer}
+ planId={planId}
+ isSync={isSync}
+ onClose={() => setShowSnapshotViewer(false)}
+ mirrors={replicationSettings?.enabled ? showSnapshotViewer.mirrors : undefined}
+ primaryStorage={replicationSettings?.enabled ? storage : undefined}
+ />
+ </SidePanel>
+ )}
</div>
);
};
diff --git a/frontend/src/components/Plan/SnapshotViewer/SnapshotViewer.tsx b/frontend/src/components/Plan/SnapshotViewer/SnapshotViewer.tsx
new file mode 100644
index 0000000..873151b
--- /dev/null
+++ b/frontend/src/components/Plan/SnapshotViewer/SnapshotViewer.tsx
@@ -0,0 +1,344 @@
+import { useState, useCallback, useRef, ReactNode } from 'react';
+import { useQuery } from '@tanstack/react-query';
+import { useNavigate } from 'react-router';
+import { toast } from 'react-toastify';
+import Icon from '../../common/Icon/Icon';
+import FileIcon from '../../common/FileIcon/FileIcon';
+import Select from '../../common/form/Select/Select';
+import ActionModal from '../../common/ActionModal/ActionModal';
+import { Backup, BackupMirror } from '../../../@types/backups';
+import { useRestoreBackup } from '../../../services/restores';
+import { useBrowseSnapshot } from '../../../services/backups';
+import { FileItem } from '../../../@types/system';
+import { isMobile, formatBytes, timeAgo } from '../../../utils/helpers';
+import SnapshotBrowserToolbar from '../../common/SnapshotBrowser/SnapshotBrowserToolbar';
+import SnapshotBrowserDirectories from '../../common/SnapshotBrowser/SnapshotBrowserDirectories';
+import SnapshotBrowserFileList from '../../common/SnapshotBrowser/SnapshotBrowserFileList';
+import SnapshotViewerFile from './SnapshotViewerFile';
+import { useSnapshotDatabase } from '../../common/SnapshotBrowser/hooks/useSnapshotDatabase';
+import { useSnapshotNavigation } from '../../common/SnapshotBrowser/hooks/useSnapshotNavigation';
+import { useSnapshotSort } from '../../common/SnapshotBrowser/hooks/useSnapshotSort';
+import classes from '../../common/SnapshotBrowser/SnapshotBrowser.module.scss';
+
+interface SnapshotViewerProps {
+ files: FileItem[];
+ backup: Backup;
+ planId: string;
+ isSync?: boolean;
+ mirrors?: BackupMirror[];
+ onClose: () => void;
+ replicationId?: string;
+ toolbarLeftContent?: ReactNode;
+ toolbarRightContent?: ReactNode;
+ isExternalLoading?: boolean;
+ /** Render additional action buttons per file row (e.g. View, Download, Compare in Pro). */
+ renderFileActions?: (file: FileItem, meta: { fileExtension: string; isDirectory: boolean }) => ReactNode;
+ /** Extra elements rendered at the end (e.g. BackupFileLoader modal in Pro). */
+ children?: ReactNode;
+ primaryStorage?: { id: string; type: string; name: string };
+ /** Called when the user selects a different storage mirror. Receives the replicationId (or undefined for primary). */
+ onStorageChange?: (replicationId: string | undefined) => void;
+}
+
+const isMobileDevice = isMobile();
+const GRID_COLUMNS = '1fr 120px minmax(100px, auto) 120px';
+const GRID_COLUMNS_SYNC = '1fr 120px minmax(100px, auto)';
+
+const SnapshotViewer = ({
+ files,
+ backup,
+ planId,
+ isSync = false,
+ mirrors,
+ onClose,
+ replicationId,
+ toolbarLeftContent,
+ toolbarRightContent,
+ isExternalLoading,
+ renderFileActions,
+ children,
+ primaryStorage,
+ onStorageChange,
+}: SnapshotViewerProps) => {
+ const [search, setSearch] = useState('');
+ const [showRestoreModal, setShowRestoreModal] = useState<FileItem | false>(false);
+ const [selectedReplicationId, setSelectedReplicationId] = useState<string | undefined>(replicationId);
+ const [currentFiles, setCurrentFiles] = useState<FileItem[]>(files);
+ const fileListRef = useRef<HTMLDivElement | null>(null);
+ const navigate = useNavigate();
+
+ const backupId = backup.id;
+ const restoreMutation = useRestoreBackup();
+ const browseSnapshotMutation = useBrowseSnapshot();
+ const useProgressiveLoading = currentFiles.length > 1000;
+
+ const { db, initError, discoveredDirectories, expandedFolders, setExpandedFolders, addDirectoriesSorted } = useSnapshotDatabase(
+ currentFiles,
+ backupId,
+ useProgressiveLoading,
+ );
+
+ const { selectedFolder, handleGoUp, handleDirectoryClick, toggleFolder, isVisible, hasSubdirectories } = useSnapshotNavigation(
+ discoveredDirectories,
+ expandedFolders,
+ setExpandedFolders,
+ );
+
+ const { sortField, sortDirection, handleSort } = useSnapshotSort();
+
+ // Handle storage change - re-browse from selected mirror
+ const handleStorageChange = useCallback(
+ (replicationIdValue?: string) => {
+ setSelectedReplicationId(replicationIdValue);
+ onStorageChange?.(replicationIdValue);
+ if (replicationIdValue) {
+ browseSnapshotMutation.mutate(
+ { backupId: backup.id, replicationId: replicationIdValue },
+ {
+ onSuccess: (data: any) => {
+ if (data?.result) {
+ setCurrentFiles(data.result);
+ }
+ },
+ },
+ );
+ } else {
+ setCurrentFiles(files);
+ }
+ },
+ [backup.id, files, browseSnapshotMutation, onStorageChange],
+ );
+
+ // Build storage selector for toolbar
+ const completedMirrors = mirrors?.filter((m) => m.status === 'completed') || [];
+ const showStorageDropdown = primaryStorage && completedMirrors.length > 0;
+
+ const storageSelector = showStorageDropdown ? (
+ <Select
+ customClasses={classes.storageSelect}
+ options={[
+ { label: primaryStorage!.name + ' (Primary)', value: 'primary', image: <img src={`/providers/${primaryStorage.type}.png`} /> },
+ ...completedMirrors.map((m) => ({
+ label: m.storageName + ' (Mirror)',
+ value: m.replicationId,
+ image: <img src={`/providers/${m.storageType}.png`} />,
+ })),
+ ]}
+ fieldValue={selectedReplicationId || 'primary'}
+ onUpdate={(value) => handleStorageChange(value === 'primary' ? undefined : value)}
+ disabled={browseSnapshotMutation.isPending}
+ />
+ ) : undefined;
+
+ // Directory contents query
+ const directoryContentsQuery = useQuery({
+ queryKey: ['directoryContents', selectedFolder, sortField, sortDirection, search, backupId],
+ queryFn: async () => {
+ if (!db || selectedFolder === null) return [];
+
+ const contents = await db.getDirectoryContents(selectedFolder, sortField, sortDirection, search);
+
+ if (useProgressiveLoading) {
+ const subdirs = await db.getSubdirectories(selectedFolder);
+ if (subdirs.length > 0) {
+ addDirectoriesSorted(subdirs);
+ }
+ }
+
+ if (selectedFolder) {
+ return [{ isGoUp: true, path: '..', name: '..', isDirectory: true } as any, ...contents];
+ }
+
+ return contents;
+ },
+ enabled: !!db && selectedFolder !== null,
+ staleTime: 30000,
+ retry: 1,
+ });
+
+ const currentDirectoryFiles = directoryContentsQuery.data || [];
+ const isInitializing = !db && !initError;
+ const isDirectoryLoading = directoryContentsQuery.isPending;
+
+ // Restore handler
+ const restoreFile = (path: string) => {
+ restoreMutation.mutate(
+ {
+ backupId,
+ planId,
+ target: '',
+ includes: [path],
+ overwrite: 'always',
+ deleteOption: false,
+ replicationId: selectedReplicationId,
+ },
+ {
+ onSuccess: (_: any, variables) => {
+ toast.success('Restoration Process Started..', { autoClose: 5000 });
+ const targetPlanId = variables?.planId;
+ if (targetPlanId) {
+ navigate(`/plan/${targetPlanId}?pendingrestore=1`);
+ }
+ onClose();
+ },
+ onError: (error) => {
+ console.error('Restore error:', error);
+ toast.error(`Restore failed. ${error.message || 'Unknown error'}`);
+ },
+ onSettled: () => {
+ setShowRestoreModal(false);
+ },
+ },
+ );
+ };
+
+ // File row renderer
+ const gridColumns = isSync ? GRID_COLUMNS_SYNC : GRID_COLUMNS;
+
+ const renderFileRow = useCallback(
+ ({ index, style }: { index: number; style: React.CSSProperties }) => {
+ const file = currentDirectoryFiles[index];
+ if (!file) return null;
+
+ return (
+ <SnapshotViewerFile
+ style={style}
+ file={file}
+ isSync={isSync}
+ gridColumns={gridColumns}
+ onGoUp={handleGoUp}
+ onDirectoryClick={handleDirectoryClick}
+ onRestore={(file) => setShowRestoreModal(file)}
+ renderFileActions={renderFileActions}
+ />
+ );
+ },
+ [currentDirectoryFiles, isSync, gridColumns, handleGoUp, handleDirectoryClick, renderFileActions],
+ );
+
+ // Error state
+ if (initError) {
+ return (
+ <div className={classes.snapshotBrowser}>
+ <div className={classes.errorState}>
+ <Icon type="error" size={24} />
+ <p>Failed to initialize database</p>
+ <small>{initError}</small>
+ <button onClick={() => window.location.reload()}>Reload Page</button>
+ </div>
+ </div>
+ );
+ }
+
+ // Loading state
+ if (isInitializing) {
+ return (
+ <div className={classes.snapshotBrowser}>
+ <div className={classes.loadingState}>
+ <Icon type="loading" size={24} />
+ <p>Indexing snapshot data...</p>
+ <small>Building efficient database for {files.length.toLocaleString()} files</small>
+ </div>
+ </div>
+ );
+ }
+
+ const defaultToolbarLeft = (
+ <div className={classes.stats}>
+ <Icon type="box" />
+ <strong>backup-{backup.id}</strong> • {formatBytes(backup.totalSize)} • {timeAgo(new Date(backup.ended))}
+ </div>
+ );
+
+ return (
+ <div className={classes.snapshotBrowser}>
+ <SnapshotBrowserToolbar
+ search={search}
+ onSearchChange={setSearch}
+ isLoading={isDirectoryLoading || isExternalLoading || browseSnapshotMutation.isPending}
+ leftContent={toolbarLeftContent || defaultToolbarLeft}
+ rightContent={
+ <>
+ {storageSelector}
+ {toolbarRightContent}
+ </>
+ }
+ />
+
+ {isExternalLoading || browseSnapshotMutation.isPending ? (
+ <div className={`${classes.browserContent} ${classes.loadingState}`}>
+ <div>
+ <Icon type="loading" size={16} /> Loading...
+ </div>
+ </div>
+ ) : (
+ <div className={classes.browserContent}>
+ <SnapshotBrowserDirectories
+ directories={discoveredDirectories}
+ selectedFolder={selectedFolder}
+ expandedFolders={expandedFolders}
+ useProgressiveLoading={useProgressiveLoading}
+ onDirectoryClick={handleDirectoryClick}
+ onToggleFolder={toggleFolder}
+ isVisible={isVisible}
+ hasSubdirectories={hasSubdirectories}
+ />
+
+ <div className={`${classes.content} styled__scrollbar`} ref={fileListRef}>
+ <SnapshotBrowserFileList
+ files={currentDirectoryFiles}
+ height={fileListRef.current?.clientHeight ? fileListRef.current.clientHeight - 45 : 520}
+ itemSize={isMobileDevice ? 65 : 46}
+ headerContent={
+ <>
+ <div onClick={() => handleSort('name')} className={sortField === 'name' ? classes.activeSort : ''}>
+ Name {sortField === 'name' && (sortDirection === 'asc' ? '↑' : '↓')}
+ </div>
+ <div onClick={() => handleSort('modifiedAt')} className={sortField === 'modifiedAt' ? classes.activeSort : ''}>
+ Last Modified {sortField === 'modifiedAt' && (sortDirection === 'asc' ? '↑' : '↓')}
+ </div>
+ <div onClick={() => handleSort('size')} className={sortField === 'size' ? classes.activeSort : ''}>
+ Size {sortField === 'size' && (sortDirection === 'asc' ? '↑' : '↓')}
+ </div>
+ {!isSync && <div className={classes.headerActions}>Actions</div>}
+ </>
+ }
+ renderRow={renderFileRow}
+ selectedFolder={selectedFolder}
+ isLoading={isDirectoryLoading}
+ gridTemplateColumns={gridColumns}
+ />
+ </div>
+ </div>
+ )}
+
+ {showRestoreModal && (
+ <ActionModal
+ title={`Restore ${showRestoreModal.isDirectory ? 'Directory' : 'File'}`}
+ message={
+ <>
+ <p>Are you sure you want to restore this {showRestoreModal.isDirectory ? 'Directory' : 'File'}?</p>
+ <p className={classes.restoreModalFile}>
+ {showRestoreModal.isDirectory ? <Icon type={'fm-directory'} size={16} /> : <FileIcon filename={showRestoreModal.path} />}{' '}
+ {showRestoreModal.path}
+ </p>
+ <p>This action will overwrite the existing file/directory with the same name in the source.</p>
+ </>
+ }
+ closeModal={() => setShowRestoreModal(false)}
+ width="600px"
+ primaryAction={{
+ title: `Yes, Restore ${showRestoreModal.isDirectory ? 'Directory' : 'File'}`,
+ type: 'default',
+ isPending: restoreMutation.isPending,
+ action: () => restoreFile(showRestoreModal.path),
+ }}
+ />
+ )}
+
+ {children}
+ </div>
+ );
+};
+
+export default SnapshotViewer;
diff --git a/frontend/src/components/Plan/SnapshotViewer/SnapshotViewerFile.tsx b/frontend/src/components/Plan/SnapshotViewer/SnapshotViewerFile.tsx
new file mode 100644
index 0000000..eeb8bf6
--- /dev/null
+++ b/frontend/src/components/Plan/SnapshotViewer/SnapshotViewerFile.tsx
@@ -0,0 +1,89 @@
+import React, { ReactNode } from 'react';
+import Icon from '../../common/Icon/Icon';
+import FileIcon from '../../common/FileIcon/FileIcon';
+import { formatBytes, formatDateTime, timeAgo } from '../../../utils/helpers';
+import { FileItem } from '../../../@types/system';
+import classes from '../../common/SnapshotBrowser/SnapshotBrowser.module.scss';
+
+interface SnapshotViewerFileProps {
+ style: React.CSSProperties;
+ file: FileItem | { isGoUp: true; path: string; name: string; isDirectory: true };
+ isSync?: boolean;
+ gridColumns: string;
+ onGoUp: () => void;
+ onDirectoryClick: (path: string) => void;
+ onRestore: (file: FileItem) => void;
+ renderFileActions?: (file: FileItem, meta: { fileExtension: string; isDirectory: boolean }) => ReactNode;
+}
+
+const SnapshotViewerFile = ({
+ style,
+ file,
+ isSync,
+ gridColumns,
+ onGoUp,
+ onDirectoryClick,
+ onRestore,
+ renderFileActions,
+}: SnapshotViewerFileProps) => {
+ if (!file) return null;
+
+ if ('isGoUp' in file && file.isGoUp) {
+ return (
+ <div
+ style={{ ...style, gridTemplateColumns: gridColumns }}
+ className={`${classes.snapshotFile} ${classes.fileIsDir} ${classes.goUpButton}`}
+ onClick={onGoUp}
+ >
+ <div className={classes.fileName}>...</div>
+ <div></div>
+ <div></div>
+ {!isSync && <div></div>}
+ </div>
+ );
+ }
+
+ const typedFile = file as FileItem;
+ const fileName = typedFile.name || typedFile.path.split('/').pop() || '';
+ const isDirectory = typedFile.isDirectory;
+ const fileExtension = fileName.split('.').pop() || '';
+
+ return (
+ <div
+ style={{ ...style, gridTemplateColumns: gridColumns }}
+ className={`${classes.snapshotFile} ${isDirectory ? classes.fileIsDir : ''}`}
+ onClick={() => {
+ if (isDirectory) {
+ onDirectoryClick(typedFile.path);
+ }
+ }}
+ >
+ <div className={classes.fileName}>
+ {isDirectory ? <Icon type={'fm-directory'} size={16} /> : <FileIcon filename={fileName} />} {fileName}
+ </div>
+ <div className={classes.fileModifiedAt} title={formatDateTime(typedFile.modifiedAt)}>
+ <i>{timeAgo(new Date(typedFile.modifiedAt))}</i>
+ </div>
+ <div className={classes.fileSize}>{!isDirectory ? formatBytes(typedFile.size || 0) : ''}</div>
+ {!isSync && (
+ <div className={classes.fileActions}>
+ {renderFileActions?.(typedFile, { fileExtension, isDirectory })}
+ <button
+ data-tooltip-id="htmlToolTip"
+ data-tooltip-place="top"
+ data-tooltip-delay-show={500}
+ data-tooltip-html="Restore"
+ onClick={(e) => {
+ e.stopPropagation();
+ onRestore(typedFile);
+ }}
+ >
+ <Icon type={'restore'} size={16} />
+ </button>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default SnapshotViewerFile;
diff --git a/frontend/src/components/Restore/RestoreFileSelector/RestoreFileSelector.tsx b/frontend/src/components/Restore/RestoreFileSelector/RestoreFileSelector.tsx
index 58b2ab7..728d506 100644
--- a/frontend/src/components/Restore/RestoreFileSelector/RestoreFileSelector.tsx
+++ b/frontend/src/components/Restore/RestoreFileSelector/RestoreFileSelector.tsx
@@ -1,11 +1,13 @@
-import { useState, useMemo } from 'react';
-import { FixedSizeList as List } from 'react-window';
+import { useState, useMemo, useEffect } from 'react';
import Icon from '../../common/Icon/Icon';
import { RestoreFileItem } from '../../../@types/restores';
import { calculateDirectorySizes, formatBytes, formatDateTime, formatNumberToK, isMobile, sortFileItems } from '../../../utils/helpers';
import FileIcon from '../../common/FileIcon/FileIcon';
import classes from './RestoreFileSelector.module.scss';
import { getParentPath, getPathSeparator, normalizePath, splitPath } from '../../../utils/restore';
+import { SnapshotBrowserToolbar, SnapshotBrowserDirectories, SnapshotBrowserFileList, SnapshotBrowserGoUpRow } from '../../common/SnapshotBrowser';
+import { useSnapshotNavigation } from '../../common/SnapshotBrowser/hooks/useSnapshotNavigation';
+import sbClasses from '../../common/SnapshotBrowser/SnapshotBrowser.module.scss';
interface RestoreFileSelectorProps {
selected: {
@@ -23,9 +25,9 @@ interface RestoreFileSelectorProps {
const isMobileDevice = isMobile();
const ITEM_HEIGHT = isMobileDevice ? 65 : 45;
+const GRID_COLUMNS = '1fr 180px minmax(80px, auto)';
const RestoreFileSelector = ({ selected, files, isLoading, errorFetching, showChange, onSelect, fileSelectCondition }: RestoreFileSelectorProps) => {
- const [selectedFolder, setSelectedFolder] = useState<string>('');
const [search, setSearch] = useState('');
const [sortField, setSortField] = useState<'name' | 'modifiedAt' | 'size'>('name');
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
@@ -152,13 +154,23 @@ const RestoreFileSelector = ({ selected, files, isLoading, errorFetching, showCh
return aParts.length - bParts.length;
});
- // Set the first directory as selected by default
- console.log('SelectedFolder :', sortedDirs[0]);
- setSelectedFolder(sortedDirs[0] || '');
-
return sortedDirs;
}, [files]);
+ const { selectedFolder, setSelectedFolder, hasSubdirectories, isVisible, expandParentFolders, toggleFolder } = useSnapshotNavigation(
+ directories,
+ expandedFolders,
+ setExpandedFolders,
+ { splitPath, getPathSeparator, hasLeadingSeparator: false },
+ );
+
+ // Set the first directory as selected by default
+ useEffect(() => {
+ if (directories.length > 0 && selectedFolder === '') {
+ setSelectedFolder(directories[0]);
+ }
+ }, [directories, selectedFolder, setSelectedFolder]);
+
const summary = useMemo(() => {
let selectedFilesCount = 0;
let selectedBytes = 0;
@@ -182,11 +194,6 @@ const RestoreFileSelector = ({ selected, files, isLoading, errorFetching, showCh
};
}, [files, selectedFiles]);
- const hasSubdirectories = (dir: string) => {
- const separator = getPathSeparator(dir);
- return directories.some((d) => d !== dir && d.startsWith(dir + separator));
- };
-
const handleSort = (field: 'name' | 'modifiedAt' | 'size') => {
if (sortField === field) {
// Toggle direction if clicking the same field
@@ -198,44 +205,6 @@ const RestoreFileSelector = ({ selected, files, isLoading, errorFetching, showCh
}
};
- const expandParentFolders = (dirPath: string) => {
- const newExpanded = new Set(expandedFolders);
- const separator = getPathSeparator(dirPath);
- const parts = splitPath(dirPath);
- let currentPath = '';
-
- // Expand all parent directories
- parts.forEach((part) => {
- currentPath = currentPath ? `${currentPath}${separator}${part}` : part;
- newExpanded.add(currentPath);
- });
-
- setExpandedFolders(newExpanded);
- };
-
- const toggleFolder = (dir: string) => {
- const newExpanded = new Set(expandedFolders);
- if (expandedFolders.has(dir)) {
- newExpanded.delete(dir);
- } else {
- newExpanded.add(dir);
- }
- setExpandedFolders(newExpanded);
- };
-
- const isVisible = (dir: string) => {
- const separator = getPathSeparator(dir);
- const parts = splitPath(dir);
- const parentParts = parts.slice(0, -1);
- let parentPath = '';
-
- // Check if all parent folders are expanded
- return parentParts.every((part) => {
- parentPath = parentPath ? `${parentPath}${separator}${part}` : part;
- return expandedFolders.has(parentPath);
- });
- };
-
const onFileSelect = (path: string, isDirectory: boolean) => {
const newSelected = { ...selectedFiles };
const isCurrentlySelected = isPathSelected(path);
@@ -343,19 +312,17 @@ const RestoreFileSelector = ({ selected, files, isLoading, errorFetching, showCh
// Parent directory navigation
if (item === null) {
return (
- <div
+ <SnapshotBrowserGoUpRow
style={style}
- className={`${classes.file} ${classes.fileIsDir} ${classes.goUpButton}`}
- onClick={() => {
+ onGoUp={() => {
const parentPath = getParentPath(selectedFolder);
const normalizedParentPath = normalizePath(parentPath);
if (!normalizedParentPath || normalizedParentPath === '') return;
expandParentFolders(normalizedParentPath);
setSelectedFolder(normalizedParentPath);
}}
- >
- <div className={classes.fileName}>...</div>
- </div>
+ gridTemplateColumns={GRID_COLUMNS}
+ />
);
}
@@ -369,9 +336,9 @@ const RestoreFileSelector = ({ selected, files, isLoading, errorFetching, showCh
return (
<div
- style={style}
+ style={{ ...style, gridTemplateColumns: GRID_COLUMNS }}
key={file.path}
- className={`${classes.file} ${isDirectory ? classes.fileIsDir : ''} ${showChange && file.changeType === 'modified' ? classes.fileModified : ''} ${showChange && file.changeType === 'removed' ? classes.fileRemoved : ''}`}
+ className={`${sbClasses.snapshotFile} ${isDirectory ? sbClasses.fileIsDir : ''} ${showChange && file.changeType === 'modified' ? classes.fileModified : ''} ${showChange && file.changeType === 'removed' ? classes.fileRemoved : ''}`}
onClick={() => {
if (isDirectory) {
expandParentFolders(normalizedPath);
@@ -379,7 +346,7 @@ const RestoreFileSelector = ({ selected, files, isLoading, errorFetching, showCh
}
}}
>
- <div className={classes.fileName}>
+ <div className={sbClasses.fileName}>
<button
className={`${classes.selectButton} ${isSelected ? classes.selected : ''} ${!canBeSelected ? classes.notSelectable : ''}`}
onClick={(e) => {
@@ -406,10 +373,12 @@ const RestoreFileSelector = ({ selected, files, isLoading, errorFetching, showCh
<Icon type="loading" size={24} /> Loading Snapshot Content..
</div>
)}
- <div className={classes.restoredFileBrowser}>
- <div className={classes.toolbar}>
- <div className={classes.toolbarLeft}>
- <div className={classes.stats}>
+ <div className={sbClasses.snapshotBrowser}>
+ <SnapshotBrowserToolbar
+ search={search}
+ onSearchChange={setSearch}
+ leftContent={
+ <div className={sbClasses.stats}>
<strong>Summary: </strong>
{formatNumberToK(summary.selectedFiles)}/{formatNumberToK(summary.totalFiles)} Items {' • '}
{formatBytes(summary.selectedBytes)}/{formatBytes(summary.totalBytes)}
@@ -423,91 +392,59 @@ const RestoreFileSelector = ({ selected, files, isLoading, errorFetching, showCh
</div>
)}
</div>
- </div>
- <div className={classes.toolbarRight}>
- <div className={classes.search}>
- <Icon type="search" size={16} />
- <input type="text" placeholder="Search in current Directory..." value={search} onChange={(e) => setSearch(e.target.value)} />
- </div>
- </div>
- </div>
-
- <div className={classes.browserContent}>
- <div className={`${classes.sidebar} styled__scrollbar`}>
- <div className={classes.sidebarHeader}>Directories</div>
- {directories.map((dir) => {
- const parts = splitPath(dir);
- const dirName = parts[parts.length - 1];
- const depth = parts.length - 1;
- const isExpanded = expandedFolders.has(dir);
- const hasChildren = hasSubdirectories(dir);
+ }
+ />
+
+ <div className={sbClasses.browserContent}>
+ <SnapshotBrowserDirectories
+ directories={directories}
+ selectedFolder={selectedFolder}
+ expandedFolders={expandedFolders}
+ onDirectoryClick={(dir) => setSelectedFolder(dir)}
+ onToggleFolder={toggleFolder}
+ isVisible={isVisible}
+ hasSubdirectories={hasSubdirectories}
+ renderDirectoryExtra={(dir) => {
const isSelected = isPathSelected(files.find((f) => f.isDirectory && normalizePath(f.path) === dir)?.path || dir);
-
- // Only render if parent folders are expanded or if it's a root folder
- if (depth === 0 || isVisible(dir)) {
- return (
- <div
- key={dir}
- className={`${classes.directory} ${selectedFolder === dir ? classes.selected : ''} ${hasChildren ? '' : classes.directoryEmpty}`}
- style={{ paddingLeft: `${depth * 20}px` }}
- onClick={() => setSelectedFolder(dir)}
- >
- {hasChildren ? (
- <button
- className={`${classes.toggleButton} ${isExpanded ? classes.active : ''}`}
- onClick={(e) => {
- e.stopPropagation();
- toggleFolder(dir);
- }}
- >
- {isExpanded ? '-' : '+'}
- </button>
- ) : (
- <span className={`${classes.togglePlaceholder}`} />
- )}
- <div className={classes.dirName}>
- <Icon type={'fm-directory'} size={14} />
- <button
- className={`${classes.selectButton} ${isSelected ? classes.selected : ''}`}
- onClick={(e) => {
- e.stopPropagation();
- const originalPath = files.find((f) => f.isDirectory && normalizePath(f.path) === dir)?.path || dir;
- onFileSelect(originalPath, true);
- }}
- >
- <Icon type={isSelected ? 'check-circle-filled' : 'check-circle'} size={13} />
- </button>
- {dirName}
- </div>
+ return (
+ <button
+ className={`${classes.selectButton} ${isSelected ? classes.selected : ''}`}
+ onClick={(e) => {
+ e.stopPropagation();
+ const originalPath = files.find((f) => f.isDirectory && normalizePath(f.path) === dir)?.path || dir;
+ onFileSelect(originalPath, true);
+ }}
+ >
+ <Icon type={isSelected ? 'check-circle-filled' : 'check-circle'} size={13} />
+ </button>
+ );
+ }}
+ />
+
+ <div className={`${sbClasses.content} styled__scrollbar`}>
+ <SnapshotBrowserFileList
+ files={directChildren}
+ height={window.innerHeight - 370}
+ itemSize={ITEM_HEIGHT}
+ headerContent={
+ <>
+ <div onClick={() => handleSort('name')} className={sortField === 'name' ? classes.activeSort : ''}>
+ Name {sortField === 'name' && (sortDirection === 'asc' ? '↑' : '↓')}
</div>
- );
+ <div onClick={() => handleSort('modifiedAt')} className={sortField === 'modifiedAt' ? classes.activeSort : ''}>
+ Last Modified {sortField === 'modifiedAt' && (sortDirection === 'asc' ? '↑' : '↓')}
+ </div>
+ <div onClick={() => handleSort('size')} className={sortField === 'size' ? classes.activeSort : ''}>
+ Size {sortField === 'size' && (sortDirection === 'asc' ? '↑' : '↓')}
+ </div>
+ </>
}
- return null;
- })}
- </div>
-
- <div className={`${classes.content} styled__scrollbar`}>
- <div className={classes.fileList}>
- <div className={classes.header}>
- <div onClick={() => handleSort('name')} className={sortField === 'name' ? classes.activeSort : ''}>
- Name {sortField === 'name' && (sortDirection === 'asc' ? '↑' : '↓')}
- </div>
- <div onClick={() => handleSort('modifiedAt')} className={sortField === 'modifiedAt' ? classes.activeSort : ''}>
- Last Modified {sortField === 'modifiedAt' && (sortDirection === 'asc' ? '↑' : '↓')}
- </div>
- <div onClick={() => handleSort('size')} className={sortField === 'size' ? classes.activeSort : ''}>
- Size {sortField === 'size' && (sortDirection === 'asc' ? '↑' : '↓')}
- </div>
- </div>
- {selectedFolder ? (
- <List height={window.innerHeight - 370} itemCount={directChildren.length} itemSize={ITEM_HEIGHT} width="100%">
- {Row}
- </List>
- ) : (
- <div className={classes.fileListEmpty}>Select a folder from the left to browse it's content</div>
- )}
- {errorFetching && <div className={classes.error}>Failed to load files. Please try again.</div>}
- </div>
+ renderRow={Row}
+ selectedFolder={selectedFolder || null}
+ gridTemplateColumns={GRID_COLUMNS}
+ emptyMessage="Select a folder from the left to browse it's content"
+ />
+ {errorFetching && <div className={classes.error}>Failed to load files. Please try again.</div>}
</div>
</div>
</div>
diff --git a/frontend/src/components/Restore/RestoredFileBrowser/RestoredFileBrowser.tsx b/frontend/src/components/Restore/RestoredFileBrowser/RestoredFileBrowser.tsx
index dfcf93e..1efe3f6 100644
--- a/frontend/src/components/Restore/RestoredFileBrowser/RestoredFileBrowser.tsx
+++ b/frontend/src/components/Restore/RestoredFileBrowser/RestoredFileBrowser.tsx
@@ -1,11 +1,13 @@
import { useState, useMemo, useEffect } from 'react';
-import { FixedSizeList as List } from 'react-window';
import Icon from '../../common/Icon/Icon';
+import FileIcon from '../../common/FileIcon/FileIcon';
import classes from './RestoredFileBrowser.module.scss';
import { RestoredFileItem, RestoredItemsStats } from '../../../@types/restores';
import { formatBytes, formatNumberToK, isMobile } from '../../../utils/helpers';
import { getParentPath, getPathSeparator, normalizePath, splitPath } from '../../../utils/restore';
-import FileIcon from '../../common/FileIcon/FileIcon';
+import { SnapshotBrowserToolbar, SnapshotBrowserDirectories, SnapshotBrowserFileList, SnapshotBrowserGoUpRow } from '../../common/SnapshotBrowser';
+import { useSnapshotNavigation } from '../../common/SnapshotBrowser/hooks/useSnapshotNavigation';
+import sbClasses from '../../common/SnapshotBrowser/SnapshotBrowser.module.scss';
interface RestoredFileBrowserProps {
files: RestoredFileItem[];
@@ -15,9 +17,9 @@ interface RestoredFileBrowserProps {
const isMobileDevice = isMobile();
const ITEM_HEIGHT = isMobileDevice ? 65 : 45;
+const GRID_COLUMNS = '1fr 100px minmax(80px, auto)';
const RestoredFileBrowser = ({ files, stats, isPreview = false }: RestoredFileBrowserProps) => {
- const [selectedFolder, setSelectedFolder] = useState<string>('');
const [search, setSearch] = useState('');
const [filters, setFilters] = useState({
unchanged: true,
@@ -34,7 +36,6 @@ const RestoredFileBrowser = ({ files, stats, isPreview = false }: RestoredFileBr
parts.forEach((part, index) => {
currentPath = currentPath ? `${currentPath}${separator}${part}` : part;
- // Only expand folders up to 5 levels deep (index < 5)
if (index < 3) {
allPaths.add(currentPath);
}
@@ -54,7 +55,6 @@ const RestoredFileBrowser = ({ files, stats, isPreview = false }: RestoredFileBr
})
.forEach((file) => {
const dirPath = getParentPath(file.path);
- // Use the normalized path as key
const normalizedDirPath = normalizePath(dirPath);
if (normalizedDirPath) {
@@ -70,7 +70,6 @@ const RestoredFileBrowser = ({ files, stats, isPreview = false }: RestoredFileBr
const directories = useMemo(() => {
const dirs = new Set<string>();
- // Derive directories from all files, not filtered fileSystem, to keep tree stable during search
files.forEach((file) => {
const dirPath = getParentPath(file.path);
const separator = getPathSeparator(dirPath);
@@ -87,62 +86,22 @@ const RestoredFileBrowser = ({ files, stats, isPreview = false }: RestoredFileBr
return Array.from(dirs);
}, [files]);
- // Set initial selected folder when directories change
+ const { selectedFolder, setSelectedFolder, hasSubdirectories, isVisible, expandParentFolders, toggleFolder } = useSnapshotNavigation(
+ directories,
+ expandedFolders,
+ setExpandedFolders,
+ { splitPath, getPathSeparator, hasLeadingSeparator: false },
+ );
+
useEffect(() => {
if (directories.length > 0 && selectedFolder === '') {
setSelectedFolder(directories[0]);
}
- }, [directories, selectedFolder]);
-
- const hasSubdirectories = (dir: string) => {
- const separator = getPathSeparator(dir);
- return directories.some((d) => d !== dir && d.startsWith(dir + separator));
- };
+ }, [directories, selectedFolder, setSelectedFolder]);
const hasUpdatedContent = (dir: string) => {
- return Object.entries(fileSystem).some(([path, files]) => {
- return path.startsWith(dir) && files.some((f) => f.action === 'restored' || f.action === 'updated');
- });
- };
-
- const expandParentDirectories = (dir: string) => {
- const newExpanded = new Set(expandedFolders);
- const separator = getPathSeparator(dir);
- const parts = splitPath(dir);
- let currentPath = '';
-
- // Expand all parent directories
- parts.forEach((part, index) => {
- currentPath = currentPath ? `${currentPath}${separator}${part}` : part;
- if (index < parts.length - 1) {
- // Don't expand the target directory itself
- newExpanded.add(currentPath);
- }
- });
-
- setExpandedFolders(newExpanded);
- };
-
- const toggleFolder = (dir: string) => {
- const newExpanded = new Set(expandedFolders);
- if (expandedFolders.has(dir)) {
- newExpanded.delete(dir);
- } else {
- newExpanded.add(dir);
- }
- setExpandedFolders(newExpanded);
- };
-
- const isVisible = (dir: string) => {
- const separator = getPathSeparator(dir);
- const parts = splitPath(dir);
- const parentParts = parts.slice(0, -1);
- let parentPath = '';
-
- // Check if all parent folders are expanded
- return parentParts.every((part) => {
- parentPath = parentPath ? `${parentPath}${separator}${part}` : part;
- return expandedFolders.has(parentPath);
+ return Object.entries(fileSystem).some(([path, dirFiles]) => {
+ return path.startsWith(dir) && dirFiles.some((f) => f.action === 'restored' || f.action === 'updated');
});
};
@@ -155,11 +114,9 @@ const RestoredFileBrowser = ({ files, stats, isPreview = false }: RestoredFileBr
const isDirectoryA = directories.includes(normalizedPathA);
const isDirectoryB = directories.includes(normalizedPathB);
- // First sort by type: directories first, then files
if (isDirectoryA && !isDirectoryB) return -1;
if (!isDirectoryA && isDirectoryB) return 1;
- // If both are same type, sort by status priority
const priority = { restored: 0, updated: 1, unchanged: 2 };
return priority[a.action] - priority[b.action];
});
@@ -169,25 +126,19 @@ const RestoredFileBrowser = ({ files, stats, isPreview = false }: RestoredFileBr
const totalItems = sortedFiles.length + (showGoUpButton ? 1 : 0);
const FileRow = ({ index, style }: { index: number; style: React.CSSProperties }) => {
- // If showing go up button and this is the first item
if (showGoUpButton && index === 0) {
return (
- <div
+ <SnapshotBrowserGoUpRow
style={style}
- className={`${classes.file} ${classes.fileIsDir} ${classes.goUpButton}`}
- onClick={() => {
+ onGoUp={() => {
const parentPath = getParentPath(selectedFolder);
const normalizedParentPath = normalizePath(parentPath);
- console.log('normalizedParentPath :', normalizedParentPath);
if (!normalizedParentPath || normalizedParentPath === '') return;
- expandParentDirectories(normalizedParentPath);
+ expandParentFolders(normalizedParentPath);
setSelectedFolder(normalizedParentPath);
}}
- >
- <div className={classes.fileName}>...</div>
- <div className={classes.status}></div>
- <div></div>
- </div>
+ gridTemplateColumns={GRID_COLUMNS}
+ />
);
}
@@ -202,22 +153,22 @@ const RestoredFileBrowser = ({ files, stats, isPreview = false }: RestoredFileBr
const isDirectory = directories.includes(normalizedPath);
const hasUpdates = hasUpdatedContent(normalizedPath);
const fileAction = file.action;
- const isRestored = file.action === 'restored' ? true : false;
+ const isRestored = file.action === 'restored';
const fileActionLabel = isRestored ? 'New' : file.action;
return (
<div
- style={style}
- className={`${classes.file} ${isDirectory ? classes.fileIsDir : ''}`}
+ style={{ ...style, gridTemplateColumns: GRID_COLUMNS }}
+ className={`${sbClasses.snapshotFile} ${isDirectory ? sbClasses.fileIsDir : ''}`}
onClick={() => {
if (isDirectory) {
setSelectedFolder(normalizedPath);
- expandParentDirectories(normalizedPath);
+ expandParentFolders(normalizedPath);
}
}}
>
- <div className={classes.fileName}>
- {isDirectory ? <Icon type={isDirectory ? 'fm-directory' : 'fm-file'} size={16} /> : <FileIcon filename={fileName || ''} />}{' '}
+ <div className={sbClasses.fileName}>
+ {isDirectory ? <Icon type={'fm-directory'} size={16} /> : <FileIcon filename={fileName || ''} />}{' '}
{isRestored && <span className={classes.newFileIndicator} />} {fileName}
{hasUpdates && <i />}
</div>
@@ -230,17 +181,19 @@ const RestoredFileBrowser = ({ files, stats, isPreview = false }: RestoredFileBr
};
return (
- <div className={classes.restoredFileBrowser}>
- <div className={classes.toolbar}>
- <div className={classes.toolbarLeft}>
- {stats && (
- <div className={classes.stats}>
+ <div className={sbClasses.snapshotBrowser}>
+ <SnapshotBrowserToolbar
+ search={search}
+ onSearchChange={setSearch}
+ leftContent={
+ stats && (
+ <div className={sbClasses.stats}>
<strong>Summary: </strong> {formatNumberToK(stats.total_files)} Items {' • '}
{formatBytes(stats.bytes_restored)}/{formatBytes(stats.total_bytes)}
</div>
- )}
- </div>
- <div className={classes.toolbarRight}>
+ )
+ }
+ rightContent={
<div className={classes.filters}>
{(Object.keys(filters) as Array<keyof typeof filters>).map((action) => (
<label key={action}>
@@ -249,81 +202,43 @@ const RestoredFileBrowser = ({ files, stats, isPreview = false }: RestoredFileBr
</label>
))}
</div>
- <div className={classes.search}>
- <Icon type="search" size={16} />
- <input type="text" placeholder="Search in current Directory..." value={search} onChange={(e) => setSearch(e.target.value)} />
- </div>
- </div>
- </div>
-
- <div className={classes.browserContent}>
- <div className={`${classes.sidebar} styled__scrollbar`}>
- <div className={classes.sidebarHeader}>Directories</div>
- {directories.map((dir) => {
- const parts = splitPath(dir);
- const dirName = parts[parts.length - 1];
- const depth = parts.length - 1;
- const isExpanded = expandedFolders.has(dir);
+ }
+ />
+
+ <div className={sbClasses.browserContent}>
+ <SnapshotBrowserDirectories
+ directories={directories}
+ selectedFolder={selectedFolder}
+ expandedFolders={expandedFolders}
+ onDirectoryClick={(dir) => {
+ setSelectedFolder(dir);
+ expandParentFolders(dir);
+ }}
+ onToggleFolder={toggleFolder}
+ isVisible={isVisible}
+ hasSubdirectories={hasSubdirectories}
+ renderDirectoryExtra={(dir) => {
const hasUpdates = hasUpdatedContent(dir);
- const hasChildren = hasSubdirectories(dir);
-
- // Only render if parent folders are expanded or if it's a root folder
- if (depth === 0 || isVisible(dir)) {
- return (
- <div
- key={dir}
- className={`${classes.directory} ${selectedFolder === dir ? classes.selected : ''} ${hasChildren ? '' : classes.directoryEmpty}`}
- style={{ paddingLeft: `${depth * 20}px` }}
- onClick={() => {
- setSelectedFolder(dir);
- expandParentDirectories(dir);
- }}
- >
- {hasChildren ? (
- <button
- className={classes.toggleButton}
- onClick={(e) => {
- e.stopPropagation();
- toggleFolder(dir);
- }}
- >
- {isExpanded ? '-' : '+'}
- </button>
- ) : (
- <span className={`${classes.togglePlaceholder}`} />
- )}
- <span className={classes.dirName}>
- <Icon type={'fm-directory'} size={14} /> {dirName}
- {hasUpdates && <span className={classes.notification} />}
- </span>
- </div>
- );
+ return hasUpdates ? <span className={classes.notification} /> : null;
+ }}
+ />
+
+ <div className={sbClasses.content}>
+ <SnapshotBrowserFileList
+ files={Array(totalItems)}
+ height={window.innerHeight - (isPreview ? 370 : 250)}
+ itemSize={ITEM_HEIGHT}
+ headerContent={
+ <>
+ <div>Name</div>
+ <div>Status</div>
+ <div>Size</div>
+ </>
}
- return null;
- })}
- </div>
-
- <div className={classes.content}>
- <div className={classes.fileList}>
- <div className={classes.header}>
- <div>Name</div>
- <div>Status</div>
- <div>Size</div>
- </div>
- {selectedFolder && totalItems > 0 ? (
- <List
- height={window.innerHeight - (isPreview ? 370 : 250)}
- itemCount={totalItems}
- itemSize={ITEM_HEIGHT}
- width="100%"
- className={`${classes.fileListVirtualized} styled__scrollbar`}
- >
- {FileRow}
- </List>
- ) : (
- <div className={classes.fileListEmpty}>Select a folder from the left to browse its content</div>
- )}
- </div>
+ renderRow={FileRow}
+ selectedFolder={selectedFolder || null}
+ gridTemplateColumns={GRID_COLUMNS}
+ />
</div>
</div>
</div>
diff --git a/frontend/src/components/common/SnapshotBrowser/SnapshotBrowser.module.scss b/frontend/src/components/common/SnapshotBrowser/SnapshotBrowser.module.scss
new file mode 100644
index 0000000..ae4e2b8
--- /dev/null
+++ b/frontend/src/components/common/SnapshotBrowser/SnapshotBrowser.module.scss
@@ -0,0 +1,376 @@
+.snapshotBrowser {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ border: 1px solid var(--line-color);
+ border-radius: 8px;
+ overflow: hidden;
+}
+
+.storageSelect {
+ background-color: transparent;
+ :global([class*='_dropdown_']) {
+ min-width: 250px;
+ }
+}
+
+.toolbar {
+ display: flex;
+ padding: 10px;
+ border-bottom: 1px solid var(--line-color);
+ gap: 15px;
+ align-items: center;
+ justify-content: space-between;
+ .toolbarRight {
+ display: flex;
+ flex-direction: row;
+ gap: 15px;
+ justify-content: space-between;
+ align-items: center;
+
+ .search {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 12px;
+ border: 1px solid var(--line-color);
+ border-radius: 4px;
+ margin-left: auto;
+
+ input {
+ border: none;
+ outline: none;
+ font-size: 0.75rem;
+ min-width: 200px;
+ background-color: var(--content-background-color);
+ }
+ }
+ }
+
+ .toolbarLeft {
+ .stats {
+ display: flex;
+ flex-direction: row;
+ gap: 8px;
+ color: var(--content-text-color-light);
+ strong {
+ color: var(--content-text-color);
+ }
+ }
+ }
+}
+
+.browserContent {
+ display: flex;
+ flex: 1;
+ overflow: hidden;
+
+ &.loadingState {
+ align-items: center;
+ justify-content: center;
+ }
+}
+
+.sidebar {
+ width: 300px;
+ border-right: 1px solid var(--line-color);
+ overflow-y: auto;
+
+ .sidebarHeader {
+ padding: 12px;
+ background: var(--background-color);
+ font-weight: 600;
+ position: sticky;
+ top: 0;
+ z-index: 2;
+ display: flex;
+ justify-content: space-between;
+ h4 {
+ margin: 0;
+ }
+ }
+ .noDirectories {
+ padding: 12px;
+ color: var(--content-text-color-light);
+ font-size: 0.85rem;
+ }
+}
+
+.directory {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 16px;
+ cursor: pointer;
+ position: relative;
+ button {
+ width: 20px;
+ }
+ .toggleButton {
+ border: 1px solid var(--line-color);
+ width: auto;
+ padding: 0px 4px;
+ border-radius: 3px;
+ }
+ .togglePlaceholder {
+ width: 10px;
+ height: 10px;
+ }
+ .dirName {
+ position: relative;
+ .notification {
+ width: 7px;
+ height: 7px;
+ background: var(--primary-color);
+ border-radius: 50%;
+ margin-left: auto;
+ position: absolute;
+ left: -2px;
+ top: 8px;
+ }
+ }
+ &.directoryEmpty {
+ .dirName {
+ padding-left: 20px;
+ .notification {
+ left: 8px;
+ }
+ }
+ }
+
+ &:hover {
+ background: var(--background-color);
+ }
+}
+
+.selected {
+ background: var(--primary-color-light);
+}
+
+.content {
+ flex: 1;
+ overflow-y: auto;
+}
+
+.fileList {
+ .header {
+ display: grid;
+ padding: 12px;
+ background: var(--background-color);
+ font-weight: 600;
+ position: sticky;
+ z-index: 2;
+ top: 0;
+ div {
+ display: flex;
+ width: 100%;
+ justify-content: center;
+ cursor: pointer;
+ user-select: none;
+ &.activeSort {
+ font-weight: bold;
+ cursor: pointer;
+ }
+
+ &:nth-child(1) {
+ justify-content: left;
+ }
+
+ &.headerActions {
+ justify-content: right;
+ }
+ }
+ }
+}
+
+.fileListEmpty {
+ height: calc(100vh - 400px);
+ width: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.virtualFileList {
+ flex: 1;
+ overflow: hidden;
+}
+
+.snapshotFile {
+ display: grid;
+ padding: 12px;
+ align-items: center;
+ box-sizing: border-box;
+ border-bottom: 1px solid var(--line-color);
+ & > div {
+ display: flex;
+ width: 100%;
+ justify-content: center;
+
+ &:nth-child(1) {
+ justify-content: left;
+ gap: 5px;
+ word-break: break-all;
+ }
+ }
+
+ &.fileIsDir {
+ .fileName {
+ cursor: pointer;
+ i {
+ width: 8px;
+ height: 8px;
+ display: inline-block;
+ margin-left: 8px;
+ background: var(--primary-color);
+ border-radius: 50%;
+ }
+ &:hover {
+ color: var(--primary-color);
+ }
+ }
+ }
+
+ .fileModifiedAt {
+ i {
+ font-style: normal;
+ }
+ }
+ .fileModifiedAt,
+ .fileSize {
+ color: var(--content-text-color-light);
+ }
+ .fileActions {
+ display: flex;
+ align-items: center;
+ width: 100%;
+ justify-content: right;
+ button {
+ color: var(--icon-color);
+ transition: all 0.12s linear;
+ &:hover {
+ color: var(--primary-color);
+ }
+ }
+ }
+
+ &:last-child {
+ border-bottom: none;
+ }
+}
+
+.goUpButton {
+ font-style: italic;
+ opacity: 0.8;
+ padding: 0px 12px;
+
+ &:hover {
+ background-color: var(--primary-color-light);
+ }
+
+ .fileName {
+ font-weight: normal;
+ }
+}
+
+.loadingState,
+.errorState {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ height: 400px;
+ gap: 16px;
+ color: var(--text-muted);
+
+ small {
+ color: var(--text-muted);
+ opacity: 0.8;
+ }
+}
+
+.errorState button {
+ padding: 8px 16px;
+ background: var(--primary);
+ color: white;
+ border: none;
+ border-radius: 4px;
+ cursor: pointer;
+}
+
+.restoreModalFile {
+ word-break: break-all;
+ background: var(--primary-color-light);
+ padding: 10px;
+ border-radius: 6px;
+}
+
+@media only screen and (max-width: 768px) {
+ .toolbar {
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 10px;
+ .toolbarLeft {
+ width: 100%;
+ .stats {
+ font-size: 0.9em;
+ :global(.icon) {
+ display: none;
+ }
+ }
+ }
+ .toolbarRight {
+ width: 100%;
+ .search {
+ width: 100%;
+ }
+ }
+ }
+ .sidebar {
+ display: none;
+ }
+
+ .content {
+ padding: 0;
+ }
+
+ .fileList {
+ .header {
+ display: none;
+ }
+ .snapshotFile {
+ display: block;
+ padding: 10px;
+ font-size: 0.9em;
+ .fileName {
+ width: 100%;
+ margin-bottom: 4px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ & > div {
+ display: block;
+ width: auto;
+ float: left;
+ margin-right: 12px;
+ }
+ .fileActions {
+ display: block;
+ width: auto;
+ float: right;
+ margin-right: 0;
+ }
+ &.goUpButton {
+ display: flex;
+ align-items: center;
+ .fileName::after {
+ content: ' Go Up ↑';
+ font-size: 12px;
+ font-style: normal;
+ font-weight: 500;
+ }
+ }
+ }
+ }
+}
diff --git a/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserDirectories.tsx b/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserDirectories.tsx
new file mode 100644
index 0000000..5fffc8c
--- /dev/null
+++ b/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserDirectories.tsx
@@ -0,0 +1,84 @@
+import { ReactNode } from 'react';
+import Icon from '../Icon/Icon';
+import classes from './SnapshotBrowser.module.scss';
+
+interface SnapshotBrowserDirectoriesProps {
+ directories: string[];
+ selectedFolder: string;
+ expandedFolders: Set<string>;
+ useProgressiveLoading?: boolean;
+ onDirectoryClick: (path: string) => void;
+ onToggleFolder: (dir: string) => void;
+ isVisible: (dir: string) => boolean;
+ hasSubdirectories: (dir: string) => boolean;
+ renderDirectoryExtra?: (dir: string) => ReactNode;
+ /** Custom function to split a path into parts. Defaults to splitting by / and \ */
+ splitPath?: (path: string) => string[];
+}
+
+const defaultSplitPath = (path: string) => path.split(/[/\\]/).filter(Boolean);
+
+const SnapshotBrowserDirectories = ({
+ directories,
+ selectedFolder,
+ expandedFolders,
+ useProgressiveLoading,
+ onDirectoryClick,
+ onToggleFolder,
+ isVisible,
+ hasSubdirectories,
+ renderDirectoryExtra,
+ splitPath: splitPathFn = defaultSplitPath,
+}: SnapshotBrowserDirectoriesProps) => {
+ return (
+ <div className={`${classes.sidebar} styled__scrollbar`}>
+ <div className={classes.sidebarHeader}>
+ <h4>
+ Directories ({directories.length}
+ {useProgressiveLoading && '+'})
+ </h4>
+ </div>
+ {directories.length === 0 && (
+ <div className={classes.noDirectories}>{useProgressiveLoading ? 'Loading directories...' : 'No directories found'}</div>
+ )}
+ {directories.map((dir) => {
+ const parts = splitPathFn(dir);
+ const dirName = parts[parts.length - 1] || dir;
+ const depth = parts.length - 1;
+ const isExpanded = expandedFolders.has(dir);
+ const hasChildren = hasSubdirectories(dir);
+
+ if (!isVisible(dir)) return null;
+
+ return (
+ <div
+ key={dir}
+ className={`${classes.directory} ${selectedFolder === dir ? classes.selected : ''} ${hasChildren ? '' : classes.directoryEmpty}`}
+ style={{ paddingLeft: `${depth * 20}px` }}
+ onClick={() => onDirectoryClick(dir)}
+ >
+ {hasChildren ? (
+ <button
+ className={classes.toggleButton}
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggleFolder(dir);
+ }}
+ >
+ {isExpanded ? '-' : '+'}
+ </button>
+ ) : (
+ <span className={classes.togglePlaceholder} />
+ )}
+ <span className={classes.dirName}>
+ <Icon type={'fm-directory'} size={14} /> {dirName}
+ </span>
+ {renderDirectoryExtra?.(dir)}
+ </div>
+ );
+ })}
+ </div>
+ );
+};
+
+export default SnapshotBrowserDirectories;
diff --git a/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserFileList.tsx b/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserFileList.tsx
new file mode 100644
index 0000000..526b27d
--- /dev/null
+++ b/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserFileList.tsx
@@ -0,0 +1,52 @@
+import React, { ReactNode } from 'react';
+import { FixedSizeList as List } from 'react-window';
+import classes from './SnapshotBrowser.module.scss';
+import { isMobile } from '../../../utils';
+
+const isMobileDevice = isMobile();
+const DEFAULT_ITEM_HEIGHT = isMobileDevice ? 65 : 46;
+
+interface SnapshotBrowserFileListProps {
+ files: any[];
+ height: number;
+ itemSize?: number;
+ headerContent: ReactNode;
+ renderRow: (props: { index: number; style: React.CSSProperties }) => React.ReactElement | null;
+ selectedFolder: string | null;
+ emptyMessage?: string;
+ isLoading?: boolean;
+ gridTemplateColumns?: string;
+}
+
+const SnapshotBrowserFileList = ({
+ files,
+ height,
+ itemSize = DEFAULT_ITEM_HEIGHT,
+ headerContent,
+ renderRow,
+ selectedFolder,
+ emptyMessage = 'Select a folder from the left to browse its content',
+ isLoading,
+ gridTemplateColumns,
+}: SnapshotBrowserFileListProps) => {
+ return (
+ <div className={classes.fileList}>
+ <div className={classes.header} style={gridTemplateColumns ? { gridTemplateColumns } : undefined}>
+ {headerContent}
+ </div>
+
+ {selectedFolder !== null && files.length > 0 && (
+ <div className={classes.virtualFileList}>
+ <List height={height} itemCount={files.length} itemSize={itemSize} width="100%" overscanCount={5}>
+ {renderRow}
+ </List>
+ </div>
+ )}
+
+ {selectedFolder === null && <div className={classes.fileListEmpty}>{emptyMessage}</div>}
+ {selectedFolder !== null && !isLoading && files.length === 0 && <div className={classes.fileListEmpty}>This folder is empty</div>}
+ </div>
+ );
+};
+
+export default SnapshotBrowserFileList;
diff --git a/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserFileRow.tsx b/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserFileRow.tsx
new file mode 100644
index 0000000..6998398
--- /dev/null
+++ b/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserFileRow.tsx
@@ -0,0 +1,44 @@
+import React, { ReactNode } from 'react';
+import Icon from '../Icon/Icon';
+import FileIcon from '../FileIcon/FileIcon';
+import classes from './SnapshotBrowser.module.scss';
+
+interface SnapshotBrowserFileRowProps {
+ style: React.CSSProperties;
+ file: { path: string; name?: string; isDirectory?: boolean };
+ isDirectory: boolean;
+ onClick?: () => void;
+ namePrefix?: ReactNode;
+ children?: ReactNode;
+ gridTemplateColumns?: string;
+ className?: string;
+}
+
+const SnapshotBrowserFileRow = ({
+ style,
+ file,
+ isDirectory,
+ onClick,
+ namePrefix,
+ children,
+ gridTemplateColumns,
+ className,
+}: SnapshotBrowserFileRowProps) => {
+ const fileName = file.name || file.path.split('/').pop() || '';
+
+ return (
+ <div
+ style={{ ...style, ...(gridTemplateColumns ? { gridTemplateColumns } : {}) }}
+ className={`${classes.snapshotFile} ${isDirectory ? classes.fileIsDir : ''} ${className || ''}`}
+ onClick={onClick}
+ >
+ <div className={classes.fileName}>
+ {namePrefix}
+ {isDirectory ? <Icon type={'fm-directory'} size={16} /> : <FileIcon filename={fileName} />} {fileName}
+ </div>
+ {children}
+ </div>
+ );
+};
+
+export default SnapshotBrowserFileRow;
diff --git a/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserGoUpRow.tsx b/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserGoUpRow.tsx
new file mode 100644
index 0000000..10596ee
--- /dev/null
+++ b/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserGoUpRow.tsx
@@ -0,0 +1,22 @@
+import React from 'react';
+import classes from './SnapshotBrowser.module.scss';
+
+interface SnapshotBrowserGoUpRowProps {
+ style: React.CSSProperties;
+ onGoUp: () => void;
+ gridTemplateColumns?: string;
+}
+
+const SnapshotBrowserGoUpRow = ({ style, onGoUp, gridTemplateColumns }: SnapshotBrowserGoUpRowProps) => {
+ return (
+ <div
+ style={{ ...style, ...(gridTemplateColumns ? { gridTemplateColumns } : {}) }}
+ className={`${classes.snapshotFile} ${classes.fileIsDir} ${classes.goUpButton}`}
+ onClick={onGoUp}
+ >
+ <div className={classes.fileName}>...</div>
+ </div>
+ );
+};
+
+export default SnapshotBrowserGoUpRow;
diff --git a/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserToolbar.tsx b/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserToolbar.tsx
new file mode 100644
index 0000000..1dfb393
--- /dev/null
+++ b/frontend/src/components/common/SnapshotBrowser/SnapshotBrowserToolbar.tsx
@@ -0,0 +1,29 @@
+import { ReactNode } from 'react';
+import Icon from '../Icon/Icon';
+import classes from './SnapshotBrowser.module.scss';
+
+interface SnapshotBrowserToolbarProps {
+ search: string;
+ onSearchChange: (value: string) => void;
+ isLoading?: boolean;
+ leftContent?: ReactNode;
+ rightContent?: ReactNode;
+}
+
+const SnapshotBrowserToolbar = ({ search, onSearchChange, isLoading, leftContent, rightContent }: SnapshotBrowserToolbarProps) => {
+ return (
+ <div className={classes.toolbar}>
+ <div className={classes.toolbarLeft}>{leftContent}</div>
+ <div className={classes.toolbarRight}>
+ {rightContent}
+ <div className={classes.search}>
+ <Icon type="search" size={16} />
+ <input type="text" placeholder="Search in current Directory..." value={search} onChange={(e) => onSearchChange(e.target.value)} />
+ {isLoading && <Icon type="loading" size={12} />}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default SnapshotBrowserToolbar;
diff --git a/frontend/src/components/common/SnapshotBrowser/hooks/useSnapshotDatabase.ts b/frontend/src/components/common/SnapshotBrowser/hooks/useSnapshotDatabase.ts
new file mode 100644
index 0000000..8523bc8
--- /dev/null
+++ b/frontend/src/components/common/SnapshotBrowser/hooks/useSnapshotDatabase.ts
@@ -0,0 +1,130 @@
+import { useState, useEffect, useCallback } from 'react';
+import { SnapshotDatabase } from '../../../../utils';
+import { FileItem } from '../../../../@types';
+
+export const useSnapshotDatabase = (files: FileItem[], backupId: string, useProgressiveLoading: boolean) => {
+ const [db, setDb] = useState<SnapshotDatabase | null>(null);
+ const [initError, setInitError] = useState<string | null>(null);
+ const [discoveredDirectories, setDiscoveredDirectories] = useState<string[]>([]);
+ const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
+
+ // Helper function to sort directories in true hierarchical order
+ const sortDirectoriesHierarchically = useCallback((dirs: string[]): string[] => {
+ const tree: { [key: string]: string[] } = {};
+ const roots: string[] = [];
+
+ // Build parent-child relationships
+ dirs.forEach((dir) => {
+ const parentPath = dir.substring(0, dir.lastIndexOf('/')) || '';
+ if (!tree[parentPath]) {
+ tree[parentPath] = [];
+ }
+ tree[parentPath].push(dir);
+ });
+
+ // Find root directories (those whose parent is not in the list)
+ dirs.forEach((dir) => {
+ const parentPath = dir.substring(0, dir.lastIndexOf('/')) || '';
+ if (parentPath === '' || !dirs.includes(parentPath)) {
+ roots.push(dir);
+ }
+ });
+
+ // Recursively build sorted list
+ const sortedList: string[] = [];
+
+ const addChildrenRecursively = (parent: string) => {
+ const children = tree[parent] || [];
+ children.sort((a, b) => {
+ const nameA = a.split('/').pop() || '';
+ const nameB = b.split('/').pop() || '';
+ return nameA.localeCompare(nameB);
+ });
+
+ children.forEach((child) => {
+ sortedList.push(child);
+ addChildrenRecursively(child);
+ });
+ };
+
+ roots.sort((a, b) => {
+ const nameA = a.split('/').pop() || '';
+ const nameB = b.split('/').pop() || '';
+ return nameA.localeCompare(nameB);
+ });
+
+ roots.forEach((root) => {
+ sortedList.push(root);
+ addChildrenRecursively(root);
+ });
+
+ return sortedList;
+ }, []);
+
+ // Helper function to add new directories while maintaining sorted order
+ const addDirectoriesSorted = useCallback(
+ (newDirs: string[]) => {
+ setDiscoveredDirectories((prev) => {
+ const allDirs = [...prev, ...newDirs];
+ const uniqueDirs = Array.from(new Set(allDirs));
+ return sortDirectoriesHierarchically(uniqueDirs);
+ });
+ },
+ [sortDirectoriesHierarchically],
+ );
+
+ // Initialize database
+ useEffect(() => {
+ const initDb = async () => {
+ try {
+ console.log('Initializing database for', files.length, 'files');
+ const database = new SnapshotDatabase(backupId);
+ await database.initializeFromFiles(files);
+ setDb(database);
+ console.log('Database initialized successfully');
+
+ if (useProgressiveLoading) {
+ // Load only top-level directories initially
+ const topDirs = await database.getTopLevelDirectories(3);
+ const sortedTopDirs = sortDirectoriesHierarchically(topDirs);
+ setDiscoveredDirectories(sortedTopDirs);
+ console.log('Loaded top-level directories:', sortedTopDirs.length);
+
+ const initialExpanded = new Set<string>();
+ sortedTopDirs.slice(0, 2).forEach((dir) => initialExpanded.add(dir));
+ setExpandedFolders(initialExpanded);
+ } else {
+ // For smaller datasets, load all directories
+ const allDirs = await database.getTopLevelDirectories(999);
+ const sortedAllDirs = sortDirectoriesHierarchically(allDirs);
+ setDiscoveredDirectories(sortedAllDirs);
+
+ const initialExpanded = new Set<string>();
+ sortedAllDirs.slice(0, 3).forEach((dir) => initialExpanded.add(dir));
+ setExpandedFolders(initialExpanded);
+ }
+ } catch (error) {
+ console.error('Failed to initialize database:', error);
+ setInitError(error instanceof Error ? error.message : 'Unknown error');
+ }
+ };
+
+ initDb();
+
+ return () => {
+ if (db) {
+ db.cleanup().catch(console.error);
+ }
+ };
+ }, [files, backupId, useProgressiveLoading, sortDirectoriesHierarchically]);
+
+ return {
+ db,
+ initError,
+ discoveredDirectories,
+ expandedFolders,
+ setExpandedFolders,
+ setDiscoveredDirectories,
+ addDirectoriesSorted,
+ };
+};
diff --git a/frontend/src/components/common/SnapshotBrowser/hooks/useSnapshotNavigation.ts b/frontend/src/components/common/SnapshotBrowser/hooks/useSnapshotNavigation.ts
new file mode 100644
index 0000000..6da13d0
--- /dev/null
+++ b/frontend/src/components/common/SnapshotBrowser/hooks/useSnapshotNavigation.ts
@@ -0,0 +1,154 @@
+import { useState, useCallback } from 'react';
+
+interface UseSnapshotNavigationOptions {
+ onDirectoryExpand?: (dir: string) => Promise<string[]>;
+ /** Custom split function for paths. Default: split by '/' and filter empty strings. */
+ splitPath?: (path: string) => string[];
+ /** Custom separator detection per path. Default: always '/'. */
+ getPathSeparator?: (path: string) => string;
+ /** Whether to prepend separator when building parent paths (e.g. /home vs home). Default: true. */
+ hasLeadingSeparator?: boolean;
+}
+
+const defaultSplitPath = (path: string) => path.split('/').filter(Boolean);
+const defaultGetPathSeparator = () => '/';
+
+export const useSnapshotNavigation = (
+ directories: string[],
+ expandedFolders: Set<string>,
+ setExpandedFolders: React.Dispatch<React.SetStateAction<Set<string>>>,
+ options?: UseSnapshotNavigationOptions,
+) => {
+ const [selectedFolder, setSelectedFolder] = useState<string>('');
+
+ const splitPathFn = options?.splitPath || defaultSplitPath;
+ const getPathSeparatorFn = options?.getPathSeparator || defaultGetPathSeparator;
+ const hasLeadingSep = options?.hasLeadingSeparator ?? true;
+
+ const hasSubdirectories = useCallback(
+ (dir: string) => {
+ const sep = getPathSeparatorFn(dir);
+ return directories.some((d) => d !== dir && d.startsWith(dir + sep));
+ },
+ [directories, getPathSeparatorFn],
+ );
+
+ const isVisible = useCallback(
+ (dir: string) => {
+ const parts = splitPathFn(dir);
+ if (parts.length <= 1) return true;
+
+ const sep = getPathSeparatorFn(dir);
+ const parentParts = parts.slice(0, -1);
+ let parentPath = '';
+
+ return parentParts.every((part) => {
+ if (!parentPath) {
+ parentPath = hasLeadingSep ? `${sep}${part}` : part;
+ } else {
+ parentPath = `${parentPath}${sep}${part}`;
+ }
+ return expandedFolders.has(parentPath);
+ });
+ },
+ [expandedFolders, splitPathFn, getPathSeparatorFn, hasLeadingSep],
+ );
+
+ const expandParentFolders = useCallback(
+ (dirPath: string) => {
+ setExpandedFolders((prev) => {
+ const newExpanded = new Set(prev);
+ const parts = splitPathFn(dirPath);
+ const sep = getPathSeparatorFn(dirPath);
+ let currentPath = '';
+
+ parts.forEach((part) => {
+ if (!currentPath) {
+ currentPath = hasLeadingSep ? `${sep}${part}` : part;
+ } else {
+ currentPath = `${currentPath}${sep}${part}`;
+ }
+ newExpanded.add(currentPath);
+ });
+
+ return newExpanded;
+ });
+ },
+ [setExpandedFolders, splitPathFn, getPathSeparatorFn, hasLeadingSep],
+ );
+
+ const toggleFolder = useCallback(
+ async (dir: string) => {
+ setExpandedFolders((prev) => {
+ const newExpanded = new Set(prev);
+ if (newExpanded.has(dir)) {
+ newExpanded.delete(dir);
+ } else {
+ newExpanded.add(dir);
+ }
+ return newExpanded;
+ });
+
+ // If expanding and progressive loading, discover subdirectories
+ if (!expandedFolders.has(dir) && options?.onDirectoryExpand) {
+ try {
+ await options.onDirectoryExpand(dir);
+ } catch (error) {
+ console.error('Error discovering subdirectories:', error);
+ }
+ }
+ },
+ [expandedFolders, setExpandedFolders, options],
+ );
+
+ const handleGoUp = useCallback(() => {
+ if (!selectedFolder) return;
+ const sep = getPathSeparatorFn(selectedFolder);
+ const lastSepIndex = selectedFolder.lastIndexOf(sep);
+ if (lastSepIndex <= 0) {
+ setSelectedFolder('');
+ } else {
+ setSelectedFolder(selectedFolder.substring(0, lastSepIndex));
+ }
+ }, [selectedFolder, getPathSeparatorFn]);
+
+ const handleDirectoryClick = useCallback(
+ async (path: string) => {
+ expandParentFolders(path);
+ setSelectedFolder(path);
+
+ // If progressive loading, discover subdirectories when navigating
+ if (options?.onDirectoryExpand) {
+ try {
+ await options.onDirectoryExpand(path);
+ } catch (error) {
+ console.error('Error discovering subdirectories:', error);
+ }
+ }
+ },
+ [expandParentFolders, options],
+ );
+
+ const getParentPath = useCallback(
+ (path: string) => {
+ if (!path) return null;
+ const sep = getPathSeparatorFn(path);
+ const lastSepIndex = path.lastIndexOf(sep);
+ if (lastSepIndex <= 0) return '';
+ return path.substring(0, lastSepIndex);
+ },
+ [getPathSeparatorFn],
+ );
+
+ return {
+ selectedFolder,
+ setSelectedFolder,
+ hasSubdirectories,
+ isVisible,
+ expandParentFolders,
+ toggleFolder,
+ handleGoUp,
+ handleDirectoryClick,
+ getParentPath,
+ };
+};
diff --git a/frontend/src/components/common/SnapshotBrowser/hooks/useSnapshotSort.ts b/frontend/src/components/common/SnapshotBrowser/hooks/useSnapshotSort.ts
new file mode 100644
index 0000000..ed53225
--- /dev/null
+++ b/frontend/src/components/common/SnapshotBrowser/hooks/useSnapshotSort.ts
@@ -0,0 +1,24 @@
+import { useState, useCallback } from 'react';
+
+export const useSnapshotSort = () => {
+ const [sortField, setSortField] = useState<'name' | 'modifiedAt' | 'size'>('name');
+ const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
+
+ const handleSort = useCallback(
+ (field: 'name' | 'modifiedAt' | 'size') => {
+ if (sortField === field) {
+ setSortDirection((prev) => (prev === 'asc' ? 'desc' : 'asc'));
+ } else {
+ setSortField(field);
+ setSortDirection('asc');
+ }
+ },
+ [sortField],
+ );
+
+ return {
+ sortField,
+ sortDirection,
+ handleSort,
+ };
+};
diff --git a/frontend/src/components/common/SnapshotBrowser/index.ts b/frontend/src/components/common/SnapshotBrowser/index.ts
new file mode 100644
index 0000000..432c6b0
--- /dev/null
+++ b/frontend/src/components/common/SnapshotBrowser/index.ts
@@ -0,0 +1,13 @@
+// Components
+export { default as SnapshotBrowserToolbar } from './SnapshotBrowserToolbar';
+export { default as SnapshotBrowserDirectories } from './SnapshotBrowserDirectories';
+export { default as SnapshotBrowserFileList } from './SnapshotBrowserFileList';
+export { default as SnapshotBrowserFileRow } from './SnapshotBrowserFileRow';
+export { default as SnapshotBrowserGoUpRow } from './SnapshotBrowserGoUpRow';
+export { default as SnapshotViewer } from '../../Plan/SnapshotViewer/SnapshotViewer';
+export { default as SnapshotViewerFile } from '../../Plan/SnapshotViewer/SnapshotViewerFile';
+
+// Hooks
+export { useSnapshotSort } from './hooks/useSnapshotSort';
+export { useSnapshotNavigation } from './hooks/useSnapshotNavigation';
+export { useSnapshotDatabase } from './hooks/useSnapshotDatabase';
diff --git a/frontend/src/components/index.ts b/frontend/src/components/index.ts
index fbd6889..776c6ed 100644
--- a/frontend/src/components/index.ts
+++ b/frontend/src/components/index.ts
@@ -90,6 +90,8 @@ export { default as PlanTypeSettings } from './Plan/PlanSettings/PlanTypeSetting
export { default as PlanStats } from './Plan/PlanStats/PlanStats';
export { default as PlanUnlockModal } from './Plan/PlanUnlockModal/PlanUnlockModal';
export { default as PlanIntegrity } from './Plan/PlanIntegrity/PlanIntegrity';
+export { default as SnapshotViewer } from './Plan/SnapshotViewer/SnapshotViewer';
+export { default as SnapshotViewerFile } from './Plan/SnapshotViewer/SnapshotViewerFile';
// Mirror/Replication components
export { default as MirrorStatusBadge } from './Plan/Mirrors/MirrorStatusBadge';
@@ -126,3 +128,14 @@ export { default as EditStorage } from './Storage/EditStorage/EditStorage';
export { default as StorageAuthSettings } from './Storage/StorageAuthSettings/StorageAuthSettings';
export { default as StorageItem } from './Storage/StorageItem/StorageItem';
export { default as StorageSettings } from './Storage/StorageSettings/StorageSettings';
+
+// SnapshotBrowser components
+export { default as SnapshotBrowserToolbar } from './common/SnapshotBrowser/SnapshotBrowserToolbar';
+export { default as SnapshotBrowserDirectories } from './common/SnapshotBrowser/SnapshotBrowserDirectories';
+export { default as SnapshotBrowserFileList } from './common/SnapshotBrowser/SnapshotBrowserFileList';
+export { default as SnapshotBrowserFileRow } from './common/SnapshotBrowser/SnapshotBrowserFileRow';
+export { default as SnapshotBrowserGoUpRow } from './common/SnapshotBrowser/SnapshotBrowserGoUpRow';
+export { useSnapshotSort } from './common/SnapshotBrowser/hooks/useSnapshotSort';
+export { useSnapshotNavigation } from './common/SnapshotBrowser/hooks/useSnapshotNavigation';
+export { useSnapshotDatabase } from './common/SnapshotBrowser/hooks/useSnapshotDatabase';
+// export { default as SnapshotBrowserStyles } from './common/SnapshotBrowser/SnapshotBrowser.module.scss';
diff --git a/frontend/src/services/backups.ts b/frontend/src/services/backups.ts
index 3bf38b9..7728272 100644
--- a/frontend/src/services/backups.ts
+++ b/frontend/src/services/backups.ts
@@ -261,6 +261,18 @@ export function useGetSnapshotFiles(payload: { backupId: string }) {
});
}
+// Get Snapshot Files (Mutation)
+// To be used for manual refresh or when triggered from an action,
+// since it bypasses the cache and directly calls the API
+export function useBrowseSnapshot() {
+ return useMutation({
+ mutationFn: getSnapshotFiles,
+ onSuccess: (res, payload) => {
+ console.log('res :', payload, res);
+ },
+ });
+}
+
// Retry Failed Replications
export async function retryFailedReplications({ backupId, replicationId }: { backupId: string; planId: string; replicationId: string }) {
const header = new Headers({ 'Content-Type': 'application/json', Accept: 'application/json' });
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index 380e076..13584a0 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -8,4 +8,5 @@ export * from './plans';
export * from './progressHelpers';
export * from './restore';
export * from './getIconNameforFile';
+export { default as SnapshotDatabase } from './snapshotDatabase';
// Note: dummy.ts is excluded as it's likely for testing/development only
diff --git a/frontend/src/utils/snapshotDatabase.ts b/frontend/src/utils/snapshotDatabase.ts
new file mode 100644
index 0000000..63ac162
--- /dev/null
+++ b/frontend/src/utils/snapshotDatabase.ts
@@ -0,0 +1,201 @@
+import { FileItem } from '../@types/system';
+
+// Lazy load Dexie only when needed
+let DexieModule: any = null;
+
+async function loadDexie() {
+ if (!DexieModule) {
+ DexieModule = await import('dexie');
+ }
+ return DexieModule;
+}
+
+interface FileRecord extends FileItem {
+ id?: number;
+ parentPath: string;
+ fileName: string;
+ depth: number;
+ isDirFlag: number; // 1 for directory, 0 for file
+}
+
+class SnapshotDatabase {
+ private db: any = null;
+ private isInitialized = false;
+
+ constructor(private backupId: string) {}
+
+ async initialize() {
+ if (this.isInitialized) return;
+
+ const { Dexie } = await loadDexie();
+
+ this.db = new Dexie(`SnapshotDB_${this.backupId}`);
+ this.db.version(1).stores({
+ files: '++id, path, parentPath, fileName, isDirFlag, size, modifiedAt, depth',
+ });
+
+ this.isInitialized = true;
+ }
+
+ async initializeFromFiles(files: FileItem[]) {
+ await this.initialize();
+
+ // Clear existing data
+ await this.db.files.clear();
+
+ // Process and insert files in batches
+ const batchSize = 1000;
+ const records: FileRecord[] = [];
+
+ for (let i = 0; i < files.length; i++) {
+ const file = files[i];
+ const lastSlashIndex = file.path.lastIndexOf('/');
+ const parentPath = file.path.substring(0, lastSlashIndex);
+ const fileName = (file.name || file.path.split('/').pop() || '').toLowerCase();
+ const depth = file.path.split('/').filter(Boolean).length;
+
+ const isDirFlag = file.isDirectory ? 1 : 0;
+
+ records.push({
+ ...file,
+ parentPath,
+ fileName,
+ depth,
+ isDirFlag,
+ });
+
+ if (records.length >= batchSize) {
+ await this.db.files.bulkAdd(records);
+ records.length = 0;
+ }
+ }
+
+ if (records.length > 0) {
+ await this.db.files.bulkAdd(records);
+ }
+
+ console.log('Database initialized with', await this.db.files.count(), 'total records');
+ }
+
+ // Get only top-level directories (depth <= maxDepth)
+ async getTopLevelDirectories(maxDepth: number = 3): Promise<string[]> {
+ if (!this.isInitialized) await this.initialize();
+
+ try {
+ const dirRecords = await this.db.files
+ .where('isDirFlag')
+ .equals(1)
+ .and((record: FileRecord) => record.depth <= maxDepth)
+ .toArray();
+
+ const paths = dirRecords.map((record: FileRecord) => record.path);
+ console.log(`getTopLevelDirectories (depth <= ${maxDepth}) returning:`, paths.length, 'directories');
+ return paths;
+ } catch (error) {
+ console.error('Error getting top-level directories:', error);
+ return [];
+ }
+ }
+
+ // Check if a directory has subdirectories
+ async hasSubdirectories(dirPath: string): Promise<boolean> {
+ if (!this.isInitialized) await this.initialize();
+
+ try {
+ const count = await this.db.files
+ .where('parentPath')
+ .equals(dirPath)
+ .and((record: FileRecord) => record.isDirFlag === 1)
+ .count();
+
+ return count > 0;
+ } catch (error) {
+ console.error('Error checking subdirectories:', error);
+ return false;
+ }
+ }
+
+ // Get immediate subdirectories of a given directory
+ async getSubdirectories(parentPath: string): Promise<string[]> {
+ if (!this.isInitialized) await this.initialize();
+
+ try {
+ const subdirs = await this.db.files
+ .where('parentPath')
+ .equals(parentPath)
+ .and((record: FileRecord) => record.isDirFlag === 1)
+ .toArray();
+
+ const paths = subdirs.map((record: FileRecord) => record.path);
+ console.log(`getSubdirectories for ${parentPath}:`, paths.length, 'subdirectories');
+ return paths;
+ } catch (error) {
+ console.error('Error getting subdirectories:', error);
+ return [];
+ }
+ }
+
+ // Get directory contents (files and folders in a specific directory)
+ async getDirectoryContents(
+ dirPath: string,
+ sortField: string = 'name',
+ sortDirection: string = 'asc',
+ searchTerm: string = '',
+ ): Promise<FileItem[]> {
+ if (!this.isInitialized) await this.initialize();
+
+ try {
+ let results: FileRecord[];
+
+ if (searchTerm.trim()) {
+ const allInDir = await this.db.files.where('parentPath').equals(dirPath).toArray();
+ const lowerSearch = searchTerm.toLowerCase();
+ results = allInDir.filter((item: FileRecord) => item.fileName.includes(lowerSearch) || item.path.toLowerCase().includes(lowerSearch));
+ } else {
+ results = await this.db.files.where('parentPath').equals(dirPath).toArray();
+ }
+
+ // Sort results
+ results.sort((a: FileRecord, b: FileRecord) => {
+ // Directories first
+ if (a.isDirFlag && !b.isDirFlag) return -1;
+ if (!a.isDirFlag && b.isDirFlag) return 1;
+
+ let aVal: any, bVal: any;
+ switch (sortField) {
+ case 'name':
+ aVal = a.fileName;
+ bVal = b.fileName;
+ break;
+ case 'modifiedAt':
+ aVal = new Date(a.modifiedAt).getTime();
+ bVal = new Date(b.modifiedAt).getTime();
+ break;
+ case 'size':
+ aVal = a.size || 0;
+ bVal = b.size || 0;
+ break;
+ default:
+ return 0;
+ }
+
+ if (aVal < bVal) return sortDirection === 'asc' ? -1 : 1;
+ if (aVal > bVal) return sortDirection === 'asc' ? 1 : -1;
+ return 0;
+ });
+
+ return results;
+ } catch (error) {
+ console.error('Error getting directory contents:', error);
+ return [];
+ }
+ }
+
+ async cleanup() {
+ if (this.db) {
+ await this.db.delete();
+ }
+ }
+}
+
+export default SnapshotDatabase;