UNPKG

@teamsparta/chat-ui

Version:
71 lines (61 loc) 2.03 kB
import React, { useEffect, useRef, useState } from "react"; import ProfileHeader from "./ProfileHeader"; import ChatArea from "./ChatArea"; import InputArea from "./InputArea"; import PresetQuestions from "./PresetQuestions"; import * as S from "./ChatContainer.style"; import MessageManager from "../store/MessageManager"; const ChatContainer = ({ config, handleSendMessage }) => { const { initialMessages, profileConfig, presetQuestions } = config; const chatAreaRef = useRef(null); const [messages, setMessages] = useState([]); const messageManager = MessageManager.getInstance(initialMessages); const scrollToBottom = () => { if (chatAreaRef.current) { chatAreaRef.current.scrollTop = chatAreaRef.current.scrollHeight; } }; useEffect(() => { scrollToBottom(); }, []); useEffect(() => { const observer = { update: () => { setMessages([...messageManager.getMessages()]); }, }; // 컴포넌트가 마운트될 때 Observer를 구독 messageManager.subscribe(observer); messageManager.initMessages(initialMessages); // 컴포넌트가 언마운트될 때 Observer를 구독 해제 return () => { messageManager.unsubscribe(observer); }; }, []); return ( <S.Container theme={profileConfig.theme}> <ProfileHeader config={profileConfig} /> <ChatArea theme={profileConfig.theme} initialImage={profileConfig.profileImage} handleThumbUp={profileConfig?.handleThumbUp} handleThumbDown={profileConfig?.handleThumbDown} useRef={chatAreaRef} messages={messages} scrollToBottom={scrollToBottom} /> {presetQuestions && ( <PresetQuestions theme={profileConfig.theme} questions={presetQuestions} /> )} <InputArea theme={profileConfig.theme} scrollToBottom={scrollToBottom} handleSendMessagae={handleSendMessage} /> </S.Container> ); }; export default ChatContainer;