"use client"; import React, { useState, useEffect, useRef } from 'react'; import Image from 'next/image'; import ChatMessage from './ChatMessage'; import ChatInput from './ChatInput'; type Message = { role: 'user' | 'assistant'; content: string; }; // Function to generate a random number of "meow"s const generateMeowCount = () => { // Random number between 1 and 30 return Math.floor(Math.random() * 30) + 1; }; const Chat: React.FC = () => { const [messages, setMessages] = useState([ { role: 'assistant', content: 'meow', }, ]); const [isTyping, setIsTyping] = useState(false); const [streamingContent, setStreamingContent] = useState(''); const messagesEndRef = useRef(null); const streamIntervalRef = useRef(null); const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToBottom(); }, [messages, isTyping, streamingContent]); // Clean up interval on unmount useEffect(() => { return () => { if (streamIntervalRef.current) { clearInterval(streamIntervalRef.current); } }; }, []); const handleSendMessage = (content: string) => { // Clear any existing interval if (streamIntervalRef.current) { clearInterval(streamIntervalRef.current); streamIntervalRef.current = null; } // Add user message setMessages((prev) => [...prev, { role: 'user', content }]); // Simulate typing setIsTyping(true); setStreamingContent(''); // Simulate response delay (between 0.5-1 seconds) setTimeout(() => { const meowCount = generateMeowCount(); let currentMeows = 0; const meowArray = Array(meowCount).fill("meow"); // Start streaming the meows streamIntervalRef.current = setInterval(() => { if (currentMeows < meowCount) { currentMeows++; setStreamingContent(meowArray.slice(0, currentMeows).join(" ")); } else { // Finished streaming if (streamIntervalRef.current) { clearInterval(streamIntervalRef.current); streamIntervalRef.current = null; } // Add the complete message setMessages((prev) => [...prev, { role: 'assistant', content: meowArray.join(" ") }]); setIsTyping(false); setStreamingContent(''); } }, 100); // Add a new meow every 100ms }, 500 + Math.random() * 500); }; return (
{messages.map((message, index) => ( ))} {isTyping && (
CatGPT Logo

CatGPT

{streamingContent ? (

{streamingContent}

) : (
)}
)}
); }; export default Chat;