-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
277 lines (247 loc) · 11.2 KB
/
App.tsx
File metadata and controls
277 lines (247 loc) · 11.2 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
import React, { useState, useCallback, useRef, useEffect } from 'react';
import { BrainCircuit, Github, Loader2, Paperclip, X, FileText, Send } from 'lucide-react';
import TopicMap from './components/TopicMap';
import ChatPanel from './components/ChatPanel';
import { generateKnowledgeMap, generateNodeExplanation } from './services/geminiService';
import { GraphData, KnowledgeNode, ChatMessage } from './types';
function App() {
const [inputTopic, setInputTopic] = useState('');
const [graphData, setGraphData] = useState<GraphData | null>(null);
const [loadingMap, setLoadingMap] = useState(false);
const [loadingChat, setLoadingChat] = useState(false);
const [selectedNode, setSelectedNode] = useState<KnowledgeNode | null>(null);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [error, setError] = useState<string | null>(null);
const [attachedFile, setAttachedFile] = useState<File | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Auto-resize textarea
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 120) + 'px';
}
}, [inputTopic]);
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files[0]) {
const file = e.target.files[0];
// Basic validation (e.g. max 10MB)
if (file.size > 10 * 1024 * 1024) {
alert("File is too large. Please upload files under 10MB.");
return;
}
setAttachedFile(file);
}
};
const clearFile = () => {
setAttachedFile(null);
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};
const fileToBase64 = (file: File): Promise<{ mimeType: string; data: string }> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const result = reader.result as string;
// Remove the "data:mime/type;base64," prefix
const data = result.split(',')[1];
resolve({ mimeType: file.type, data });
};
reader.onerror = error => reject(error);
});
};
const handleGenerate = async (e?: React.FormEvent) => {
if (e) e.preventDefault();
if (!inputTopic.trim() && !attachedFile) return;
setLoadingMap(true);
setError(null);
setGraphData(null);
setMessages([]);
setSelectedNode(null);
try {
let fileData = null;
if (attachedFile) {
fileData = await fileToBase64(attachedFile);
}
const data = await generateKnowledgeMap(inputTopic, fileData);
if (data && data.root) {
setGraphData(data);
// Initial welcome message
const sourceText = attachedFile ? `Document "${attachedFile.name}"` : `"${inputTopic}"`;
setMessages([{
id: 'init',
role: 'model',
text: `### ${data.root.label}\n\nAnalysis complete. I've mapped out the structure of ${sourceText}. Click any node to explore details!`
}]);
} else {
setError("Could not structure this content. Try a different topic or document.");
}
} catch (err) {
console.error(err);
setError("Failed to generate map. Please check your API Key or input.");
} finally {
setLoadingMap(false);
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleGenerate();
}
};
const handleNodeClick = useCallback(async (node: KnowledgeNode) => {
if (selectedNode?.id === node.id && loadingChat) return;
setSelectedNode(node);
setLoadingChat(true);
const newUserMsg: ChatMessage = {
id: Date.now().toString(),
role: 'user',
text: node.label
};
setMessages(prev => [...prev, newUserMsg]);
try {
const context = messages.slice(-2).map(m => m.text).join(" ");
const explanation = await generateNodeExplanation(
graphData?.root.label || "the topic",
node.label,
node.description,
context
);
setMessages(prev => [...prev, {
id: (Date.now() + 1).toString(),
role: 'model',
text: `### ${node.label}\n\n${explanation}`
}]);
} catch (err) {
console.error(err);
setMessages(prev => [...prev, {
id: (Date.now() + 1).toString(),
role: 'model',
text: "Sorry, I couldn't fetch the explanation for this node. Please try again."
}]);
} finally {
setLoadingChat(false);
}
}, [selectedNode, loadingChat, graphData, messages]);
return (
<div className="flex flex-col h-screen overflow-hidden bg-[#0b0f19]">
{/* Header */}
<header className="border-b border-white/10 bg-slate-900/50 backdrop-blur-md flex items-center justify-between px-6 py-3 flex-shrink-0 z-20 relative">
<div className="absolute inset-0 bg-gradient-to-r from-indigo-500/10 via-transparent to-transparent pointer-events-none" />
<div className="flex items-center gap-3 relative z-10 mr-4">
<div className="p-2 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-lg shadow-lg shadow-indigo-500/20">
<BrainCircuit className="text-white w-5 h-5" />
</div>
<h1 className="text-xl font-bold text-white tracking-tight hidden sm:block">
InsightMap <span className="text-indigo-400 font-light">AI</span>
</h1>
</div>
<div className="flex-1 max-w-2xl mx-auto relative group z-10">
<div className="absolute -inset-0.5 bg-gradient-to-r from-indigo-500 to-purple-600 rounded-2xl opacity-30 group-hover:opacity-60 transition duration-500 blur"></div>
<div className="relative flex flex-col bg-slate-900 border border-slate-700/50 rounded-2xl shadow-inner overflow-hidden">
{/* File Badge Area - Inside Input Container */}
{attachedFile && (
<div className="px-3 pt-2 pb-0 flex animate-fade-in">
<div className="bg-indigo-500/10 text-indigo-300 text-xs px-2 py-1 rounded-md flex items-center gap-2 border border-indigo-500/30">
<FileText size={12} />
<span className="max-w-[200px] truncate font-medium">{attachedFile.name}</span>
<button
onClick={clearFile}
className="text-indigo-400 hover:text-white hover:bg-indigo-500/20 rounded-full p-0.5 transition-colors"
title="Remove file"
>
<X size={12}/>
</button>
</div>
</div>
)}
<div className="flex items-end">
{/* Text Area */}
<textarea
ref={textareaRef}
value={inputTopic}
onChange={(e) => setInputTopic(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={attachedFile ? "Add specific instructions (optional)..." : "Enter a topic, paste an article, or attach a file..."}
rows={1}
className="w-full bg-transparent py-3 pl-4 pr-24 text-sm text-slate-200 placeholder-slate-500 focus:outline-none resize-none custom-scrollbar"
style={{ minHeight: '46px', maxHeight: '120px' }}
/>
{/* Actions */}
<div className="absolute right-2 bottom-1.5 flex items-center gap-1">
<input
type="file"
ref={fileInputRef}
onChange={handleFileSelect}
className="hidden"
accept=".pdf,.txt,.md,.csv,.json,image/*"
/>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className={`p-2 rounded-full transition-colors ${attachedFile ? 'text-indigo-400 bg-indigo-500/10' : 'text-slate-400 hover:text-slate-200 hover:bg-slate-800'}`}
title="Attach file (PDF, TXT, MD...)"
>
<Paperclip size={18} />
</button>
<button
onClick={() => handleGenerate()}
disabled={loadingMap || (!inputTopic.trim() && !attachedFile)}
className="p-2 bg-indigo-600 text-white rounded-xl hover:bg-indigo-500 transition-all disabled:opacity-50 disabled:hover:bg-indigo-600 shadow-lg"
>
{loadingMap ? <Loader2 className="animate-spin w-4 h-4"/> : <Send size={16} />}
</button>
</div>
</div>
</div>
</div>
<div className="ml-4 z-10 hidden sm:block">
<a href="#" className="text-slate-500 hover:text-white transition-colors">
<Github className="w-6 h-6" />
</a>
</div>
</header>
{/* Main Content */}
<div className="flex-1 flex overflow-hidden relative">
{/* Map Area */}
<div className="flex-1 relative">
{error && (
<div className="absolute inset-0 flex items-center justify-center z-10 pointer-events-none">
<div className="bg-red-900/80 border border-red-500/50 text-red-100 px-6 py-4 rounded-xl backdrop-blur-md shadow-2xl flex items-center gap-3">
<X size={20} /> {error}
</div>
</div>
)}
{loadingMap && (
<div className="absolute inset-0 flex flex-col items-center justify-center z-10 bg-[#0b0f19]/80 backdrop-blur-sm transition-all duration-500">
<div className="relative">
<div className="absolute inset-0 bg-indigo-500 blur-xl opacity-20 animate-pulse"></div>
<Loader2 className="relative animate-spin w-12 h-12 text-indigo-400 mb-4" />
</div>
<p className="text-slate-200 font-medium tracking-wide animate-pulse">
{attachedFile ? "Analyzing document structure..." : "Synthesizing knowledge graph..."}
</p>
<p className="text-xs text-slate-500 mt-2">
{attachedFile ? "Extracting key concepts from file" : "Connecting related nodes"}
</p>
</div>
)}
<TopicMap
data={graphData}
onNodeClick={handleNodeClick}
selectedNodeId={selectedNode?.id || null}
/>
</div>
{/* Chat Area */}
<ChatPanel
messages={messages}
loading={loadingChat}
currentNode={selectedNode}
/>
</div>
</div>
);
}
export default App;