Chat.js 3.55 KB
import React, { useState, useEffect, useRef } from "react";
import { connect } from "react-redux";

import {userMessage, sendMessage, createSession} from "../../actions/action_watson";
import store from "../../store";
import axios from "axios";

import Header from "../header/Header";

const BotOptions = ({ option }) => {
    return (
      <div className={'msg label bot'}>{option.label}</div>
    );
}

const BotMsg = ({ bot }) => {
    if (bot.response_type === 'text') {
        return (
            <div dangerouslySetInnerHTML={ {__html: bot.text } } className={'msg bot'}></div>
        )
    } else if (bot.response_type === 'option') {
        console.log("bot : ", bot);
        return (
            <>
                {bot.options.map((e, i) => (
                    <BotOptions key={i} option={e} />
                ))}
            </>
        );
    } else if (bot.response_type === 'image') {
        return (
            <div className={'bot-image-box'}>
                <img src={bot.source} className={'bot-image'} />
            </div>
        );
    }
}

const Chat = ({ chat, userMsg, botMsg, botOption, userMessage, sendMessage }) => {
    const [message, setMessage] = useState("");
    const endOfMessages = useRef(null);

    const scrollToBottom = () => {
        endOfMessages.current.scrollIntoView({ behavior: "smooth" });
    };
    useEffect(scrollToBottom, [chat, userMsg, botMsg, botOption]);

    const handleClick = async (e) => {
        const code = e.keyCode || e.which;

        if (code === 13) {
            console.log(message);
            userMessage(message);
            sendMessage(message);
            setMessage("");
        }
    };

    // initial message
    useEffect(() => {
        if (!localStorage.session) {
            const makeSession = async () => {
                await store.dispatch(createSession());
                axios.defaults.headers.common["session_id"] = localStorage.session;
                console.log("send message before ");
                sendMessage("");
                console.log("send message after ");
            }
            makeSession().then(r => console.log(r)).catch(e => console.log(e));
        }
    }, []);

    return (
        <div className="chat">
            <Header />
            <div className="historyContainer">
                {chat.map((e, i) => {
                    if (e.type === 'bot') {
                        return (
                            <>
                                {e.message.map((elem, idx) => (
                                    <BotMsg key={idx} bot={elem}/>
                                ))}
                            </>
                        );
                    } else if (e.type === 'user') {
                        return (
                            <div key={i} className={'msg user'}>{e.message}</div>
                        )
                    }
                })}
                <div ref={endOfMessages}></div>
            </div>
            <div className={'input'}>
                <input
                    id="chatBox"
                    onChange={(e) => setMessage(e.target.value)}
                    onKeyPress={handleClick}
                    value={message}
                    placeholder={'type anything about corona'}
                />
            </div>
        </div>
    );
};

const mapStateToProps = (state) => ({
    chat: state.watson.messages,
    userMsg: state.watson.userMessages,
    botMsg: state.watson.botMessages,
    botOption: state.watson.botOptions
});

export default connect(mapStateToProps, { userMessage, sendMessage })(Chat);