Skip to content

Commit

Permalink
Refactoring script.js into mulitple files
Browse files Browse the repository at this point in the history
  • Loading branch information
sajedjalil committed Sep 28, 2024
1 parent 1851786 commit cddcffd
Show file tree
Hide file tree
Showing 7 changed files with 140 additions and 128 deletions.
26 changes: 26 additions & 0 deletions static/js/apiService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// apiService.js
import { getCookie } from './utils.js';

export async function sendMessageToAPI(message, chatHistory, userTimestamp) {
const data = {
userType: 'patient',
message: message,
history: chatHistory,
timestamp: userTimestamp
};

const response = await fetch('/chat/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken')
},
body: JSON.stringify(data)
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

return await response.json();
}
39 changes: 39 additions & 0 deletions static/js/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// main.js
import { userInput, sendButton } from './uiElements.js';
import { addMessage, updateAIMessage } from './messageHandler.js';
import { sendMessageToAPI } from './apiService.js';

let chatHistory = [];

async function sendMessage() {
const message = userInput.value.trim();
if (message) {
const userTimestamp = Date.now();
addMessage(message, true, userTimestamp);
userInput.value = '';

chatHistory.push({ role: 'user', content: message });

const aiMessageElement = addMessage('', false, null);

try {
const responseData = await sendMessageToAPI(message, chatHistory, userTimestamp);
const aiMessage = responseData.response;
const aiTimestamp = responseData.ai_timestamp;
updateAIMessage(aiMessageElement, aiMessage, aiTimestamp);

chatHistory.push({ role: 'assistant', content: aiMessage });

} catch (error) {
console.error('Error:', error);
updateAIMessage(aiMessageElement, "Sorry, there was an error processing your request.", Date.now());
}
}
}

sendButton.addEventListener('click', sendMessage);
userInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendMessage();
}
});
37 changes: 37 additions & 0 deletions static/js/messageHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// messageHandler.js
import { chatMessages } from './uiElements.js';
import { formatTimestamp } from './utils.js';

export function addMessage(message, isUser, timestamp) {
const messageElement = document.createElement('div');
messageElement.classList.add('message');
messageElement.classList.add(isUser ? 'user-message' : 'ai-message');

const formattedTimestamp = formatTimestamp(timestamp);

if (isUser) {
messageElement.innerHTML = `
<div class="message-content">${marked.parse(message)}</div>
<div class="timestamp">${formattedTimestamp}</div>
`;
} else {
messageElement.innerHTML = '<div class="typing-indicator">AI is typing...</div>';
}

chatMessages.appendChild(messageElement);
chatMessages.scrollTop = chatMessages.scrollHeight;
return messageElement;
}

export function updateAIMessage(messageElement, content, timestamp) {
const typingIndicator = messageElement.querySelector('.typing-indicator');
if (typingIndicator) {
typingIndicator.remove();
}
const formattedTimestamp = formatTimestamp(timestamp);
messageElement.innerHTML = `
<div class="message-content">${marked.parse(content)}</div>
<div class="timestamp">${formattedTimestamp}</div>
`;
chatMessages.scrollTop = chatMessages.scrollHeight;
}
127 changes: 0 additions & 127 deletions static/js/script.js

This file was deleted.

3 changes: 3 additions & 0 deletions static/js/uiElements.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const chatMessages = document.getElementById('chat-messages');
export const userInput = document.getElementById('user-input');
export const sendButton = document.getElementById('send-button');
34 changes: 34 additions & 0 deletions static/js/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// utils.js
export function formatTimestamp(timestamp) {
const date = new Date(timestamp);
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);

let dateString;
if (date.toDateString() === today.toDateString()) {
dateString = 'Today';
} else if (date.toDateString() === yesterday.toDateString()) {
dateString = 'Yesterday';
} else {
dateString = date.toLocaleDateString([], { month: 'short', day: 'numeric', year: 'numeric' });
}

const timeString = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
return `${dateString} at ${timeString}`;
}

export function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
2 changes: 1 addition & 1 deletion templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@
</div>
</div>

<script src="{% static 'js/script.js' %}"></script>
<script type="module" src="{% static 'js/main.js' %}"></script>
</body>
</html>

0 comments on commit cddcffd

Please sign in to comment.