Честно говоря, я не знаком с реализацией codemirror и др. js, но я пытаюсь использовать веб-сокеты и др. js для обновления текстовой области codemirror, он в основном зависает и выдает ошибку серверной части, когда я type, однако, когда я помещаю курсор, только он работает идеально, мне нужно понимать, что я делаю не так, или может ли кто-нибудь четко объяснить, как работает технология. Это мой код
componentWillMount() {
if (!isAuthenticated()) {
const randomUser = "user" + Math.floor(Math.random() * 9999).toString();
this.setState({ user: randomUser });
} else if (isAuthenticated()) {
this.setState({ user: isAuthenticated().user.name });
}
const socket = io("http://localhost:8080");
this.setState({ socket });
const SocketIOAdapter = ot.SocketIOAdapter;
}
componentDidMount() {
const SocketIOAdapter = ot.SocketIOAdapter;
this.state.socket.on("doc", (obj) => {
console.log(obj);
this.setState({ code: obj.str }, () => {
this.init(
obj.str,
obj.revision,
obj.clients,
new SocketIOAdapter(this.state.socket)
);
});
});
this.state.socket.emit("joinRoom", {
room: this.props.match.params.id,
username: `${this.state.user} joined`,
message: "",
});
this.state.socket.on("chatMessage", (data) => {
console.log(data);
this.setState((previousState) => ({
messages: [...previousState.messages, data],
}));
});
this.scrollToBottom();
}
componentDidUpdate() {
this.scrollToBottom();
}
state = {
socket: null,
messages: [],
textmessage: "",
user: "",
code: "HELLO",
socket: "",
};
sendMessageHandler = () => {
const { textmessage, user, socket } = this.state;
sendMessage(textmessage, user, socket);
this.setState({ textmessage: "" });
};
init = (str, revision, clients, serverAdapter) => {
const EditorClient = ot.EditorClient;
const CodeMirrorAdapter = ot.CodeMirrorAdapter;
console.log(this.CodeMirrorAdapter);
this.cmClient = window.cmClient = new EditorClient(
revision,
clients,
serverAdapter,
new CodeMirrorAdapter(this.cm.editor)
);
};
handleChange = (e) => {
e.preventDefault();
this.setState({
[e.target.name]: e.target.value,
});
};
scrollToBottom = () => {
this.messagesEnd.scrollIntoView({ behavior: "smooth" });
};
renderChatMessages = () => {
return this.state.messages.map((message) => {
return (
<div key={message.date} className="chat-message">
<p>
<span className="user">{message.username} </span>
{message.date}
</p>
<p>{message.message}</p>
</div>
);
});
};
chatBox = () => {
return (
<div className="chatBox">
<div className="messageBox">
{this.renderChatMessages()}
<div
style={{ float: "left", clear: "both" }}
ref={(el) => {
this.messagesEnd = el;
}}
></div>
</div>
<TextField
className="message-form"
id="standard-textarea"
label="Message"
placeholder="Message as Reginald"
name="textmessage"
value={this.state.textmessage}
onChange={(e) => this.handleChange(e)}
multiline
></TextField>
<button
className="button-class send-button"
onClick={() => {
this.sendMessageHandler();
}}
>
Send
</button>
</div>
);
};
render() {
return (
<div className="Parent-container">
<div>
<div className="Editor">
<h2>Type code in the box</h2>
<CodeMirror
className="Editor"
value={this.state.code}
options={{
mode: "javascript",
theme: "material",
lineNumbers: true,
}}
onChange={(editor, value) => {
const SocketIOAdapter = ot.SocketIOAdapter;
this.state.socket.emit("doc", (obj) => {
// console.log(obj);
this.init(
obj.str=value,
obj.revision,
obj.clients,
new SocketIOAdapter(this.state.socket)
);
});
}}
ref={(c) => (this.cm = c)}
/>
</div>
</div>
{this.chatBox()}
</div>
);
}
}
export default Session;
const socketIO = require('socket.io');
var ot = require('ot');
var roomList = {};
module.exports = function(server) {
var str = 'Hello there'
var io = socketIO(server);
io.on('connection', function(socket) {
socket.on('joinRoom', function(data) {
if (!roomList[data.room]) {
var socketIOServer = new ot.EditorSocketIOServer(str, [],data.room, function(socket, cb){
cb(true)
});
roomList[data.room] = socketIOServer;
}
roomList[data.room].addClient(socket);
roomList[data.room].setName(socket, data.username);
console.log(JSON.stringify(roomList))
socket.room = data.room;
socket.name = data.username;
socket.join(data.room)
io.to(socket.room).emit('chatMessage', data)
})
socket.on('chatMessage', function(data) {
console.log(data)
io.to(socket.room).emit('chatMessage', data)
})
socket.on('disconnect', function() {
socket.leave(socket.room)
io.to(socket.room).emit('chatMessage',{username:`${socket.name} left`, message:""})
})
})
}