-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.js
119 lines (105 loc) · 2.33 KB
/
chat.js
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
115
116
117
118
119
import React, { PureComponent } from "react";
const container = {
width: "100%",
height: "32rem",
display: "flex",
flexDirection: "column"
};
const form = {
width: "100%",
maxHeight: "6rem",
display: "flex",
justifyContent: "space-around",
alignItems: "baseline"
};
const button = {
borderRadius: "0.25rem",
padding: "0.25rem 1rem"
};
const chatLog = {
textAlign: "left",
width: "80%",
maxHeight: "26rem",
margin: "0 auto",
overflowY: "scroll"
};
const chatLine = {
margin: "0.25rem"
};
function* chatterer() {
// opening the conversation
yield String.fromCodePoint(0x1F643);
while (true) {
// ongoing call-and-response
const msg = yield String.fromCodePoint(0x1F4A9);
if (msg.search(/bye/i) !== -1) {
break;
}
}
// closing the conversation
return String.fromCodePoint(0x1F44B);
}
class Chat extends PureComponent {
constructor(props) {
super(props);
this.it = props.generator();
this.state = {
convo: []
};
}
componentDidMount() {
setTimeout(() => {
this.setState({
convo: [
...this.state.convo,
this.it.next().value
]
});
}, 500);
}
componentDidUpdate() {
this.chat.scrollTop = this.chat.scrollHeight;
}
handleSubmit = (e) => {
if (e) {
e.preventDefault();
}
const msg = this.input.value;
this.setState(({
convo: [
...this.state.convo,
msg
]
}));
setTimeout(() => {
this.setState({
convo: [
...this.state.convo,
this.it.next(msg).value
]
});
}, 500);
this.input.value = "";
}
render() {
return (
<div style={container}>
<form onSubmit={this.handleSubmit} style={form}>
<label style={{ padding: "0.5rem" }}>
Chat with the bot:
<input type="text" id="chat" ref={(input) => { this.input = input; }} style={{ padding: "0.25rem" }} />
</label>
<button style={button} type="submit">Send</button>
</form>
<div ref={(chat) => { this.chat = chat; }} style={chatLog}>
{this.state.convo.map(
(msg, i) => (
<p className={this.props.logClassName} key={i} style={chatLine}>{msg}</p>
)
)}
</div>
</div>
);
}
}
export default Chat;