This repository has been archived by the owner on May 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.js
69 lines (52 loc) · 1.68 KB
/
main.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
import React from "react";
import {render, findDOMNode} from 'react-dom';
import Colyseus from 'colyseus.js'
class Main extends React.Component {
constructor() {
super();
// use current hostname/port as colyseus server endpoint
var endpoint = location.protocol.replace("http", "ws") + "//" + location.hostname;
// development server
if (location.port && location.port !== "80") { endpoint += ":2657" }
this.colyseus = new Colyseus(endpoint)
this.chatRoom = this.colyseus.join('chat', { channel: window.location.hash || "#default" })
this.chatRoom.on('update', this.onUpdateRemote.bind(this))
this.state = {
currentText: "",
messages : []
};
}
onUpdateRemote (newState, patches) {
console.log("new state: ", newState, "patches:", patches)
this.setState(newState, this.autoScroll.bind(this))
}
autoScroll () {
var domMessages = findDOMNode(this.refs.messages)
domMessages.scrollTop = domMessages.scrollHeight
}
onInputChange (e) {
e.preventDefault()
this.setState({ currentText: e.target.value })
}
onSubmit (e) {
e.preventDefault()
this.chatRoom.send(this.state.currentText)
this.setState({currentText: ""})
}
render() {
return <div>
<div id="messages" ref="messages">
{ this.state.messages.map((message, i) => {
return <p key={i}>{ message }</p>
}) }
</div>
<form id="form" onSubmit={this.onSubmit.bind(this)}>
<input id="input" type="text" onChange={this.onInputChange.bind(this)} value={this.state.currentText} />
<button type="submit">send</button>
</form>
</div>
}
}
render((
<Main/>
), document.getElementById('main'));