-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathApp.tsx
More file actions
462 lines (415 loc) · 16.7 KB
/
App.tsx
File metadata and controls
462 lines (415 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/**
* App.tsx - Main Application Component
*
* This component now uses AppContext for centralized state management.
* Most state and logic has been moved to AppContext to reduce prop drilling.
*
* What remains here:
* - Modal management (useModalManager)
* - UI-specific callbacks (handleInspectEdit, handleModelChange)
* - First-visit credits modal logic
* - URL project loading
*/
import React, { useState, useCallback, useRef, useEffect } from 'react';
import { CREDITS_MODAL_DELAY_MS, STORAGE_KEYS } from '@/constants';
import { ControlPanel, ControlPanelRef } from './components/ControlPanel';
import { PreviewPanel } from './components/PreviewPanel';
import { loadProjectFromUrl } from './utils/shareUrl';
import { SyncConfirmationDialog } from './components/SyncConfirmationDialog';
import { DiffModal } from './components/DiffModal';
import { useModalManager } from './hooks/useModalManager';
import { usePanelResize } from './hooks/usePanelResize';
import { useAppContext } from './contexts/AppContext';
import { useUI } from './contexts/UIContext';
import { useAutoCommit } from './hooks/useAutoCommit';
import { useKeyboardShortcuts } from './hooks/useKeyboardShortcuts';
import { githubApi } from './services/api/github';
import { settingsApi } from './services/api/settings';
import { activityLogger } from './services/activityLogger';
import { InspectedElement, EditScope } from './components/PreviewPanel/ComponentInspector';
import { getContextManager } from './services/conversationContext';
import { ToastProvider } from './components/Toast';
import { ContextMenuProvider } from './components/ContextMenu';
import { IDEFrame } from './components/IDEFrame';
import { PromptConfirmationProvider } from './contexts/PromptConfirmationContext';
import { PromptConfirmationModal } from './components/PromptConfirmationModal';
import type { SettingsCategory } from './components/MegaSettingsModal/types';
// Lazy-loaded modals for better initial bundle size (~80KB savings)
import {
LazyAISettingsModal,
LazyMegaSettingsModal,
LazyCreditsModal,
LazyCodeMapModal,
LazyTailwindPalette,
LazyComponentTree,
LazyDeployModal,
LazyShareModal,
LazyHistoryPanel,
LazyProjectHealthModal,
LazyProjectManager,
LazyPromptHistoryModal,
LazySnippetsPanel,
} from './components/LazyModals';
// Re-export types for backwards compatibility
export type { FileSystem } from './types';
export default function App() {
// Get state from contexts
const ctx = useAppContext();
const ui = useUI();
// Centralized modal state management
const modals = useModalManager();
const [megaSettingsInitialCategory, setMegaSettingsInitialCategory] = useState<SettingsCategory>('ai-providers');
// Global keyboard shortcuts (Ctrl+Z, Ctrl+Shift+Z, Ctrl+S)
useKeyboardShortcuts();
// Resizable panel divider (drag to resize, double-click to reset)
const { panelWidth, isDragging, dividerProps } = usePanelResize();
// Preview error tracking for auto-commit
const [previewHasErrors, setPreviewHasErrors] = useState(false);
// Runner status for Start Fresh modal
const [hasRunningServer, setHasRunningServer] = useState(false);
// Prompt History state
const [showPromptHistory, setShowPromptHistory] = useState(false);
const [historyPrompt, setHistoryPrompt] = useState<string | undefined>();
// GitHub Backup state
const [backupEnabled, setBackupEnabled] = useState(false);
const [backupBranchName, setBackupBranchName] = useState('backup/auto');
// Load backup settings on mount
useEffect(() => {
activityLogger.info('system', 'FluidFlow started');
settingsApi.getGitHubBackup().then((settings) => {
setBackupEnabled(settings.enabled);
setBackupBranchName(settings.branchName || 'backup/auto');
if (settings.enabled) {
activityLogger.info('backup', 'GitHub backup enabled', settings.branchName || 'backup/auto');
}
}).catch(console.error);
}, []);
// Backup push callback
const handleBackupPush = useCallback(async () => {
if (!ctx.currentProject?.id) return;
try {
// Get token from settings
const { token } = await settingsApi.getBackupToken();
if (!token) {
activityLogger.warn('backup', 'No GitHub token configured', 'Skipping backup push');
return;
}
activityLogger.info('backup', `Pushing to ${backupBranchName}`, ctx.currentProject.name);
// Push to backup branch
const result = await githubApi.backupPush(ctx.currentProject.id, {
branch: backupBranchName,
token,
includeContext: false,
});
// Update backup status
if (result.success) {
await settingsApi.updateBackupStatus(result.timestamp, result.commit);
activityLogger.success('backup', 'GitHub backup complete', result.commit?.substring(0, 7));
}
} catch (err) {
const errorMsg = err instanceof Error ? err.message : 'Unknown error';
activityLogger.error('backup', 'GitHub backup failed', errorMsg);
throw err; // Re-throw so useAutoCommit can track status
}
}, [ctx.currentProject?.id, ctx.currentProject?.name, backupBranchName]);
// Auto-commit feature: commits when preview is error-free
const { isAutoCommitting, lastBackupStatus: _lastBackupStatus } = useAutoCommit({
enabled: ui.autoCommitEnabled,
files: ctx.files,
hasUncommittedChanges: ctx.hasUncommittedChanges,
previewHasErrors,
gitInitialized: ctx.gitStatus?.initialized ?? false,
localChanges: ctx.localChanges,
onCommit: ctx.commit,
backupEnabled,
onBackupPush: handleBackupPush,
});
// Reset key for ControlPanel re-mount
const [resetKey, setResetKey] = useState(0);
// ControlPanel ref for inspect edit handler
const controlPanelRef = useRef<ControlPanelRef>(null);
// Track active file in ref for stale closure handling
const activeFileRef = useRef(ctx.activeFile);
useEffect(() => {
activeFileRef.current = ctx.activeFile;
}, [ctx.activeFile]);
// Track selected model in ref for stale closure handling
const selectedModelRef = useRef(ui.selectedModel);
useEffect(() => {
selectedModelRef.current = ui.selectedModel;
}, [ui.selectedModel]);
// Handler for inspect edit from PreviewPanel
const handleInspectEdit = useCallback(async (prompt: string, element: InspectedElement, scope: EditScope) => {
// Ensure left panel is visible before sending inspect edit
// Panel is always mounted (CSS hidden), so ref is always available
if (!ui.leftPanelVisible) {
ui.setLeftPanelVisible(true);
}
if (controlPanelRef.current) {
await controlPanelRef.current.handleInspectEdit(prompt, element, scope);
}
}, [ui]);
// Handle model/provider change - also clears conversation context
const handleModelChange = useCallback((newModel: string) => {
if (newModel !== selectedModelRef.current) {
ui.setSelectedModel(newModel);
// Clear the main chat context when model changes
const contextManager = getContextManager();
contextManager.clearContext('main-chat');
console.log('[App] Model changed, context cleared:', newModel);
}
}, [ui]);
// Load project from URL if present (for shared projects)
useEffect(() => {
const urlProject = loadProjectFromUrl();
if (urlProject && Object.keys(urlProject).length > 0) {
ctx.setFiles(urlProject);
// Select first src file
const firstSrc = Object.keys(urlProject).find(f => f.startsWith('src/'));
if (firstSrc) ctx.setActiveFile(firstSrc);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Check if first visit and show credits
useEffect(() => {
const hasVisited = localStorage.getItem(STORAGE_KEYS.HAS_VISITED);
if (!hasVisited) {
localStorage.setItem(STORAGE_KEYS.HAS_VISITED, 'true');
// FIX-16: Store timeout for cleanup
const creditsTimeout = setTimeout(() => {
modals.open('credits');
}, CREDITS_MODAL_DELAY_MS);
return () => clearTimeout(creditsTimeout);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Enhanced resetApp that also resets resetKey
const handleResetApp = useCallback(() => {
ctx.resetApp();
setResetKey(prev => prev + 1);
}, [ctx]);
return (
<PromptConfirmationProvider>
<ContextMenuProvider>
<ToastProvider>
<div
className="fixed inset-0 flex flex-col overflow-hidden max-h-screen"
style={{
backgroundColor: 'var(--theme-background)',
color: 'var(--theme-text-primary)'
}}
>
{/* IDE Frame wrapper */}
<div className="flex-1 min-h-0 z-10 relative">
<IDEFrame
onChatClick={ui.toggleLeftPanel}
onSettingsClick={() => modals.open('megaSettings')}
onInfoClick={() => modals.open('credits')}
onOpenGitTab={() => ui.setActiveTab('git')}
onOpenProjectsTab={() => ui.setActiveTab('projects')}
onOpenHistoryPanel={() => modals.toggle('history')}
onOpenCredits={() => {
setMegaSettingsInitialCategory('about');
modals.open('megaSettings');
}}
onOpenHealthCheck={() => modals.open('projectHealth')}
onOpenAIUsage={() => {
setMegaSettingsInitialCategory('ai-usage');
modals.open('megaSettings');
}}
showActivityBar={true}
showTitleBar={true}
showStatusBar={true}
isAutoCommitting={isAutoCommitting}
>
<div className="flex flex-col md:flex-row h-full w-full overflow-hidden" data-panel-container>
{/* ControlPanel - CSS-based hiding to preserve state during hide/show */}
<div
className={ui.leftPanelVisible ? 'shrink-0' : 'hidden'}
style={{ width: ui.leftPanelVisible ? panelWidth : 0 }}
>
<ControlPanel
ref={controlPanelRef}
key={resetKey}
// App.tsx callbacks
resetApp={handleResetApp}
onModelChange={handleModelChange}
// Modal open handlers
onOpenAISettings={() => modals.open('aiSettings')}
onOpenMegaSettings={() => modals.open('megaSettings')}
onOpenCodeMap={() => modals.open('codeMap')}
onOpenGitTab={() => ui.setActiveTab('git')}
onOpenPromptHistory={() => setShowPromptHistory(true)}
// Local state
hasRunningServer={hasRunningServer}
historyPrompt={historyPrompt}
/>
</div>
{/* Resizable Divider - drag to resize, double-click to reset */}
{ui.leftPanelVisible && (
<div
{...dividerProps}
className={`hidden md:block h-full ${dividerProps.className} ${isDragging ? 'z-50' : ''}`}
title="Drag to resize, double-click to reset"
/>
)}
{/* PreviewPanel - now consumes contexts directly, minimal props */}
<PreviewPanel
// Only App.tsx-specific callbacks remain
onInspectEdit={handleInspectEdit}
onSendErrorToChat={(error) => controlPanelRef.current?.sendErrorToChat(error)}
onPreviewErrorsChange={setPreviewHasErrors}
onRunnerStatusChange={setHasRunningServer}
onRevertAndRetry={() => controlPanelRef.current?.revertAndRetry()}
onRevertOnly={() => controlPanelRef.current?.revertOnly() ?? false}
canRevertAndRetry={controlPanelRef.current?.canRevertAndRetry ?? false}
canRevert={controlPanelRef.current?.canRevert ?? false}
lastPrompt={controlPanelRef.current?.lastPrompt ?? null}
/>
</div>
</IDEFrame>
</div>
{/* Diff Modal */}
{ctx.pendingReview && (
<DiffModal
originalFiles={ctx.files}
newFiles={ctx.pendingReview.newFiles}
label={ctx.pendingReview.label}
onConfirm={ctx.confirmChange}
onCancel={ctx.cancelReview}
incompleteFiles={ctx.pendingReview.incompleteFiles}
/>
)}
{/* Sync Confirmation Dialog */}
{ctx.pendingSyncConfirmation && (
<SyncConfirmationDialog
confirmation={ctx.pendingSyncConfirmation}
onConfirm={ctx.confirmPendingSync}
onCancel={ctx.cancelPendingSync}
isLoading={ctx.isSyncing}
/>
)}
{/* Snippets Panel */}
<LazySnippetsPanel
isOpen={modals.state.snippetsPanel}
onClose={() => modals.close('snippetsPanel')}
onInsert={(code: string) => {
if (ctx.activeFile && ctx.files[ctx.activeFile]) {
const newContent = ctx.files[ctx.activeFile] + '\n\n' + code;
ctx.setFiles({ ...ctx.files, [ctx.activeFile]: newContent });
ui.setActiveTab('code');
}
}}
/>
{/* Tailwind Palette (lazy-loaded) */}
<LazyTailwindPalette
isOpen={modals.state.tailwindPalette}
onClose={() => modals.close('tailwindPalette')}
onInsert={(className: string) => {
navigator.clipboard.writeText(className);
}}
/>
{/* Component Tree (lazy-loaded) */}
<LazyComponentTree
isOpen={modals.state.componentTree}
onClose={() => modals.close('componentTree')}
files={ctx.files}
onFileSelect={(file: string) => {
ctx.setActiveFile(file);
ui.setActiveTab('code');
}}
/>
{/* Deploy Modal (lazy-loaded) */}
<LazyDeployModal
isOpen={modals.state.deploy}
onClose={() => modals.close('deploy')}
files={ctx.files}
/>
{/* Share Modal (lazy-loaded) */}
<LazyShareModal
isOpen={modals.state.share}
onClose={() => modals.close('share')}
files={ctx.files}
/>
{/* AI Settings Modal (lazy-loaded) */}
<LazyAISettingsModal
isOpen={modals.state.aiSettings}
onClose={() => modals.close('aiSettings')}
onProviderChange={(_providerId, modelId) => handleModelChange(modelId)}
/>
{/* Mega Settings Modal (lazy-loaded) */}
<LazyMegaSettingsModal
isOpen={modals.state.megaSettings}
onClose={() => modals.close('megaSettings')}
initialCategory={megaSettingsInitialCategory}
onProviderChange={(_providerId, modelId) => handleModelChange(modelId)}
/>
{/* History Panel (lazy-loaded) */}
<LazyHistoryPanel
isOpen={modals.state.history}
onClose={() => modals.close('history')}
history={ctx.history}
currentIndex={ctx.currentIndex}
onGoToIndex={ctx.goToIndex}
onSaveSnapshot={ctx.saveSnapshot}
/>
{/* Project Manager */}
<LazyProjectManager
isOpen={modals.state.projectManager}
onClose={() => modals.close('projectManager')}
projects={ctx.projects}
currentProjectId={ctx.currentProject?.id}
isLoading={ctx.isLoadingProjects}
isServerOnline={ctx.isServerOnline}
onCreateProject={async (name, description) => {
const newProject = await ctx.createProject(name || 'Untitled', description);
if (newProject) {
modals.close('projectManager');
}
}}
onOpenProject={async (id) => {
const result = await ctx.openProject(id);
if (result.success) {
modals.close('projectManager');
}
}}
onDeleteProject={async (id) => { await ctx.deleteProject(id); }}
onDuplicateProject={async (id) => { await ctx.duplicateProject(id); }}
onRefresh={ctx.refreshProjects}
/>
{/* Credits Modal (lazy-loaded) */}
<LazyCreditsModal
isOpen={modals.state.credits}
onClose={() => modals.close('credits')}
showOnFirstLaunch={true}
/>
{/* CodeMap Modal (lazy-loaded) */}
<LazyCodeMapModal
isOpen={modals.state.codeMap}
onClose={() => modals.close('codeMap')}
files={ctx.files}
/>
{/* Prompt History Modal */}
<LazyPromptHistoryModal
isOpen={showPromptHistory}
onClose={() => setShowPromptHistory(false)}
onSelectPrompt={(selectedPrompt) => {
setHistoryPrompt(selectedPrompt);
}}
/>
{/* Prompt Confirmation Modal (intercepts all AI calls when enabled) */}
<PromptConfirmationModal />
{/* Project Health Modal (lazy-loaded) */}
<LazyProjectHealthModal
isOpen={modals.state.projectHealth}
onClose={() => modals.close('projectHealth')}
files={ctx.files}
projectName={ctx.currentProject?.name}
onApplyFixes={(fixes) => ctx.setFiles({ ...ctx.files, ...fixes })}
/>
</div>
</ToastProvider>
</ContextMenuProvider>
</PromptConfirmationProvider>
);
}