-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
613 lines (549 loc) · 25.6 KB
/
App.tsx
File metadata and controls
613 lines (549 loc) · 25.6 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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
import React, { useState, useEffect } from 'react';
import Sidebar from './components/Sidebar';
import Dashboard from './components/Dashboard';
import DocumentList from './components/DocumentList';
import SharedBrowser from './components/SharedBrowser';
import UploadModal from './components/UploadModal';
import SettingsModal from './components/SettingsModal';
import Auth from './components/Auth';
import { SmartDoc, User, Folder, DocCategory, SharedFolder } from './types';
import { Plus, X, Tag, Calendar, FileText, RefreshCw, Folder as FolderIcon, Cloud, Database, Edit2, Save } from 'lucide-react';
import {
loadLocalData,
addDocumentLocal,
deleteDocumentLocal,
updateDocumentLocal,
addFolderLocal,
deleteFolderLocal,
updateUserProfile,
createSharedFolder,
getSharedFolders,
addDocumentToShared,
deleteDocumentShared,
deleteSharedFolderFull,
USE_REMOTE_DB
} from './services/localService';
const App: React.FC = () => {
const [user, setUser] = useState<User | null>(null);
const [activeTab, setActiveTab] = useState<'dashboard' | 'files' | 'shared'>('dashboard');
const [filterDate, setFilterDate] = useState<string | null>(null);
const [isUploadOpen, setIsUploadOpen] = useState(false);
const [uploadTargetSharedFolderId, setUploadTargetSharedFolderId] = useState<string | null>(null); // If not null, uploading to shared
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
// Private Data
const [documents, setDocuments] = useState<SmartDoc[]>([]);
const [folders, setFolders] = useState<Folder[]>([]);
// Shared Data
const [sharedFolders, setSharedFolders] = useState<SharedFolder[]>([]);
const [currentFolderId, setCurrentFolderId] = useState<string | null>(null);
const [selectedDoc, setSelectedDoc] = useState<SmartDoc | null>(null);
// Edit State
const [isEditing, setIsEditing] = useState(false);
const [editFormData, setEditFormData] = useState<SmartDoc | null>(null);
const [isSyncing, setIsSyncing] = useState(false);
// Reset editing state when selected doc changes
useEffect(() => {
setIsEditing(false);
setEditFormData(null);
}, [selectedDoc]);
// Sync Data function - Accepts user override to avoid stale state in closures
const syncData = async (currentUser?: User | null) => {
const targetUser = currentUser || user;
if (!targetUser) return;
setIsSyncing(true);
try {
const userId = targetUser.email || targetUser.uniqueId || 'user';
// Parallel Fetch
const [privateData, sharedData] = await Promise.all([
loadLocalData(userId, targetUser.accessToken),
getSharedFolders()
]);
setDocuments(privateData.documents);
setFolders(privateData.folders);
setSharedFolders(sharedData);
} catch (e: any) {
console.error("Failed to sync", e);
// Show alert if it's a Permission error so the user knows to fix Console Rules
if (e.message && (e.message.includes("PERMISSION DENIED") || e.message.includes("rules"))) {
alert(e.message);
}
} finally {
setIsSyncing(false);
}
}
const handleLogin = (loggedInUser: User) => {
setUser(loggedInUser);
setDocuments([]);
setFolders([]);
setSharedFolders([]);
setCurrentFolderId(null);
setActiveTab('dashboard');
setFilterDate(null);
// Pass the user directly to ensure we don't rely on stale state
syncData(loggedInUser);
};
const handleLogout = () => {
setUser(null);
setDocuments([]);
setFolders([]);
setSharedFolders([]);
setCurrentFolderId(null);
setActiveTab('dashboard');
setFilterDate(null);
};
const handleUpdateProfilePhoto = async (file: File) => {
if (!user || !user.email) return;
const reader = new FileReader();
reader.onload = async (e) => {
const base64 = e.target?.result as string;
if (base64) {
const result = await updateUserProfile(user.email!, { picture: base64 }, user.accessToken);
if (!('error' in result)) {
setUser(result as User);
} else {
alert(result.error);
}
}
};
reader.readAsDataURL(file);
};
const handleSaveSettings = async (updates: { name?: string; password?: string; picture?: string }) => {
if (!user || !user.email) return;
const result = await updateUserProfile(user.email, updates, user.accessToken);
if ('error' in result) {
alert(result.error);
} else {
setUser(result as User);
}
};
const handleUpload = async (doc: SmartDoc, file?: File) => {
if (!user) return;
setIsSyncing(true);
try {
if (uploadTargetSharedFolderId) {
// SHARED UPLOAD
// 1. Upload to the Shared Folder
// Clone the doc to ensure we don't pass a mutated reference if that happens
await addDocumentToShared(uploadTargetSharedFolderId, { ...doc }, user);
// 2. REPLICATION: Also upload to "My Files" (Private Root)
// We create a separate copy for the private section so it has its own independent storage file.
// This prevents issues where deleting the private file breaks the shared one.
const privateDocCopy = { ...doc };
privateDocCopy.folderId = null; // Use null for Firebase (undefined causes error)
delete privateDocCopy.uploadedBy; // Remove shared context
await addDocumentLocal(user, privateDocCopy);
await syncData(); // Refresh to see updates in both places
alert("Success! Document uploaded to Shared Folder and saved to My Files.");
} else {
// PRIVATE UPLOAD
let finalDoc = { ...doc };
await addDocumentLocal(user, finalDoc);
setDocuments(prev => [finalDoc, ...prev]);
setActiveTab('files');
setFilterDate(null);
}
} catch (e: any) {
console.error("Upload failed", e);
if (e.message.includes('storage/unauthorized') || e.message.includes('STORAGE PERMISSION')) {
alert("UPLOAD FAILED: Permission Denied.\n\nPlease update your Firebase Storage Rules in the Console to allow uploads.\n\nSee the 'Shared' tab for rule instructions.");
} else if (e.message.includes("contains undefined")) {
alert("UPLOAD FAILED: Internal Error (Undefined Value). Please check console.");
} else {
alert(e.message || "Failed to save document.");
}
} finally {
setIsSyncing(false);
setUploadTargetSharedFolderId(null); // Reset upload target
}
};
const handleDelete = async (id: string) => {
const docToDelete = documents.find(d => d.id === id);
if (!docToDelete || !user) return;
if (window.confirm("Are you sure you want to delete this document?")) {
setIsSyncing(true);
try {
await deleteDocumentLocal(user, id);
setDocuments(prev => prev.filter(d => d.id !== id));
if (selectedDoc?.id === id) setSelectedDoc(null);
} catch (e: any) {
console.error("Delete failed", e);
alert(e.message || "Failed to delete.");
} finally {
setIsSyncing(false);
}
}
};
const handleCreateFolder = async (name: string) => {
if (!user) return;
const newFolder: Folder = {
id: crypto.randomUUID(),
name,
createdAt: Date.now()
};
setIsSyncing(true);
try {
await addFolderLocal(user, newFolder);
setFolders(prev => [...prev, newFolder]);
} catch(e: any) {
alert(e.message || "Failed to create folder");
} finally {
setIsSyncing(false);
}
};
// --- SHARED ACTIONS ---
const handleCreateSharedFolder = async (name: string) => {
if(!user) return;
setIsSyncing(true);
try {
await createSharedFolder(name, user);
await syncData();
} catch (e: any) {
alert(e.message);
} finally {
setIsSyncing(false);
}
};
const handleDeleteSharedDoc = async (folderId: string, docId: string) => {
if (!window.confirm("Delete this document for EVERYONE?")) return;
setIsSyncing(true);
try {
await deleteDocumentShared(folderId, docId);
await syncData();
if(selectedDoc?.id === docId) setSelectedDoc(null);
} catch(e: any) {
alert(e.message);
} finally {
setIsSyncing(false);
}
};
const handleDeleteSharedFolder = async (folderId: string) => {
if (!window.confirm("Delete this shared folder and all contents? This cannot be undone.")) return;
setIsSyncing(true);
try {
await deleteSharedFolderFull(folderId);
await syncData();
} catch (e: any) {
alert(e.message);
} finally {
setIsSyncing(false);
}
};
const handleDeleteFolder = async (id: string) => {
if (!user) return;
if (window.confirm("Delete this folder? Documents inside will be moved to the root.")) {
setIsSyncing(true);
try {
// Update UI state first
const updatedDocs = documents.map(doc => doc.folderId === id ? { ...doc, folderId: undefined } : doc);
const updatedFolders = folders.filter(f => f.id !== id);
setDocuments(updatedDocs);
setFolders(updatedFolders);
await deleteFolderLocal(user, id);
const docsInFolder = documents.filter(d => d.folderId === id);
for (const d of docsInFolder) {
await updateDocumentLocal(user, { ...d, folderId: undefined });
}
} catch(e: any) {
alert(e.message || "Failed to delete folder");
} finally {
setIsSyncing(false);
}
}
}
const handleUpdateDoc = async (updatedDoc: SmartDoc) => {
if (!user) return;
// Note: Editing shared docs metadata is not fully implemented in UI for simplification,
// but this function handles private docs mostly.
setDocuments(prev => prev.map(d => d.id === updatedDoc.id ? updatedDoc : d));
if (selectedDoc && selectedDoc.id === updatedDoc.id) {
setSelectedDoc(updatedDoc);
}
setIsSyncing(true);
try {
await updateDocumentLocal(user, updatedDoc);
} catch (e: any) {
console.error("Update failed", e);
alert(e.message || "Failed to save changes.");
} finally {
setIsSyncing(false);
}
};
const handleDashboardDateClick = (date: string) => {
setFilterDate(date);
setActiveTab('files');
};
useEffect(() => {
if (isUploadOpen || selectedDoc || isSettingsOpen) {
document.body.style.overflow = 'hidden';
} else {
document.body.style.overflow = 'unset';
}
}, [isUploadOpen, selectedDoc, isSettingsOpen]);
if (!user) {
return <Auth onLogin={handleLogin} />;
}
// Helper to determine if we can show a preview image
const hasPreview = selectedDoc?.fileData && (selectedDoc.fileData.startsWith('data:image') || selectedDoc.fileData.startsWith('http'));
return (
<div className="flex h-screen bg-gray-50 overflow-hidden font-sans">
<Sidebar
activeTab={activeTab}
setActiveTab={(tab) => {
setActiveTab(tab);
if (tab === 'dashboard') setFilterDate(null);
}}
onLogout={handleLogout}
user={user}
onUpdatePhoto={handleUpdateProfilePhoto}
onOpenSettings={() => setIsSettingsOpen(true)}
/>
<main className="flex-1 flex flex-col min-w-0 overflow-hidden relative">
<header className="h-20 bg-white border-b border-gray-100 flex items-center justify-between px-8 flex-shrink-0">
<div>
<h1 className="text-2xl font-bold text-gray-800 tracking-tight">
{activeTab === 'dashboard' ? 'Dashboard' : (activeTab === 'shared' ? 'Shared Groups' : 'My Files')}
</h1>
<div className="flex items-center gap-2 mt-1">
{isSyncing ? (
<span className="flex items-center gap-1.5 text-xs text-blue-600 font-medium bg-blue-50 px-2.5 py-1 rounded-full animate-in fade-in">
<RefreshCw size={12} className="animate-spin" /> Syncing...
</span>
) : (
<p className="text-sm text-gray-400">Welcome back, {user.name.split(' ')[0]}</p>
)}
</div>
</div>
<div className="flex items-center gap-6">
<div className="hidden sm:flex flex-col items-end">
<span className="text-gray-900 font-bold text-lg leading-tight">{user.name}</span>
<div className="flex items-center gap-3 mt-1">
{user.uniqueId && (
<span className="text-xs text-gray-500 font-mono tracking-wide">
{user.uniqueId}
</span>
)}
<span className="flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-bold tracking-wider border border-gray-200">
<Database size={10} />
{USE_REMOTE_DB ? 'DATABASE' : 'LOCAL'}
</span>
</div>
</div>
<button
onClick={() => { setUploadTargetSharedFolderId(null); setIsUploadOpen(true); }}
className="bg-blue-600 hover:bg-blue-700 text-white px-5 py-2.5 rounded-xl font-medium shadow-md shadow-blue-200 transition-all flex items-center gap-2 active:scale-95 group"
>
<Plus size={20} className="group-hover:rotate-90 transition-transform" />
<span className="hidden sm:inline">Upload</span>
</button>
</div>
</header>
<div className="flex-1 overflow-y-auto p-8">
<div className="max-w-7xl mx-auto">
{activeTab === 'dashboard' && (
<Dashboard documents={documents} onDateClick={handleDashboardDateClick} />
)}
{activeTab === 'files' && (
<DocumentList
documents={documents}
folders={folders}
currentFolderId={currentFolderId}
filterDate={filterDate}
onClearDateFilter={() => setFilterDate(null)}
onNavigate={setCurrentFolderId}
onCreateFolder={handleCreateFolder}
onDeleteFolder={handleDeleteFolder}
onDeleteDoc={handleDelete}
onViewDoc={setSelectedDoc}
/>
)}
{activeTab === 'shared' && (
<SharedBrowser
sharedFolders={sharedFolders}
currentUser={user}
onRefresh={() => syncData()}
onViewDoc={setSelectedDoc}
onUploadToShared={(fid) => { setUploadTargetSharedFolderId(fid); setIsUploadOpen(true); }}
onCreateSharedFolder={handleCreateSharedFolder}
onDeleteSharedDoc={handleDeleteSharedDoc}
onDeleteSharedFolder={handleDeleteSharedFolder}
/>
)}
</div>
</div>
</main>
<UploadModal
isOpen={isUploadOpen}
onClose={() => { setIsUploadOpen(false); setUploadTargetSharedFolderId(null); }}
onUpload={handleUpload}
currentFolderId={currentFolderId}
/>
<SettingsModal
isOpen={isSettingsOpen}
onClose={() => setIsSettingsOpen(false)}
user={user}
onSave={handleSaveSettings}
/>
{selectedDoc && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-in fade-in duration-200">
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col md:flex-row">
<div className="w-full md:w-1/2 bg-gray-100 p-8 flex items-center justify-center border-r border-gray-200 relative">
{hasPreview ? (
<img
src={selectedDoc.fileData}
alt="Document Preview"
className="max-w-full max-h-full shadow-lg rounded object-contain"
/>
) : (
<div className="text-gray-400 flex flex-col items-center text-center p-4">
<FileText size={64} />
<p className="mt-4 text-sm">No preview available.</p>
</div>
)}
</div>
<div className="w-full md:w-1/2 flex flex-col h-full bg-white">
<div className="p-6 border-b border-gray-100 flex justify-between items-start">
<div>
{!isEditing && (
<div className="flex flex-wrap gap-2 mb-2">
<span className="inline-block px-2 py-1 bg-blue-50 text-blue-600 text-xs font-bold uppercase tracking-wider rounded">
{selectedDoc.category}
</span>
{selectedDoc.uploadedBy && (
<span className="inline-block px-2 py-1 bg-purple-50 text-purple-600 text-xs font-bold uppercase tracking-wider rounded">
From: {selectedDoc.uploadedBy}
</span>
)}
</div>
)}
<h2 className="text-2xl font-bold text-gray-800 leading-tight">
{isEditing ? 'Edit Document' : selectedDoc.name}
</h2>
</div>
<button onClick={() => { setSelectedDoc(null); setIsEditing(false); }} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
<X size={24} className="text-gray-500" />
</button>
</div>
{/* --- EDIT MODE (Only for private docs currently) --- */}
{isEditing && editFormData ? (
<div className="p-6 overflow-y-auto flex-1 space-y-5">
<div className="p-3 bg-yellow-50 text-yellow-700 text-xs rounded border border-yellow-100 mb-2">
Editing details is currently only available for private documents.
</div>
<div>
<label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Name</label>
<input
type="text"
value={editFormData.name}
onChange={e => setEditFormData({...editFormData, name: e.target.value})}
className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none"
/>
</div>
{/* ... other edit fields ... */}
<div>
<label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Summary</label>
<textarea
value={editFormData.summary}
onChange={e => setEditFormData({...editFormData, summary: e.target.value})}
className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none h-32 resize-none"
/>
</div>
</div>
) : (
// --- VIEW MODE ---
<div className="p-6 overflow-y-auto flex-1 space-y-6">
{/* Only show Move Folder option for Private Docs */}
{!selectedDoc.uploadedBy && (
<div className="bg-gray-50 p-3 rounded-lg border border-gray-100 flex items-center justify-between">
<div className="flex items-center gap-2">
<FolderIcon size={16} className="text-gray-400" />
<span className="text-sm text-gray-600 font-medium">Location</span>
</div>
<select
value={selectedDoc.folderId || ""}
onChange={(e) => handleUpdateDoc({ ...selectedDoc, folderId: e.target.value || null })}
className="bg-white border border-gray-200 text-gray-800 text-sm rounded-md focus:ring-blue-500 focus:border-blue-500 block p-1.5 cursor-pointer max-w-[150px]"
>
<option value="">Home (Root)</option>
{folders.map(f => (
<option key={f.id} value={f.id}>{f.name}</option>
))}
</select>
</div>
)}
<div>
<h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wide mb-2">Summary</h3>
<p className="text-gray-700 leading-relaxed bg-gray-50 p-4 rounded-lg border border-gray-100">
{selectedDoc.summary}
</p>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wide mb-1">Uploaded</h3>
<div className="flex items-center gap-2 text-gray-600 text-sm">
<Calendar size={14} />
{new Date(selectedDoc.uploadDate).toLocaleDateString()}
</div>
</div>
{selectedDoc.extractedDate && (
<div>
<h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wide mb-1">Extracted Date</h3>
<div className="flex items-center gap-2 text-gray-600 text-sm">
<Calendar size={14} />
{selectedDoc.extractedDate}
</div>
</div>
)}
</div>
<div>
<h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wide mb-2">Tags</h3>
<div className="flex flex-wrap gap-2">
{selectedDoc.tags.map((tag, i) => (
<span key={i} className="px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-sm font-medium flex items-center gap-1">
<Tag size={12} />
{tag}
</span>
))}
</div>
</div>
</div>
)}
{/* Footer Actions */}
<div className="p-6 border-t border-gray-100 bg-gray-50 flex justify-end gap-3">
{isEditing ? (
<>
<button
onClick={() => { setIsEditing(false); setEditFormData(null); }}
className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg text-sm font-medium transition-colors"
>
Cancel
</button>
<button
onClick={() => { if(editFormData) handleUpdateDoc(editFormData); setIsEditing(false); }}
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors flex items-center gap-2"
>
<Save size={16} />
Save Changes
</button>
</>
) : (
// Edit button is visible for everyone, but logic inside might restrict fields.
// For shared docs, we hide "Edit" for now to keep it simple, as concurrent editing isn't implemented.
!selectedDoc.uploadedBy && (
<button
onClick={() => { setEditFormData(selectedDoc); setIsEditing(true); }}
className="px-4 py-2 border border-gray-300 bg-white hover:bg-gray-50 text-gray-700 rounded-lg text-sm font-medium transition-colors flex items-center gap-2"
>
<Edit2 size={16} />
Edit Details
</button>
)
)}
</div>
</div>
</div>
</div>
)}
</div>
);
};
export default App;