/
index.js
83 lines (75 loc) 路 1.98 KB
/
index.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
import { h, Component } from 'preact';
import database from 'firebase/database';
import autoBind from "react-autobind";
import send from './send.png';
export default class Input extends Component {
constructor(props) {
super(props);
this.firebaseDB = database();
this.currentChat = null;
this.timeoutRef = null;
this.userInput = null;
this.chatMessageRef = null;
autoBind(this);
}
componentDidMount() {
this.userInput = document.querySelector("input");
}
componentWillReceiveProps(nextProps) {
const {chatURL, userId} = this.props;
if (nextProps.chatURL !== chatURL) {
this.chatMessageRef = this.firebaseDB.ref(`chats/${nextProps.chatURL}/messages`);
}
}
clearTimeOut() {
clearTimeout(this.timeoutRef);
}
handleKeyPress() {
this.clearTimeOut();
const {chatURL, userId} = this.props;
this.currentChat = this.firebaseDB.ref(`chats/${chatURL}/${userId}`);
if (event.keyCode === 13) {
this.currentChat.update({
typing: false
});
this.sendMsg();
}
else {
this.currentChat.update({
typing: true
});
}
}
handleKeyUp() {
this.clearTimeOut();
this.timeoutRef = setTimeout(() => {
this.currentChat.update({
typing: false
});
}, 300);
}
sendMsg() {
if (!this.userInput.value.replace(/^\s+|\s+$/g, "") || !this.chatMessageRef) {
return false;
}
const timestamp = new Date();
this.chatMessageRef.push({
id: this.props.userId,
message: this.userInput.value,
timestamp: timestamp.toString()
});
this.userInput.value = "";
}
render() {
return(
<div className="app__input-container">
<div className="app__input">
<input placeholder="Type your message.." onKeyDown={this.handleKeyPress} onKeyUp={this.handleKeyUp}/>
<button onClick={this.sendMsg}>
<img src={send} alt="Send Message"/>
</button>
</div>
</div>
);
}
}