-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
410 lines (371 loc) · 16.7 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chat App</title>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<style>
html, body {
height: 100%;
margin: 0;
overflow: hidden;
}
.chat-container {
height: 100vh;
}
.messages-container {
height: calc(100% - 120px);
}
.conversations-list {
height: calc(100vh - 100px);
overflow-y: auto;
}
.textarea-container {
min-height: 60px;
max-height: 200px;
}
textarea {
resize: none;
min-height: 60px;
max-height: 150px;
}
</style>
</head>
<body class="bg-gray-100">
<!-- Auth Container -->
<div id="authContainer" class="h-screen flex items-center">
<!-- Login Form -->
<div id="loginForm" class="max-w-md mx-auto bg-white p-8 rounded-lg shadow-md">
<h2 class="text-2xl font-bold mb-6 text-center">Login</h2>
<form id="loginFormElement" class="space-y-4">
<div>
<label class="block text-gray-700">Username</label>
<input type="text" id="loginUsername" class="w-full p-2 border rounded" required>
</div>
<div>
<label class="block text-gray-700">Password</label>
<input type="password" id="loginPassword" class="w-full p-2 border rounded" required>
</div>
<button type="submit" class="w-full bg-blue-500 text-white p-2 rounded hover:bg-blue-600">Login</button>
</form>
<p class="mt-4 text-center">
Don't have an account?
<a href="#" id="showSignup" class="text-blue-500">Sign up</a>
</p>
</div>
<!-- Signup Form -->
<div id="signupForm" class="max-w-md mx-auto bg-white p-8 rounded-lg shadow-md hidden">
<h2 class="text-2xl font-bold mb-6 text-center">Sign Up</h2>
<form id="signupFormElement" class="space-y-4">
<div>
<label class="block text-gray-700">Username</label>
<input type="text" id="signupUsername" class="w-full p-2 border rounded" required>
</div>
<div>
<label class="block text-gray-700">Email</label>
<input type="email" id="signupEmail" class="w-full p-2 border rounded" required>
</div>
<div>
<label class="block text-gray-700">Password</label>
<input type="password" id="signupPassword" class="w-full p-2 border rounded" required>
</div>
<button type="submit" class="w-full bg-green-500 text-white p-2 rounded hover:bg-green-600">Sign Up</button>
</form>
<p class="mt-4 text-center">
Already have an account?
<a href="#" id="showLogin" class="text-blue-500">Login</a>
</p>
</div>
</div>
<!-- Main Chat Container -->
<div id="chatContainer" class="hidden h-screen">
<div class="flex h-full">
<!-- Sidebar -->
<div class="w-64 bg-gray-800 text-white flex flex-col">
<!-- New Chat Button -->
<div class="p-4 border-b border-gray-700">
<button id="newChatButton" class="w-full bg-gray-700 text-white p-2 rounded hover:bg-gray-600">
+ New Chat
</button>
</div>
<!-- Conversations List -->
<div id="conversationsList" class="conversations-list p-2 space-y-2">
<!-- Conversations will be added here -->
</div>
<!-- Logout Button -->
<div class="mt-auto p-4 border-t border-gray-700">
<button id="logoutButton" class="w-full bg-red-500 text-white p-2 rounded hover:bg-red-600">
Logout
</button>
</div>
</div>
<!-- Chat Area -->
<div class="flex-1 flex flex-col bg-white">
<!-- Chat Messages -->
<div id="messagesContainer" class="messages-container p-4 space-y-4 overflow-y-auto">
<!-- Messages will be added here -->
</div>
<!-- Message Input -->
<div class="p-4 border-t">
<form id="chatForm" class="flex flex-col space-y-2">
<div class="textarea-container relative">
<textarea
id="messageInput"
class="w-full p-3 border rounded"
placeholder="Type your message..."
rows="3"
></textarea>
</div>
<button
type="submit"
class="bg-blue-500 text-white px-6 py-2 rounded hover:bg-blue-600"
>
Send
</button>
</form>
</div>
</div>
</div>
</div>
<script>
const API_URL = 'http://localhost:8000';
let authToken = localStorage.getItem('token');
let currentConversationId = null;
let conversations = [];
// Show/hide auth forms
document.getElementById('showSignup').addEventListener('click', () => {
document.getElementById('loginForm').classList.add('hidden');
document.getElementById('signupForm').classList.remove('hidden');
});
document.getElementById('showLogin').addEventListener('click', () => {
document.getElementById('signupForm').classList.add('hidden');
document.getElementById('loginForm').classList.remove('hidden');
});
// Check auth state and show appropriate container
function checkAuth() {
if (authToken) {
document.getElementById('authContainer').classList.add('hidden');
document.getElementById('chatContainer').classList.remove('hidden');
loadConversations();
} else {
document.getElementById('authContainer').classList.remove('hidden');
document.getElementById('chatContainer').classList.add('hidden');
}
}
// Function to delete a conversation
function deleteConversation(conversationId) {
conversations = conversations.filter(c => c.id !== conversationId);
updateConversationsList();
// If we deleted the current conversation, load another one or create new
if (conversationId === currentConversationId) {
if (conversations.length > 0) {
loadConversation(conversations[0].id);
} else {
document.getElementById('newChatButton').click();
}
}
}
// Handle new conversation
document.getElementById('newChatButton').addEventListener('click', () => {
currentConversationId = Date.now().toString();
const conversation = {
id: currentConversationId,
title: 'New Chat',
messages: []
};
conversations.push(conversation);
updateConversationsList();
document.getElementById('messagesContainer').innerHTML = '';
});
// Update conversations list in sidebar
function updateConversationsList() {
const container = document.getElementById('conversationsList');
container.innerHTML = '';
conversations.forEach(conv => {
const div = document.createElement('div');
div.className = `p-2 rounded flex justify-between items-center ${conv.id === currentConversationId ? 'bg-gray-700' : 'hover:bg-gray-700'}`;
// Title/conversation div (clickable)
const titleDiv = document.createElement('div');
titleDiv.className = 'flex-grow cursor-pointer truncate pr-2';
titleDiv.textContent = conv.title;
titleDiv.onclick = () => loadConversation(conv.id);
// Delete button
const deleteButton = document.createElement('button');
deleteButton.className = 'text-gray-400 hover:text-red-500 p-1 rounded';
deleteButton.innerHTML = '×'; // Using × symbol for delete
deleteButton.onclick = (e) => {
e.stopPropagation(); // Prevent conversation from being loaded
if (confirm('Are you sure you want to delete this conversation?')) {
deleteConversation(conv.id);
}
};
div.appendChild(titleDiv);
div.appendChild(deleteButton);
container.appendChild(div);
});
// Store conversations in localStorage
localStorage.setItem('conversations', JSON.stringify(conversations));
}
// Load specific conversation
function loadConversation(conversationId) {
currentConversationId = conversationId;
const conversation = conversations.find(c => c.id === conversationId);
if (conversation) {
document.getElementById('messagesContainer').innerHTML = '';
conversation.messages.forEach(msg => addMessage(msg.role, msg.content));
updateConversationsList();
}
}
// Load all conversations
function loadConversations() {
const savedConversations = localStorage.getItem('conversations');
if (savedConversations) {
conversations = JSON.parse(savedConversations);
updateConversationsList();
if (conversations.length > 0) {
loadConversation(conversations[0].id);
} else {
document.getElementById('newChatButton').click();
}
} else {
document.getElementById('newChatButton').click();
}
}
// Signup form submission
document.getElementById('signupFormElement').addEventListener('submit', async (e) => {
e.preventDefault();
try {
const response = await fetch(`${API_URL}/signup`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: document.getElementById('signupUsername').value,
email: document.getElementById('signupEmail').value,
password: document.getElementById('signupPassword').value
})
});
if (response.ok) {
alert('Signup successful! Please login.');
document.getElementById('signupForm').classList.add('hidden');
document.getElementById('loginForm').classList.remove('hidden');
} else {
const error = await response.json();
alert(error.detail || 'Signup failed');
}
} catch (error) {
alert('Error during signup');
}
});
// Login form submission
document.getElementById('loginFormElement').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('username', document.getElementById('loginUsername').value);
formData.append('password', document.getElementById('loginPassword').value);
try {
const response = await fetch(`${API_URL}/token`, {
method: 'POST',
body: formData
});
if (response.ok) {
const data = await response.json();
localStorage.setItem('token', data.access_token);
authToken = data.access_token;
checkAuth();
// Function to delete a conversation
function deleteConversation(conversationId) {
conversations = conversations.filter(c => c.id !== conversationId);
updateConversationsList();
// If we deleted the current conversation, load another one or create new
if (conversationId === currentConversationId) {
if (conversations.length > 0) {
loadConversation(conversations[0].id);
} else {
document.getElementById('newChatButton').click();
}
}
}
} else {
alert('Login failed');
}
} catch (error) {
alert('Error during login');
}
});
// Handle textarea auto-resize and Enter key
const messageInput = document.getElementById('messageInput');
messageInput.addEventListener('input', function() {
this.style.height = 'auto';
this.style.height = Math.min(this.scrollHeight, 150) + 'px';
});
messageInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
document.getElementById('chatForm').dispatchEvent(new Event('submit'));
}
});
// Chat form submission
document.getElementById('chatForm').addEventListener('submit', async (e) => {
e.preventDefault();
const message = messageInput.value.trim();
if (!message) return;
messageInput.value = '';
messageInput.style.height = 'auto';
// Add user message to chat and conversation
addMessage('user', message);
const conversation = conversations.find(c => c.id === currentConversationId);
conversation.messages.push({ role: 'user', content: message });
// Update conversation title if it's the first message
if (conversation.title === 'New Chat') {
conversation.title = message.slice(0, 30) + (message.length > 30 ? '...' : '');
updateConversationsList();
}
try {
const response = await fetch(`${API_URL}/chat`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: message
})
});
if (response.ok) {
const data = await response.json();
addMessage('assistant', data.response);
conversation.messages.push({ role: 'assistant', content: data.response });
updateConversationsList();
} else {
alert('Failed to send message');
}
} catch (error) {
alert('Error sending message');
}
});
// Logout button
document.getElementById('logoutButton').addEventListener('click', () => {
localStorage.removeItem('token');
localStorage.removeItem('conversations');
authToken = null;
conversations = [];
document.getElementById('messagesContainer').innerHTML = '';
checkAuth();
});
// Add message to chat
function addMessage(role, content) {
const messagesContainer = document.getElementById('messagesContainer');
const messageDiv = document.createElement('div');
messageDiv.className = `p-4 rounded-lg ${role === 'user' ? 'bg-blue-100 ml-12' : 'bg-gray-100 mr-12'}`;
messageDiv.textContent = content;
messagesContainer.appendChild(messageDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
// Initial auth check
checkAuth();
</script>
</body>
</html>