Add useFS hook

This commit is contained in:
Alex Gleason committed 2025-07-20 15:17:46 -05:00
1 parent 4837f32ade
commit 4c7c35dc0e
11 files changed
+198 -199

No files matched your search

+23 -15
View File
@@ -5,6 +5,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createHead, UnheadProvider } from '@unhead/react/client';
import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense } from 'react';
import LightningFS from '@isomorphic-git/lightning-fs';
import NostrProvider from '@/components/NostrProvider';
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
@@ -13,6 +14,7 @@ import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import { AISettingsProvider } from '@/contexts/AISettingsContext';
import { FSProvider } from '@/contexts/FSContext';
import AppRouter from './AppRouter';
const head = createHead({
@@ -43,25 +45,31 @@ const presetRelays = [
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
// Initialize LightningFS
const lightningFS = new LightningFS('shakespeare-fs');
const fs = lightningFS.promises;
export function App() {
return (
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<AISettingsProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
<FSProvider fs={fs}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<AISettingsProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
</FSProvider>
</AppProvider>
</UnheadProvider>
);
+11 -10
View File
@@ -9,7 +9,7 @@ import { Send, Bot, User, Settings, Play } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAISettings } from '@/contexts/AISettingsContext';
import { FsToolSet } from '@/lib/FsToolSet';
import { fsManager } from '@/lib/fs';
import { useFS } from '@/hooks/useFS';
const webcontainerPromise = WebContainer.boot();
@@ -26,6 +26,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
const [isLoading, setIsLoading] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const { settings, isConfigured } = useAISettings();
const { fs } = useFS();
const addMessage = (message: AIMessage) => {
setMessages((prev) => {
@@ -47,18 +48,18 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
const buildFileTree = async (dirPath: string): Promise<FileSystemTree> => {
const tree: FileSystemTree = {};
const items = await fsManager.fs.promises.readdir(dirPath);
const items = await fs.readdir(dirPath);
for (const item of items) {
const itemPath = `${dirPath}/${item}`;
const stat = await fsManager.fs.promises.stat(itemPath);
const stat = await fs.stat(itemPath);
if (stat.isDirectory()) {
tree[item] = {
directory: await buildFileTree(itemPath),
};
} else {
const content = await fsManager.fs.promises.readFile(itemPath, 'utf8');
const content = await fs.readFile(itemPath, 'utf8');
tree[item] = {
file: {
contents: content,
@@ -89,7 +90,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
// Create dist directory in project if it doesn't exist
const distPath = `/projects/${projectId}/dist`;
try {
await fsManager.fs.promises.mkdir(distPath);
await fs.mkdir(distPath);
} catch {
// Directory might already exist, that's fine
}
@@ -109,7 +110,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
if (item.isDirectory()) {
console.log(`Creating directory: ${destItemPath}`);
try {
await fsManager.fs.promises.mkdir(destItemPath);
await fs.mkdir(destItemPath);
} catch {
// Directory might already exist
}
@@ -117,7 +118,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
} else {
console.log(`Copying file: ${sourceItemPath} -> ${destItemPath}`);
const content = await webcontainer.fs.readFile(sourceItemPath);
await fsManager.fs.promises.writeFile(destItemPath, content);
await fs.writeFile(destItemPath, content);
}
} catch (itemError) {
console.warn(`Failed to copy item ${item.name}:`, itemError);
@@ -137,7 +138,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
if (item.isDirectory()) {
console.log(`Processing directory: ${item.name}`);
try {
await fsManager.fs.promises.mkdir(destPath);
await fs.mkdir(destPath);
} catch {
// Directory might already exist
}
@@ -145,7 +146,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
} else {
console.log(`Processing file: ${item.name}`);
const content = await webcontainer.fs.readFile(sourcePath);
await fsManager.fs.promises.writeFile(destPath, content);
await fs.writeFile(destPath, content);
}
} catch (itemError) {
console.warn(`Failed to process ${item.name}:`, itemError);
@@ -201,7 +202,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
});
const provider = openai(settings.model);
const toolSet = new FsToolSet(fsManager.fs.promises, `/projects/${projectId}`);
const toolSet = new FsToolSet(fs, `/projects/${projectId}`);
return generateText({
model: provider,
+8 -5
View File
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { fsManager } from '@/lib/fs';
import { ProjectsManager } from '@/lib/fs';
import { useFS } from '@/hooks/useFS';
import { ChevronRight, ChevronDown, File, Folder } from 'lucide-react';
import { cn } from '@/lib/utils';
@@ -20,17 +21,19 @@ interface FileNode {
export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProps) {
const [tree, setTree] = useState<FileNode[]>([]);
const [isLoading, setIsLoading] = useState(true);
const { fs } = useFS();
const projectsManager = new ProjectsManager(fs);
const buildFileTree = useCallback(async (projectId: string, dirPath: string): Promise<FileNode[]> => {
const items = await fsManager.listFiles(projectId, dirPath);
const items = await projectsManager.listFiles(projectId, dirPath);
const nodes: FileNode[] = [];
for (const item of items) {
const itemPath = dirPath ? `${dirPath}/${item}` : item;
const fullPath = `${fsManager['dir']}/${projectId}/${itemPath}`;
const fullPath = `${projectsManager['dir']}/${projectId}/${itemPath}`;
try {
const stat = await fsManager['fs'].promises.stat(fullPath);
const stat = await fs.stat(fullPath);
if (stat.isDirectory()) {
const children = await buildFileTree(projectId, itemPath);
@@ -59,7 +62,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
}
return a.name.localeCompare(b.name);
});
}, [projectId]);
}, [projectsManager, fs]);
const loadFileTree = useCallback(async () => {
setIsLoading(true);
+12 -9
View File
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { fsManager } from '@/lib/fs';
import { ProjectsManager } from '@/lib/fs';
import { useFS } from '@/hooks/useFS';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
@@ -49,11 +50,13 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const [isLoading, setIsLoading] = useState(false);
const [hasBuiltProject, setHasBuiltProject] = useState(false);
const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS();
const projectsManager = new ProjectsManager(fs);
const loadFileContent = useCallback(async (filePath: string) => {
setIsLoading(true);
try {
const content = await fsManager.readFile(projectId, filePath);
const content = await projectsManager.readFile(projectId, filePath);
setFileContent(content);
} catch (_error) {
console.error('Failed to load file:', _error);
@@ -61,7 +64,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
} finally {
setIsLoading(false);
}
}, [projectId]);
}, [projectId, projectsManager]);
const getContentType = (filename: string): string => {
const ext = filename.split('.').pop()?.toLowerCase();
@@ -91,13 +94,13 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const checkForBuiltProject = useCallback(async () => {
try {
const exists = await fsManager.fileExists(projectId, 'dist/index.html');
const exists = await projectsManager.fileExists(projectId, 'dist/index.html');
setHasBuiltProject(exists);
} catch (error) {
console.error('Failed to check for built project:', error);
setHasBuiltProject(false);
}
}, [projectId]);
}, [projectId, projectsManager]);
const refreshIframe = useCallback(() => {
if (iframeRef.current) {
@@ -158,7 +161,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
// SPA routing: try to serve the exact file first
try {
const file = await fsManager.readFile(projectId, 'dist' + filePath);
const file = await projectsManager.readFile(projectId, 'dist' + filePath);
console.log(`Serving file: ${filePath}`);
sendResponse({
jsonrpc: '2.0',
@@ -181,7 +184,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
// SPA fallback: serve index.html for non-file requests
try {
const indexFile = await fsManager.readFile(projectId, 'dist/index.html');
const indexFile = await projectsManager.readFile(projectId, 'dist/index.html');
console.log(`Serving index.html fallback for: ${path}`);
sendResponse({
jsonrpc: '2.0',
@@ -224,7 +227,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
id
});
}
}, [projectId, sendResponse, sendError]);
}, [projectId, projectsManager, sendResponse, sendError]);
// Setup messaging protocol for iframe communication
useEffect(() => {
@@ -265,7 +268,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
if (!selectedFile) return;
try {
await fsManager.fs.promises.writeFile(`/projects/${projectId}/${selectedFile}`, content);
await fs.writeFile(`/projects/${projectId}/${selectedFile}`, content);
setFileContent(content);
} catch (error) {
console.error('Failed to save file:', error);
+29
View File
@@ -0,0 +1,29 @@
import { createContext, useContext, type ReactNode } from 'react';
import LightningFS from '@isomorphic-git/lightning-fs';
interface FSContextType {
fs: LightningFS.PromisifiedFS;
}
const FSContext = createContext<FSContextType | undefined>(undefined);
interface FSProviderProps {
children: ReactNode;
fs: LightningFS.PromisifiedFS;
}
export function FSProvider({ children, fs }: FSProviderProps) {
return (
<FSContext.Provider value={{ fs }}>
{children}
</FSContext.Provider>
);
}
export function useFS(): FSContextType {
const context = useContext(FSContext);
if (context === undefined) {
throw new Error('useFS must be used within a FSProvider');
}
return context;
}
+5
View File
@@ -0,0 +1,5 @@
import { useFS as useInternalFS } from '@/contexts/FSContext';
export function useFS() {
return useInternalFS();
}
+44 -28
View File
@@ -1,8 +1,13 @@
import { fsManager } from './fs';
import { ProjectsManager } from './fs';
// Context-aware AI tools that automatically use the current project ID
class ContextualAITools {
private currentProjectId: string | null = null;
private projectsManager: ProjectsManager;
constructor(projectsManager: ProjectsManager) {
this.projectsManager = projectsManager;
}
setCurrentProjectId(projectId: string) {
this.currentProjectId = projectId;
@@ -18,7 +23,7 @@ class ContextualAITools {
async readFile(filePath: string): Promise<string> {
const projectId = this.getCurrentProjectId();
try {
return await fsManager.readFile(projectId, filePath);
return await this.projectsManager.readFile(projectId, filePath);
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
throw new Error(`Failed to read file "${filePath}": ${fsError.message}`);
@@ -28,7 +33,7 @@ class ContextualAITools {
async writeFile(filePath: string, content: string): Promise<{ success: boolean; message: string }> {
const projectId = this.getCurrentProjectId();
try {
await fsManager.writeFile(projectId, filePath, content);
await this.projectsManager.writeFile(projectId, filePath, content);
return { success: true, message: `File ${filePath} written successfully` };
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
@@ -39,7 +44,7 @@ class ContextualAITools {
async deleteFile(filePath: string): Promise<{ success: boolean; message: string }> {
const projectId = this.getCurrentProjectId();
try {
await fsManager.deleteFile(projectId, filePath);
await this.projectsManager.deleteFile(projectId, filePath);
return { success: true, message: `File ${filePath} deleted successfully` };
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
@@ -50,7 +55,7 @@ class ContextualAITools {
async listFiles(dirPath: string = ''): Promise<string[]> {
const projectId = this.getCurrentProjectId();
try {
return await fsManager.listFiles(projectId, dirPath);
return await this.projectsManager.listFiles(projectId, dirPath);
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
throw new Error(`Failed to list files in "${dirPath}": ${fsError.message}`);
@@ -60,7 +65,7 @@ class ContextualAITools {
async fileExists(filePath: string): Promise<boolean> {
const projectId = this.getCurrentProjectId();
try {
return await fsManager.fileExists(projectId, filePath);
return await this.projectsManager.fileExists(projectId, filePath);
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
throw new Error(`Failed to check if file exists "${filePath}": ${fsError.message}`);
@@ -81,15 +86,15 @@ class ContextualAITools {
const projectId = this.getCurrentProjectId();
const structure: Record<string, unknown> = {};
async function buildStructure(currentPath: string, obj: Record<string, unknown>) {
const items = await fsManager.listFiles(projectId, currentPath);
const buildStructure = async (currentPath: string, obj: Record<string, unknown>) => {
const items = await this.projectsManager.listFiles(projectId, currentPath);
for (const item of items) {
const itemPath = currentPath ? `${currentPath}/${item}` : item;
const fullPath = `${fsManager['dir']}/${projectId}/${itemPath}`;
const fullPath = `${this.projectsManager['dir']}/${projectId}/${itemPath}`;
try {
const stat = await fsManager['fs'].promises.stat(fullPath);
const stat = await this.projectsManager['fs'].stat(fullPath);
if (stat.isDirectory()) {
const newObj: Record<string, unknown> = {};
obj[item] = newObj;
@@ -101,7 +106,7 @@ class ContextualAITools {
// Skip inaccessible items
}
}
}
};
await buildStructure('', structure);
return structure;
@@ -111,19 +116,19 @@ class ContextualAITools {
const projectId = this.getCurrentProjectId();
const results: Array<{path: string, content: string}> = [];
async function searchDirectory(dirPath: string) {
const items = await fsManager.listFiles(projectId, dirPath);
const searchDirectory = async (dirPath: string) => {
const items = await this.projectsManager.listFiles(projectId, dirPath);
for (const item of items) {
const itemPath = dirPath ? `${dirPath}/${item}` : item;
const fullPath = `${fsManager['dir']}/${projectId}/${itemPath}`;
const fullPath = `${this.projectsManager['dir']}/${projectId}/${itemPath}`;
try {
const stat = await fsManager['fs'].promises.stat(fullPath);
const stat = await this.projectsManager['fs'].stat(fullPath);
if (stat.isDirectory()) {
await searchDirectory(itemPath);
} else {
const content = await fsManager.readFile(projectId, itemPath);
const content = await this.projectsManager.readFile(projectId, itemPath);
if (content.toLowerCase().includes(query.toLowerCase())) {
results.push({ path: itemPath, content });
}
@@ -132,15 +137,17 @@ class ContextualAITools {
// Skip inaccessible files
}
}
}
};
await searchDirectory('');
return results;
}
}
// Create a singleton instance
export const contextualAITools = new ContextualAITools();
// Factory function to create ContextualAITools with ProjectsManager
export function createContextualAITools(projectsManager: ProjectsManager): ContextualAITools {
return new ContextualAITools(projectsManager);
}
// Backward compatibility: export the old interface for existing code
interface LegacyOperation {
@@ -152,40 +159,46 @@ interface LegacyOperation {
}
export class AITools {
private contextualAITools: ContextualAITools;
constructor(projectsManager: ProjectsManager) {
this.contextualAITools = new ContextualAITools(projectsManager);
}
async executeOperation(operation: LegacyOperation): Promise<unknown> {
try {
switch (operation.type) {
case 'read':
if (!operation.filePath) throw new Error('filePath is required');
return await contextualAITools.readFile(operation.filePath);
return await this.contextualAITools.readFile(operation.filePath);
case 'write':
if (!operation.filePath) throw new Error('filePath is required');
if (!operation.content) {
throw new Error('Content is required for write operations');
}
return await contextualAITools.writeFile(operation.filePath, operation.content);
return await this.contextualAITools.writeFile(operation.filePath, operation.content);
case 'delete':
if (!operation.filePath) throw new Error('filePath is required');
return await contextualAITools.deleteFile(operation.filePath);
return await this.contextualAITools.deleteFile(operation.filePath);
case 'list':
return await contextualAITools.listFiles(operation.filePath);
return await this.contextualAITools.listFiles(operation.filePath);
case 'exists':
if (!operation.filePath) throw new Error('filePath is required');
return await contextualAITools.fileExists(operation.filePath);
return await this.contextualAITools.fileExists(operation.filePath);
case 'build':
return await contextualAITools.buildProject();
return await this.contextualAITools.buildProject();
case 'getProjectStructure':
return await contextualAITools.getProjectStructure();
return await this.contextualAITools.getProjectStructure();
case 'searchFiles':
if (!operation.query) throw new Error('query is required');
return await contextualAITools.searchFiles(operation.query);
return await this.contextualAITools.searchFiles(operation.query);
default:
throw new Error(`Unknown operation type: ${operation.type}`);
@@ -196,4 +209,7 @@ export class AITools {
}
}
export const aiTools = new AITools();
// Factory function to create AITools with ProjectsManager
export function createAITools(projectsManager: ProjectsManager): AITools {
return new AITools(projectsManager);
}
+29 -109
View File
@@ -19,18 +19,18 @@ export interface Project {
lastModified: Date;
}
export class FileSystemManager {
fs: LightningFS;
export class ProjectsManager {
fs: LightningFS.PromisifiedFS;
dir: string;
constructor() {
this.fs = new LightningFS('shakespeare-fs');
constructor(fs: LightningFS.PromisifiedFS) {
this.fs = fs;
this.dir = '/projects';
}
async init() {
try {
await this.fs.promises.mkdir(this.dir);
await this.fs.mkdir(this.dir);
} catch {
// Directory might already exist
}
@@ -40,7 +40,7 @@ export class FileSystemManager {
const id = this.generateProjectId(name);
const projectPath = `${this.dir}/${id}`;
await this.fs.promises.mkdir(projectPath);
await this.fs.mkdir(projectPath);
const project: Project = {
id,
@@ -51,7 +51,7 @@ export class FileSystemManager {
};
// Save project metadata
await this.fs.promises.writeFile(
await this.fs.writeFile(
`${projectPath}/.project.json`,
JSON.stringify(project, null, 2)
);
@@ -63,99 +63,21 @@ export class FileSystemManager {
}
async cloneTemplate(projectPath: string) {
try {
await git.clone({
fs: this.fs,
http,
dir: projectPath,
url: GIT_TEMPLATE_URL,
singleBranch: true,
depth: 1,
});
} catch {
// Create basic structure if clone fails
await this.createBasicStructure(projectPath);
}
}
async createBasicStructure(projectPath: string) {
const files = {
'package.json': JSON.stringify({
name: 'shakespeare-project',
version: '0.1.0',
type: 'module',
scripts: {
dev: 'vite',
build: 'vite build',
preview: 'vite preview'
},
dependencies: {
react: '^18.2.0',
'react-dom': '^18.2.0'
},
devDependencies: {
'@types/react': '^18.2.0',
'@types/react-dom': '^18.2.0',
'@vitejs/plugin-react': '^4.0.0',
vite: '^4.4.0'
}
}, null, 2),
'index.html': `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Shakespeare Project</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>`,
'src/main.jsx': `import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)`,
'src/App.jsx': `import React from 'react'
function App() {
return (
<div className="App">
<h1>Welcome to your Shakespeare project!</h1>
<p>This is a basic React app template.</p>
</div>
)
}
export default App`,
'vite.config.js': `import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})`
};
for (const [filename, content] of Object.entries(files)) {
const filePath = `${projectPath}/${filename}`;
const dir = filePath.split('/').slice(0, -1).join('/');
try {
await this.fs.promises.mkdir(dir);
} catch {
// Directory might already exist
}
await this.fs.promises.writeFile(filePath, content);
}
// Create a LightningFS instance for git operations
const gitFS = new LightningFS('shakespeare-fs');
await git.clone({
fs: gitFS,
http,
dir: projectPath,
url: GIT_TEMPLATE_URL,
singleBranch: true,
depth: 1,
});
}
async getProjects(): Promise<Project[]> {
try {
const projectDirs = await this.fs.promises.readdir(this.dir);
const projectDirs = await this.fs.readdir(this.dir);
const projects: Project[] = [];
for (const dir of projectDirs) {
@@ -163,7 +85,7 @@ export default defineConfig({
const projectFile = `${projectPath}/.project.json`;
try {
const projectData = await this.fs.promises.readFile(projectFile, 'utf8');
const projectData = await this.fs.readFile(projectFile, 'utf8');
const project = JSON.parse(projectData);
projects.push({
...project,
@@ -184,7 +106,7 @@ export default defineConfig({
async getProject(id: string): Promise<Project | null> {
try {
const projectFile = `${this.dir}/${id}/.project.json`;
const projectData = await this.fs.promises.readFile(projectFile, 'utf8');
const projectData = await this.fs.readFile(projectFile, 'utf8');
const project = JSON.parse(projectData);
return {
...project,
@@ -199,9 +121,9 @@ export default defineConfig({
async readFile(projectId: string, filePath: string): Promise<string> {
const fullPath = `${this.dir}/${projectId}/${filePath}`;
try {
const stat = await this.fs.promises.stat(fullPath);
const stat = await this.fs.stat(fullPath);
if (stat.isFile()) {
return await this.fs.promises.readFile(fullPath, 'utf8');
return await this.fs.readFile(fullPath, 'utf8');
} else {
throw new Error(`Path is not a file: ${filePath}`);
}
@@ -217,8 +139,8 @@ export default defineConfig({
async writeFile(projectId: string, filePath: string, content: string): Promise<void> {
const fullPath = `${this.dir}/${projectId}/${filePath}`;
const dir = fullPath.split('/').slice(0, -1).join('/');
await this.fs.promises.mkdir(dir);
await this.fs.promises.writeFile(fullPath, content);
await this.fs.mkdir(dir);
await this.fs.writeFile(fullPath, content);
// Update last modified
await this.updateProjectLastModified(projectId);
@@ -226,14 +148,14 @@ export default defineConfig({
async deleteFile(projectId: string, filePath: string): Promise<void> {
const fullPath = `${this.dir}/${projectId}/${filePath}`;
await this.fs.promises.unlink(fullPath);
await this.fs.unlink(fullPath);
await this.updateProjectLastModified(projectId);
}
async listFiles(projectId: string, dirPath: string = ''): Promise<string[]> {
const fullPath = `${this.dir}/${projectId}/${dirPath}`;
try {
return await this.fs.promises.readdir(fullPath);
return await this.fs.readdir(fullPath);
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
if (fsError.code === 'ENOENT') {
@@ -246,7 +168,7 @@ export default defineConfig({
async fileExists(projectId: string, filePath: string): Promise<boolean> {
try {
const fullPath = `${this.dir}/${projectId}/${filePath}`;
await this.fs.promises.stat(fullPath);
await this.fs.stat(fullPath);
return true;
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
@@ -270,14 +192,12 @@ export default defineConfig({
private async updateProjectLastModified(projectId: string): Promise<void> {
try {
const projectFile = `${this.dir}/${projectId}/.project.json`;
const projectData = await this.fs.promises.readFile(projectFile, 'utf8');
const projectData = await this.fs.readFile(projectFile, 'utf8');
const project = JSON.parse(projectData);
project.lastModified = new Date().toISOString();
await this.fs.promises.writeFile(projectFile, JSON.stringify(project, null, 2));
await this.fs.writeFile(projectFile, JSON.stringify(project, null, 2));
} catch {
// Ignore errors updating last modified
}
}
}
export const fsManager = new FileSystemManager();
+6 -3
View File
@@ -1,6 +1,7 @@
import { useState, useEffect, useCallback } from 'react';
import { useParams } from 'react-router-dom';
import { fsManager, type Project } from '@/lib/fs';
import { ProjectsManager, type Project } from '@/lib/fs';
import { useFS } from '@/hooks/useFS';
import { ChatPane } from '@/components/Shakespeare/ChatPane';
import { PreviewPane } from '@/components/Shakespeare/PreviewPane';
import { Button } from '@/components/ui/button';
@@ -13,20 +14,22 @@ export function ProjectView() {
const [project, setProject] = useState<Project | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [activeTab, setActiveTab] = useState<'preview' | 'code'>('preview');
const { fs } = useFS();
const projectsManager = new ProjectsManager(fs);
const navigate = useNavigate();
const loadProject = useCallback(async () => {
if (!projectId) return;
try {
const projectData = await fsManager.getProject(projectId);
const projectData = await projectsManager.getProject(projectId);
setProject(projectData);
} catch (_error) {
console.error('Failed to load project:', _error);
} finally {
setIsLoading(false);
}
}, [projectId]);
}, [projectId, projectsManager]);
useEffect(() => {
loadProject();
+14 -11
View File
@@ -1,6 +1,7 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { fsManager, type Project } from '@/lib/fs';
import { ProjectsManager, type Project } from '@/lib/fs';
import { useFS } from '@/hooks/useFS';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
@@ -13,29 +14,31 @@ export function ShakespeareHome() {
const [isLoading, setIsLoading] = useState(true);
const [isCreating, setIsCreating] = useState(false);
const navigate = useNavigate();
const { fs } = useFS();
const projectsManager = new ProjectsManager(fs);
useEffect(() => {
loadProjects();
}, []);
const loadProjects = async () => {
const loadProjects = useCallback(async () => {
try {
await fsManager.init();
const projectList = await fsManager.getProjects();
await projectsManager.init();
const projectList = await projectsManager.getProjects();
setProjects(projectList);
} catch (error) {
console.error('Failed to load projects:', error);
} finally {
setIsLoading(false);
}
};
}, [projectsManager]);
useEffect(() => {
loadProjects();
}, [loadProjects]);
const handleCreateProject = async () => {
if (!prompt.trim()) return;
setIsCreating(true);
try {
const project = await fsManager.createProject(prompt.trim());
const project = await projectsManager.createProject(prompt.trim());
navigate(`/project/${project.id}`);
} catch (error) {
console.error('Failed to create project:', error);
+17 -9
View File
@@ -1,10 +1,12 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createHead, UnheadProvider } from '@unhead/react/client';
import { BrowserRouter } from 'react-router-dom';
import LightningFS from '@isomorphic-git/lightning-fs';
import { NostrLoginProvider } from '@nostrify/react/login';
import NostrProvider from '@/components/NostrProvider';
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import { FSProvider } from '@/contexts/FSContext';
interface TestAppProps {
children: React.ReactNode;
@@ -25,18 +27,24 @@ export function TestApp({ children }: TestAppProps) {
relayUrl: 'wss://relay.nostr.band',
};
// Initialize LightningFS for testing
const lightningFS = new LightningFS('test-fs');
const fs = lightningFS.promises;
return (
<UnheadProvider head={head}>
<AppProvider storageKey='test-app-config' defaultConfig={defaultConfig}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='test-login'>
<NostrProvider>
<BrowserRouter>
{children}
</BrowserRouter>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
<FSProvider fs={fs}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='test-login'>
<NostrProvider>
<BrowserRouter>
{children}
</BrowserRouter>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
</FSProvider>
</AppProvider>
</UnheadProvider>
);