Chat.js
3.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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);