diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index c1a7d610..256f788d 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -7,6 +7,7 @@ import Clone from "./pages/Clone"; import Settings from "./pages/Settings"; import AISettings from "./pages/AISettings"; import GitSettings from "./pages/GitSettings"; +import DataSettings from "./pages/DataSettings"; import { NIP19Page } from "./pages/NIP19Page"; import NotFound from "./pages/NotFound"; import { ProjectView } from "./pages/ProjectView"; @@ -24,6 +25,7 @@ export function AppRouter() { } /> } /> } /> + } /> } /> {/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */} diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index a58f5c22..d7904958 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,6 +1,6 @@ import React, { useState, memo } from 'react'; import { useNavigate } from 'react-router-dom'; -import { Plus, Folder, Download, GitBranch, MoreVertical, Settings, Loader2 } from 'lucide-react'; +import { Plus, Folder, GitBranch, MoreVertical, Settings, Loader2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; @@ -9,11 +9,8 @@ import { StarButton } from '@/components/StarButton'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useLocalStorage } from '@/hooks/useLocalStorage'; -import { useToast } from '@/hooks/useToast'; -import { useFS } from '@/hooks/useFS'; import type { Project } from '@/lib/ProjectsManager'; import { cn } from '@/lib/utils'; -import JSZip from 'jszip'; interface ProjectItemProps { project: Project; @@ -88,12 +85,9 @@ export function ProjectSidebar({ }: ProjectSidebarProps) { const [projects, setProjects] = useState([]); const [isLoading, setIsLoading] = useState(true); - const [isExporting, setIsExporting] = useState(false); const [favorites] = useLocalStorage('project-favorites', []); const projectsManager = useProjectsManager(); const navigate = useNavigate(); - const { toast } = useToast(); - const { fs } = useFS(); // Load projects on mount React.useEffect(() => { @@ -119,82 +113,6 @@ export function ProjectSidebar({ const isFavorite = (projectId: string) => favorites.includes(projectId); - const exportFilesAsZip = async (projectName: string) => { - 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 = `${projectName}-${dateStr}.zip`; - - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - URL.revokeObjectURL(url); - }; - - const handleExportFiles = async () => { - setIsExporting(true); - try { - const projectName = selectedProject?.name || 'shakespeare'; - await exportFilesAsZip(projectName); - - toast({ - title: "Files exported successfully", - description: "Your project files have been downloaded as a zip file.", - }); - } catch (error) { - console.error('Failed to export files:', error); - toast({ - title: "Failed to export files", - description: error instanceof Error ? error.message : "An unexpected error occurred", - variant: "destructive", - }); - } finally { - setIsExporting(false); - } - }; - // Sort projects: favorites first, then by lastModified (newest first) const sortedProjects = projects.sort((a, b) => { const aIsFavorite = isFavorite(a.id); @@ -235,15 +153,6 @@ export function ProjectSidebar({ Import Repository - - - {isExporting ? 'Exporting...' : 'Export Files'} - - navigate('/settings')} className="flex items-center gap-2 w-full" diff --git a/src/components/SettingsLayout.tsx b/src/components/SettingsLayout.tsx index 90f0a1c7..6cf2adec 100644 --- a/src/components/SettingsLayout.tsx +++ b/src/components/SettingsLayout.tsx @@ -1,7 +1,7 @@ import { useState, useEffect } from 'react'; import { useNavigate, useLocation, Outlet } from 'react-router-dom'; import { Button } from '@/components/ui/button'; -import { Menu, Columns2, Settings as SettingsIcon, Bot, GitBranch } from 'lucide-react'; +import { Menu, Columns2, Settings as SettingsIcon, Bot, GitBranch, Database } from 'lucide-react'; import { ProjectSidebar } from '@/components/ProjectSidebar'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useIsMobile } from '@/hooks/useIsMobile'; @@ -31,6 +31,13 @@ const settingsItems: SettingsItem[] = [ icon: GitBranch, href: '/settings/git', }, + { + id: 'data', + title: 'Data', + description: 'Export files and manage local data', + icon: Database, + href: '/settings/data', + }, ]; export function SettingsLayout() { diff --git a/src/pages/DataSettings.test.tsx b/src/pages/DataSettings.test.tsx new file mode 100644 index 00000000..be462867 --- /dev/null +++ b/src/pages/DataSettings.test.tsx @@ -0,0 +1,46 @@ +import { describe, it, expect } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { TestApp } from '@/test/TestApp'; +import DataSettings from './DataSettings'; + +describe('DataSettings', () => { + it('renders the data settings page correctly', () => { + render( + + + + ); + + // Check for main heading + expect(screen.getByText('Data')).toBeInTheDocument(); + + // Check for description + expect(screen.getByText('Export your projects or clear all local data from this browser.')).toBeInTheDocument(); + + // Check for Export Files section + expect(screen.getByText('Export Files')).toBeInTheDocument(); + expect(screen.getByText('Export All Files')).toBeInTheDocument(); + + // Check for Clear All Data section + expect(screen.getAllByText('Clear All Data')).toHaveLength(2); // Title and button + expect(screen.getByRole('button', { name: /clear all data/i })).toBeInTheDocument(); + }); + + it('shows export and clear buttons', () => { + render( + + + + ); + + // Export button should be visible + const exportButton = screen.getByRole('button', { name: /export all files/i }); + expect(exportButton).toBeInTheDocument(); + expect(exportButton).not.toBeDisabled(); + + // Clear data button should be visible + const clearButton = screen.getByRole('button', { name: /clear all data/i }); + expect(clearButton).toBeInTheDocument(); + expect(clearButton).not.toBeDisabled(); + }); +}); \ No newline at end of file diff --git a/src/pages/DataSettings.tsx b/src/pages/DataSettings.tsx new file mode 100644 index 00000000..add3880f --- /dev/null +++ b/src/pages/DataSettings.tsx @@ -0,0 +1,257 @@ +import { useState } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { Download, Trash2, AlertTriangle, Loader2, Database } 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 { useToast } from '@/hooks/useToast'; +import { useFS } from '@/hooks/useFS'; +import JSZip from 'jszip'; + +export function DataSettings() { + const [isExporting, setIsExporting] = useState(false); + const [isClearing, setIsClearing] = useState(false); + const { toast } = useToast(); + const { fs } = useFS(); + const navigate = useNavigate(); + + 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: "Files exported successfully", + description: "Your project files have been downloaded as a zip file.", + }); + } catch (error) { + console.error('Failed to export files:', error); + toast({ + title: "Failed to export files", + description: error instanceof Error ? error.message : "An unexpected error occurred", + 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: "Data cleared successfully", + description: "All local data has been removed. Redirecting to homepage...", + }); + + // Small delay to show the toast, then redirect + setTimeout(() => { + navigate('/'); + }, 1500); + } catch (error) { + console.error('Failed to clear data:', error); + toast({ + title: "Failed to clear data", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); + } finally { + setIsClearing(false); + } + }; + + return ( +
+
+

+ + Data +

+

+ Export your projects or clear all local data from this browser. +

+
+ +
+ {/* Export Files */} + + + + + Export Files + + + Download all your projects and files as a ZIP archive. This includes all project files, settings, and data stored locally. + + + + + + + + {/* Clear All Data */} + + + + + Clear All Data + + + Permanently delete all local data including projects, settings, and cached information. This action cannot be undone. + + + + + + + + + + + + Are you absolutely sure? + + +

+ This action will permanently delete all local data from this browser, including: +

+
    +
  • All projects and their files
  • +
  • AI settings and API keys
  • +
  • Git credentials and settings
  • +
  • User preferences and themes
  • +
  • Cached data and session information
  • +
+

+ This action cannot be undone. Consider exporting your files first. +

+
+
+ + Cancel + + Yes, clear all data + + +
+
+
+
+
+
+ ); +} + +export default DataSettings; \ No newline at end of file diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx index e0ffe48c..61477c7f 100644 --- a/src/pages/Settings.tsx +++ b/src/pages/Settings.tsx @@ -1,5 +1,5 @@ import { useNavigate } from 'react-router-dom'; -import { Bot, GitBranch } from 'lucide-react'; +import { Bot, GitBranch, Database } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; interface SettingsItem { @@ -25,6 +25,13 @@ const settingsItems: SettingsItem[] = [ icon: GitBranch, href: '/settings/git', }, + { + id: 'data', + title: 'Data', + description: 'Export files and manage local data', + icon: Database, + href: '/settings/data', + }, ]; export function Settings() {