import { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft } 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 { useToast } from '@/hooks/useToast'; import { useFS } from '@/hooks/useFS'; import { useIsMobile } from '@/hooks/useIsMobile'; 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 DataSettings() { const { t } = useTranslation(); const [isExporting, setIsExporting] = useState(false); const [isClearing, setIsClearing] = useState(false); const [storageInfo, setStorageInfo] = useState(null); const [storageError, setStorageError] = useState(null); const { toast } = useToast(); const { fs } = useFS(); const navigate = useNavigate(); const isMobile = useIsMobile(); // 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 useEffect(() => { const loadStorageInfo = async () => { try { // Check if StorageManager API is available if (!('storage' in navigator)) { setStorageError('StorageManager API is not available in this browser'); return; } // Get storage estimate const estimate = await navigator.storage.estimate(); // Extract usage details safely const usageDetails: StorageUsageDetails | undefined = (estimate as StorageEstimate & { usageDetails?: StorageUsageDetails }).usageDetails; setStorageInfo({ quota: estimate.quota || 0, usage: estimate.usage || 0, usageDetails, }); } 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 handleClearAllData = async () => { setIsClearing(true); try { // Clear localStorage localStorage.clear(); // 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('dataSettings')}

{t('dataSettingsDescriptionLong')}

)} {!isMobile && (

{t('dataSettings')}

{t('dataSettingsDescriptionLong')}

)}
{/* 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')}
)} {/* 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 DataSettings;