Skip to content

Commit

Permalink
Lots of fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
davetaz committed Apr 16, 2024
1 parent ffc6e15 commit 29238c4
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 38 deletions.
5 changes: 0 additions & 5 deletions index.js
Expand Up @@ -111,11 +111,6 @@ function unauthorised(res) {
return res.status(401).render("errors/401");
}

function isAdmin(req) {
// Check if authMethod session variable is set to 'google'
return req.session.authMethod === 'google';
}

app.get('/', function(req, res) {
if (req.session.passport) {
res.redirect("/profile");
Expand Down
63 changes: 45 additions & 18 deletions public/js/chat.js
@@ -1,25 +1,40 @@
// Function to render Markdown content using React
async function renderMarkdown(markdown, container) {
// Function to render Markdown content using React
async function renderMarkdown(markdown, container, callback) {
const React = window.React;
const ReactDOM = window.ReactDOM;
const ReactMarkdown = window.ReactMarkdown;
const { useEffect, useState } = React;

if (!window.React || !window.ReactDOM || !ReactMarkdown) {
console.error('React, ReactDOM, or ReactMarkdown is not loaded.');
return;
}

// Define a functional component for rendering Markdown
const MarkdownComponent = ({ markdown }) => {
useEffect(() => {
// Call the callback function if it's provided
if (callback && typeof callback === 'function') {
callback();
}
// Scroll to bottom after rendering
setTimeout(() => scrollToBottom('msgs_cont'), 100);
}, []); // Empty dependency array to ensure the effect runs only once after initial render

return React.createElement(ReactMarkdown, null, markdown);
};

// Create a root to render the Markdown content
const root = ReactDOM.createRoot(container);

// Render the Markdown component
root.render(
React.createElement(ReactMarkdown, null, markdown)
React.createElement(MarkdownComponent, { markdown })
);
setTimeout(() => scrollToBottom('msgs_cont'), 100);
}

async function renderMarkdownWordByWord(markdown, container) {
function renderMarkdownWordByWord(markdown, container, callback) {
const React = window.React;
const ReactDOM = window.ReactDOM;
const ReactMarkdown = window.ReactMarkdown;
Expand All @@ -38,7 +53,13 @@ async function renderMarkdownWordByWord(markdown, container) {

// Function to incrementally update the content, preserving Markdown
const updateContent = () => {
if (currentIndex >= tokens.length) return;
if (currentIndex >= tokens.length) {
// Call the callback function if it's provided
if (callback && typeof callback === 'function') {
callback();
}
return;
}

// Construct the current content slice with proper Markdown
const currentContent = tokens.slice(0, currentIndex + 1).join('');
Expand Down Expand Up @@ -83,11 +104,16 @@ function renderMessage(message, existingElement = null) {

// Call renderMarkdownWordByWord or renderMarkdown to render the message inside the new element
// Make sure renderMarkdownWordByWord or renderMarkdown is defined in the global scope
if (message.role === "assistant") {
renderMarkdownWordByWord(message.message.content, element);
renderRating(message.rating, element);
if (message.message.role === "assistant") {
renderMarkdownWordByWord(message.message.content, element, () => {
renderRating(message.rating, element);
});
} else {
renderMarkdown(message.message.content, element);
renderMarkdown(message.message.content, element, () => {
if (message.message.role === "assistant") {
renderRating(message.rating, element);
}
});
}
}

Expand Down Expand Up @@ -116,15 +142,15 @@ async function loadConversation(conversationId) {
element.id = messageId;
element.className = message.message.role; // Assuming 'role' is part of the message object for styling purposes
listCont.appendChild(element);
renderMarkdown(message.message.content, element);
if (message.message.role === "assistant") {
setTimeout(() => {
renderMarkdown(message.message.content, element, () => {
if (message.message.role === "assistant") {
renderRating(message.rating, element);
}, 800); // 1000 milliseconds = 1 second
}
}
});
});
// Update the address bar with the conversation ID
window.history.pushState({}, '', '/conversation/' + conversationId);
document.getElementById('conversationId').value = conversationId;
// Update the address bar with the conversation ID
window.history.pushState({}, '', '/conversation/' + conversationId);
} catch (error) {
console.error('Error loading conversation:', error);
// Handle error (e.g., show error message)
Expand Down Expand Up @@ -168,7 +194,6 @@ function renderRating(rating, element) {
starsContainer.appendChild(star);
}
}

ratingContainer.appendChild(starsContainer);
element.appendChild(ratingContainer);
scrollToBottom('msgs_cont');
Expand Down Expand Up @@ -281,7 +306,9 @@ async function handleSubmit(event) {
}

async function sendMessage(conversationId, message) {
renderMessage(message);
let newMessage = {};
newMessage.message = message;
renderMessage(newMessage);
const messageInput = document.getElementById('txt');
const responseLi = createResponseNode();
messageInput.value = ''; // Clear the input field
Expand Down
3 changes: 1 addition & 2 deletions routes/completion.js
Expand Up @@ -71,10 +71,9 @@ router.post("/:conversationId", verifyTokenMiddleware, verifyConversationMiddlew

// Update the OpenAI response to include the newly inserted message's _id
const insertedMessage = conversation.history[conversation.history.length - 1];
openaiResponse.id = insertedMessage._id;

// Return the response to the user
res.status(200).json(openaiResponse);
res.status(200).json(insertedMessage);
} catch (error) {
console.error("Error in /openai-completion route:", error);
res.status(error.status || 500).json({ error: error.message });
Expand Down
25 changes: 12 additions & 13 deletions views/partials/conversations.ejs
Expand Up @@ -15,7 +15,6 @@
// Group conversations by date categories
const categorizedConversations = categorizeConversations(conversations);
// Iterate over categorized conversations and render them
Object.keys(categorizedConversations).forEach(category => {
// Create a new div for each category
Expand All @@ -31,16 +30,17 @@
const categoryList = document.createElement('ul');
categoryList.classList.add('category-list');
// Render conversations under each category
categorizedConversations[category].forEach(conversation => {
const conversationItem = document.createElement('li');
const conversationLink = document.createElement('a');
conversationLink.textContent = getTitle(conversation.history[0].message.content);
conversationLink.href = `javascript:loadConversation('${conversation._id}')`; // Call loadConversation with conversationId
conversationLink.classList.add('conversation');
conversationItem.appendChild(conversationLink);
categoryList.appendChild(conversationItem); // Add conversation to the list
});
if (categorizedConversations[category].length > 0) {
categorizedConversations[category].forEach(conversation => {
const conversationItem = document.createElement('li');
const conversationLink = document.createElement('a');
conversationLink.textContent = getTitle(conversation.history[0].message.content);
conversationLink.href = `javascript:loadConversation('${conversation._id}')`; // Call loadConversation with conversationId
conversationLink.classList.add('conversation');
conversationItem.appendChild(conversationLink);
categoryList.appendChild(conversationItem); // Add conversation to the list
});
};
// Append the category list to the category div
categoryDiv.appendChild(categoryList);
Expand Down Expand Up @@ -69,8 +69,7 @@
// Iterate over conversations and categorize them
conversations.forEach(conversation => {
const lastMessageDate = new Date(conversation.history[conversation.history.length - 1].timestamp);
console.log(lastMessageDate);
const lastMessageDate = new Date(conversation.history[conversation.history.length - 1].timestamp);3
const currentDate = new Date();
const timeDiff = currentDate.getTime() - lastMessageDate.getTime();
const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
Expand Down

0 comments on commit 29238c4

Please sign in to comment.