-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
189 lines (155 loc) · 6.67 KB
/
script.js
File metadata and controls
189 lines (155 loc) · 6.67 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
// Global variables
let sessionId = null;
let currentTone = "friendly";
// --- IMPORTANT ---
// This is the full URL of your backend on Hugging Face Spaces.
const BACKEND_URL = "https://celestialssd-psyassist.hf.space";
document.addEventListener('DOMContentLoaded', function() {
const chatMessages = document.getElementById('chat-messages');
const userInput = document.getElementById('user-message');
const sendButton = document.getElementById('send-btn');
const crisisResources = document.getElementById('crisis-resources');
const menuToggle = document.querySelector('.menu-toggle');
const sidebar = document.querySelector('.sidebar');
menuToggle.addEventListener('click', function() {
sidebar.classList.toggle('active');
});
document.addEventListener('click', function(e) {
if (window.innerWidth <= 768 && !sidebar.contains(e.target) && !menuToggle.contains(e.target) && sidebar.classList.contains('active')) {
sidebar.classList.remove('active');
}
});
function addMessage(message, isUser) {
const messageDiv = document.createElement('div');
messageDiv.className = isUser ? 'message user-message' : 'message bot-message';
const messagePara = document.createElement('p');
messagePara.textContent = message;
messageDiv.appendChild(messagePara);
if (!isUser) {
const disclaimer = document.createElement('small');
disclaimer.textContent = 'Remember: I\'m an AI assistant, not a replacement for professional mental health care.';
messageDiv.appendChild(disclaimer);
}
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
async function sendMessage() {
const message = userInput.value.trim();
if (message === '') return;
addMessage(message, true);
userInput.value = '';
try {
// Use the full backend URL and the correct /api/chat endpoint
const response = await fetch(`${BACKEND_URL}/api/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: message,
session_id: sessionId,
tone: currentTone
}),
});
if (!response.ok) {
throw new Error(`Server error: ${response.status}`);
}
const data = await response.json();
if (data.session_id) {
sessionId = data.session_id;
}
addMessage(data.response, false);
if (data.crisis) {
crisisResources.style.display = 'block';
}
} catch (error) {
console.error('Error:', error);
addMessage("I'm having trouble connecting. Please try again later.", false);
}
}
sendButton.addEventListener('click', sendMessage);
userInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
document.querySelector('.btn').addEventListener('click', function() {
while (chatMessages.children.length > 1) {
chatMessages.removeChild(chatMessages.lastChild);
}
if (crisisResources) {
crisisResources.style.display = 'none';
}
startNewSession(sessionId);
});
const toneLinks = document.querySelectorAll('.dropdown-content a');
toneLinks.forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault();
const parentButton = link.closest('.dropdown')?.querySelector('.dropbtn');
if (!parentButton || !parentButton.textContent.includes('Tone')) {
return;
}
const tone = this.textContent.toLowerCase();
currentTone = tone;
parentButton.innerHTML = `<i class="fas fa-sliders-h"></i> Tone: ${this.textContent}`;
addMessage(`I'll adjust my tone to be more ${tone} now.`, false);
console.log("Tone set to:", currentTone);
});
});
loadChatHistory();
window.addEventListener('beforeunload', function() {
if (sessionId) {
const payload = {
message: "_session_end_",
session_id: sessionId,
end_chat: true
};
// CORRECTED: Using a Blob with sendBeacon is more robust
const blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
navigator.sendBeacon(`${BACKEND_URL}/api/chat`, blob);
}
});
startNewSession();
});
async function startNewSession(oldSessionId = null) {
try {
// Use the full backend URL and the correct /api/new-chat endpoint
const response = await fetch(`${BACKEND_URL}/api/new-chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
session_id: oldSessionId
}),
});
const data = await response.json();
sessionId = data.session_id;
console.log("New session started:", sessionId);
} catch (error) {
console.error("Error starting new session:", error);
}
}
async function loadChatHistory() {
try {
// Use the full backend URL and the correct /api/chat-history endpoint
const response = await fetch(`${BACKEND_URL}/api/chat-history`);
const data = await response.json();
const historyDropdown = document.querySelector('.sidebar .dropdown:nth-child(2) .dropdown-content');
if (!historyDropdown) return;
// Clear existing history items
const existingLinks = historyDropdown.querySelectorAll('a:not(:last-child)');
existingLinks.forEach(link => link.remove());
data.history.forEach(session => {
const date = new Date(session.timestamp.replace(/(\d{8})_(\d{6})/, '$1T$2')).toLocaleString();
const historyItem = document.createElement('a');
historyItem.href = '#';
historyItem.textContent = `${session.summary} (${date})`;
historyDropdown.insertBefore(historyItem, historyDropdown.lastElementChild);
});
} catch (error) {
console.error("Error loading chat history:", error);
}
}