// components/ChatApp.jsx import React, { useState, useRef, useEffect } from 'react'; import MessageBubble from './MessageBubble'; import { Button , Typography, Box} from '@mui/material'; import { ChatBubbleOutline } from '@mui/icons-material'; import PipelineLoader from './PipelineLoader'; export default function ChatApp() { const [message, setMessage] = useState(''); const [history, setHistory] = useState([]); const [loading, setLoading] = useState(false); const chatEndRef = useRef(null); const examples = [ "What is Python?", "Write a JavaScript function to reverse a string.", "Explain how transformers work.", ]; const scrollToBottom = () => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(scrollToBottom, [history]); const token = process.env.REACT_APP_HF_TOKEN; const sendMessage = async () => { if (!message.trim()) return; const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); const newHistory = [...history, { role: 'user', content: message, time }]; setHistory(newHistory); setMessage(''); setLoading(true); const response = await fetch('https://fredericksundeep-chatmateapi.hf.space/chat-stream', { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ message, history: newHistory }), }); const reader = response.body.getReader(); const decoder = new TextDecoder(); let done = false; let content = ''; while (!done) { const { value, done: isDone } = await reader.read(); if (value) { const chunk = decoder.decode(value); content += chunk; const currentContent = content; // capture safe reference setHistory(h => h.map((msg, i) => i === newHistory.length ? { ...msg, content: currentContent } : msg ) ); } done = isDone; } setHistory(h => [...h, { role: 'assistant', content, time }]); setLoading(false); }; return (
Chat Mate
{history.length === 0 && !loading && ( {examples.map((example, i) => ( ))} )} {history.map((msg, i) => ( ))} {loading && }