Skip to content

Commit

Permalink
Fix initialization issues in TextOutput
Browse files Browse the repository at this point in the history
  • Loading branch information
albin-karlsson committed Apr 18, 2024
1 parent dc23729 commit 048e5fa
Showing 1 changed file with 38 additions and 9 deletions.
47 changes: 38 additions & 9 deletions client/src/components/TextOutput.jsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,53 @@
import React, { useEffect } from "react";
import React, { useState, useEffect, useRef } from "react";

function TextOutput({ conversation }) {
const [currentMessageIndex, setCurrentMessageIndex] = useState(0);
const [currentSnippetIndex, setCurrentSnippetIndex] = useState(0);
const [currentMessageTextSnippet, setCurrentMessageTextSnippet] =
useState("");
const [initialize, setInitialize] = useState(true); // Flag to control initialization
const textOutputStyle = {
fontFamily: "Arial, sans-serif",
};

// Function to calculate the display time based on text length
const calculateDisplayTime = (text) => Math.max(3, text.length * 0.05);

useEffect(() => {
if (initialize && conversation.length > 0) {
setCurrentMessageIndex(0);
setCurrentSnippetIndex(0);
setInitialize(false); // Reset initialization flag after first setup
}
}, [conversation, initialize]);

useEffect(() => {
console.log("Updated conversation:", conversation);
}, [conversation]); // Make sure to use [conversation] to track changes properly
const processSnippets = () => {
if (conversation.length > currentMessageIndex) {
const snippets =
conversation[currentMessageIndex].text.split(/(?<=\.\s)/);
if (snippets.length > currentSnippetIndex) {
setCurrentMessageTextSnippet(snippets[currentSnippetIndex]);
const timeout = setTimeout(() => {
if (currentSnippetIndex < snippets.length - 1) {
setCurrentSnippetIndex(currentSnippetIndex + 1);
} else if (currentMessageIndex < conversation.length - 1) {
setCurrentMessageIndex(currentMessageIndex + 1);
setCurrentSnippetIndex(0);
}
}, calculateDisplayTime(snippets[currentSnippetIndex]) * 1000);
return () => clearTimeout(timeout);
}
}
};

// Check if the conversation has at least one message and display it, otherwise show a default message.
// const firstMessageText =
// conversation.length > 0 ? conversation[0].text : "No messages yet.";
processSnippets();
}, [currentMessageIndex, currentSnippetIndex, conversation]);

return (
<div>
<h2 style={textOutputStyle}>
{/* {firstMessageText} */}
<br />
Lorem ipsum dolor sit amet.
{currentMessageTextSnippet || "Waiting for messages..."}
</h2>
</div>
);
Expand Down

0 comments on commit 048e5fa

Please sign in to comment.