From 048e5fac61ee2486d788e3b6cbef5766263f2f8f Mon Sep 17 00:00:00 2001 From: albin-karlsson <55614148+albin-karlsson@users.noreply.github.com> Date: Thu, 18 Apr 2024 12:57:20 +0200 Subject: [PATCH] Fix initialization issues in TextOutput --- client/src/components/TextOutput.jsx | 47 ++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 9 deletions(-) diff --git a/client/src/components/TextOutput.jsx b/client/src/components/TextOutput.jsx index 88d4405..ed73e7f 100644 --- a/client/src/components/TextOutput.jsx +++ b/client/src/components/TextOutput.jsx @@ -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 (