-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai.js
More file actions
109 lines (90 loc) · 4.41 KB
/
Copy pathai.js
File metadata and controls
109 lines (90 loc) · 4.41 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
const API_URL = "http://127.0.0.1:5000";
// --- DOM Elements ---
const messagesContainer = document.getElementById('messagesContainer');
const dreamInput = document.getElementById('dreamInput');
const sendButton = document.getElementById('sendButton');
const loadingIndicator = document.getElementById('loadingIndicator');
// --- Utility Functions ---
function getToken() {
// Get token for Authorization header if user is logged in
return localStorage.getItem('token');
}
function scrollMessagesToBottom() {
// Wait for rendering to complete, then scroll
setTimeout(() => {
messagesContainer.scrollTop = messagesContainer.scrollHeight;
window.scrollTo(0, document.body.scrollHeight);
}, 100);
}
function appendMessage(role, content) {
const isUser = role === 'user';
const alignment = isUser ? 'justify-end' : 'justify-start';
const bubbleColor = isUser ? 'bg-user-bubble text-white' : 'bg-ai-bubble text-gray-800 shadow-md';
const cornerClass = isUser ? 'rounded-br-none' : 'rounded-bl-none';
const name = isUser ? 'You' : 'AI Interpreter';
const messageHTML = `
<div class="flex ${alignment}">
<div class="max-w-xs md:max-w-lg">
<p class="text-xs text-gray-500 mb-0.5 ${isUser ? 'text-right' : 'text-left'}">${name}</p>
<div class="p-4 rounded-xl ${bubbleColor} ${cornerClass} break-words whitespace-pre-wrap">
<p class="text-base leading-snug">${content}</p>
</div>
</div>
</div>
`;
messagesContainer.insertAdjacentHTML('beforeend', messageHTML);
scrollMessagesToBottom();
}
/**
* Handles the chat submission, sending the dream to the backend for interpretation.
*/
async function handleChat(event) {
event.preventDefault();
const dreamText = dreamInput.value.trim();
const token = getToken();
if (!dreamText) return;
// 1. Display User Message immediately
appendMessage('user', dreamText);
dreamInput.value = ''; // Clear input
// 2. Disable input and show loading
dreamInput.disabled = true;
sendButton.disabled = true;
loadingIndicator.classList.remove('hidden');
const headers = { 'Content-Type': 'application/json' };
if (token) {
// Attach the token for logged-in users
headers['Authorization'] = `Bearer ${token}`;
}
try {
// 3. Make the API call
const res = await axios.post(`${API_URL}/chat`, { dream: dreamText }, { headers: headers });
// Backend response structure: {"reply": "...", "guest": false} or {"interpretation": "...", "guest": true}
let replyContent;
if (res.data.interpretation) {
// Guest response
replyContent = res.data.interpretation;
} else if (res.data.reply) {
// Logged-in user response
replyContent = res.data.reply;
} else {
replyContent = "I received a blank response from the interpreter.";
}
// 4. Display AI Response
appendMessage('assistant', replyContent);
} catch (err) {
console.error('Chat failed:', err);
let errorMessage = 'An error occurred while interpreting your dream.';
if (err.response?.data?.error) {
errorMessage += ` Details: ${err.response.data.error}`;
}
appendMessage('assistant', `Error: ${errorMessage}. Please try again.`);
} finally {
// 5. Re-enable input and hide loading
dreamInput.disabled = false;
sendButton.disabled = false;
loadingIndicator.classList.add('hidden');
dreamInput.focus();
}
}
// Expose function globally for the HTML form
window.handleChat = handleChat;