Add Data page to settings

This commit is contained in:
Alex Gleason committed 2025-09-13 15:59:29 -05:00
1 parent bb47f36a35
commit 2c7fd7d79b
6 files changed
+322 -94

No files matched your search

+2
View File
@@ -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() {
<Route index element={<Settings />} />
<Route path="ai" element={<AISettings />} />
<Route path="git" element={<GitSettings />} />
<Route path="data" element={<DataSettings />} />
</Route>
<Route path="/project/:projectId" element={<ProjectView />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
+1 -92
View File
@@ -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<Project[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isExporting, setIsExporting] = useState(false);
const [favorites] = useLocalStorage<string[]>('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({
<GitBranch className="h-4 w-4" />
Import Repository
</DropdownMenuItem>
<DropdownMenuItem
onClick={handleExportFiles}
disabled={isExporting}
className="flex items-center gap-2 w-full"
>
<Download className="h-4 w-4" />
{isExporting ? 'Exporting...' : 'Export Files'}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => navigate('/settings')}
className="flex items-center gap-2 w-full"
+8 -1
View File
@@ -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() {
+46
View File
@@ -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(
<TestApp>
<DataSettings />
</TestApp>
);
// 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(
<TestApp>
<DataSettings />
</TestApp>
);
// 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();
});
});
+257
View File
@@ -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<void>((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 (
<div className="p-6 space-y-6">
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Database className="h-6 w-6 text-primary" />
Data
</h1>
<p className="text-muted-foreground">
Export your projects or clear all local data from this browser.
</p>
</div>
<div className="space-y-4">
{/* Export Files */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Download className="h-5 w-5" />
Export Files
</CardTitle>
<CardDescription>
Download all your projects and files as a ZIP archive. This includes all project files, settings, and data stored locally.
</CardDescription>
</CardHeader>
<CardContent>
<Button
onClick={handleExportFiles}
disabled={isExporting}
className="w-full sm:w-auto"
>
{isExporting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Exporting...
</>
) : (
<>
<Download className="h-4 w-4 mr-2" />
Export All Files
</>
)}
</Button>
</CardContent>
</Card>
{/* Clear All Data */}
<Card className="border-destructive/20">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-destructive">
<Trash2 className="h-5 w-5" />
Clear All Data
</CardTitle>
<CardDescription>
Permanently delete all local data including projects, settings, and cached information. This action cannot be undone.
</CardDescription>
</CardHeader>
<CardContent>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="destructive"
disabled={isClearing}
className="w-full sm:w-auto"
>
{isClearing ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Clearing...
</>
) : (
<>
<Trash2 className="h-4 w-4 mr-2" />
Clear All Data
</>
)}
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
Are you absolutely sure?
</AlertDialogTitle>
<AlertDialogDescription className="space-y-2">
<p>
This action will permanently delete all local data from this browser, including:
</p>
<ul className="list-disc list-inside space-y-1 text-sm">
<li>All projects and their files</li>
<li>AI settings and API keys</li>
<li>Git credentials and settings</li>
<li>User preferences and themes</li>
<li>Cached data and session information</li>
</ul>
<p className="font-medium text-destructive">
This action cannot be undone. Consider exporting your files first.
</p>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleClearAllData}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Yes, clear all data
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</CardContent>
</Card>
</div>
</div>
);
}
export default DataSettings;
+8 -1
View File
@@ -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() {