import { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog'; import { Progress } from '@/components/ui/progress'; import { Switch } from '@/components/ui/switch'; import { useToast } from '@/hooks/useToast'; import { useFS } from '@/hooks/useFS'; import { useIsMobile } from '@/hooks/useIsMobile'; import { useOffline } from '@/hooks/useOffline'; import { isPersistentStorageSupported, isPersistentStorageGranted, requestPersistentStorage, getStorageInfo } from '@/lib/persistentStorage'; import JSZip from 'jszip'; interface StorageUsageDetails { indexedDB?: number; caches?: number; serviceWorkerRegistrations?: number; [key: string]: number | undefined; } interface StorageInfo { quota: number; usage: number; usageDetails?: StorageUsageDetails; } export function StorageSettings() { const { t } = useTranslation(); const [isExporting, setIsExporting] = useState(false); const [isClearing, setIsClearing] = useState(false); const [isRequestingPersistent, setIsRequestingPersistent] = useState(false); const [storageInfo, setStorageInfo] = useState(null); const [storageError, setStorageError] = useState(null); const [isPersistent, setIsPersistent] = useState(null); const { toast } = useToast(); const { fs } = useFS(); const navigate = useNavigate(); const isMobile = useIsMobile(); const { clearCache } = useOffline(); // Format bytes to human readable format const formatBytes = (bytes: number): string => { if (bytes === 0) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; }; // Load storage information and persistent status useEffect(() => { const loadStorageInfo = async () => { try { // Check if StorageManager API is available if (!isPersistentStorageSupported()) { setStorageError('StorageManager API is not available in this browser'); return; } // Get storage estimate const info = await getStorageInfo(); if (info) { setStorageInfo({ quota: info.quota, usage: info.usage, usageDetails: info.usageDetails as StorageUsageDetails, }); } // Check if storage is persistent const persistent = await isPersistentStorageGranted(); setIsPersistent(persistent); } catch (error) { console.error('Failed to get storage information:', error); setStorageError(error instanceof Error ? error.message : 'Failed to get storage information'); } }; loadStorageInfo(); }, []); const exportFilesAsZip = async () => { const zip = new JSZip(); // Recursive function to add files and directories to zip const addToZip = async (dirPath: string, zipFolder: JSZip) => { try { const entries = await fs.readdir(dirPath, { withFileTypes: true }); for (const entry of entries) { const fullPath = dirPath === '/' ? `/${entry.name}` : `${dirPath}/${entry.name}`; if (entry.isDirectory()) { // Create folder in zip and recursively add its contents const folder = zipFolder.folder(entry.name); if (folder) { await addToZip(fullPath, folder); } } else if (entry.isFile()) { // Add file to zip try { const fileContent = await fs.readFile(fullPath); zipFolder.file(entry.name, fileContent); } catch (error) { console.warn(`Failed to read file ${fullPath}:`, error); } } } } catch (error) { console.warn(`Failed to read directory ${dirPath}:`, error); } }; // Start from root directory await addToZip('/', zip); // Generate zip file const content = await zip.generateAsync({ type: 'blob' }); // Create download link const url = URL.createObjectURL(content); const link = document.createElement('a'); link.href = url; // Generate filename with date const now = new Date(); const dateStr = now.toISOString().split('T')[0]; // YYYY-MM-DD format link.download = `shakespeare-projects-${dateStr}.zip`; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); }; const handleExportFiles = async () => { setIsExporting(true); try { await exportFilesAsZip(); toast({ title: t('filesExportedSuccessfully'), description: t('filesExportedDescription'), }); } catch (error) { console.error('Failed to export files:', error); toast({ title: t('failedToExportFiles'), description: error instanceof Error ? error.message : t('error'), variant: "destructive", }); } finally { setIsExporting(false); } }; const handlePersistentStorageToggle = async (checked: boolean) => { // If trying to turn off, we can't actually do that - just ignore if (!checked) { return; } setIsRequestingPersistent(true); try { // Check if persist method is available if (!isPersistentStorageSupported()) { toast({ title: t('persistentStorageNotSupported'), description: t('persistentStorageNotSupportedDescription'), variant: "destructive", }); return; } // Check if already persistent const alreadyPersistent = await isPersistentStorageGranted(); if (alreadyPersistent) { setIsPersistent(true); toast({ title: t('persistentStorageAlreadyGranted'), description: t('persistentStorageAlreadyGrantedDescription'), }); return; } // Request persistent storage const granted = await requestPersistentStorage(); if (granted) { setIsPersistent(true); toast({ title: t('persistentStorageGranted'), description: t('persistentStorageGrantedDescription'), }); } else { toast({ title: t('persistentStorageDenied'), description: t('persistentStorageDeniedDescription'), variant: "destructive", }); } } catch (error) { console.error('Failed to request persistent storage:', error); toast({ title: t('failedToRequestPersistentStorage'), description: error instanceof Error ? error.message : t('error'), variant: "destructive", }); } finally { setIsRequestingPersistent(false); } }; const handleClearAllData = async () => { setIsClearing(true); try { // Clear localStorage localStorage.clear(); // Clear caches await clearCache(); // Clear IndexedDB databases const databases = await indexedDB.databases(); const deletePromises = databases.map(db => { if (db.name) { return new Promise((resolve, reject) => { const deleteReq = indexedDB.deleteDatabase(db.name!); deleteReq.onsuccess = () => resolve(); deleteReq.onerror = () => reject(deleteReq.error); deleteReq.onblocked = () => { console.warn(`Delete blocked for database: ${db.name}`); // Still resolve to continue with the process resolve(); }; }); } return Promise.resolve(); }); await Promise.all(deletePromises); toast({ title: t('dataClearedSuccessfully'), description: t('dataClearedDescription'), }); // Small delay to show the toast, then redirect setTimeout(() => { navigate('/'); }, 1500); } catch (error) { console.error('Failed to clear data:', error); toast({ title: t('failedToClearData'), description: error instanceof Error ? error.message : t('error'), variant: "destructive", }); } finally { setIsClearing(false); } }; return (
{isMobile && (

{t('storageSettings')}

{t('storageSettingsDescription')}

)} {!isMobile && (

{t('storageSettings')}

{t('storageSettingsDescription')}

)}
{/* Storage Information */} {storageError ? (
{storageError}
) : storageInfo ? (
{/* Usage Progress */}
{t('used')}: {formatBytes(storageInfo.usage)} {t('available')}: {formatBytes(storageInfo.quota)}
0 ? (storageInfo.usage / storageInfo.quota) * 100 : 0} className="h-2" />
{storageInfo.quota > 0 ? t('usagePercentage', { percentage: ((storageInfo.usage / storageInfo.quota) * 100).toFixed(1) }) : t('usageUnavailable') }
) : (
{t('loadingStorageInfo')}
)} {/* Persist Data */} {t('persistData')} {t('persistDataDescription')}
{/* Export Files */} {t('exportFiles')} {t('exportFilesDescription')} {/* Clear All Data */} {t('clearAllData')} {t('clearAllDataDescription')} {t('areYouSure')}

{t('clearDataWarning')}

  • {t('allProjects')}
  • {t('aiSettingsAndKeys')}
  • {t('gitCredentialsSettings')}
  • {t('userPreferences')}
  • {t('cachedData')}

{t('actionCannotBeUndone')}

{t('cancel')} {t('yesClearAllData')}
); } export default StorageSettings;