import React, { Component } from 'react'; import { withTranslation, Trans} from "react-i18next"; import {Button, Link, Badge, TextField, Grid, Container, Card, CardHeader, Paper, Avatar, FormHelperText, Typography} from "@mui/material"; import ReconnectingWebSocket from 'reconnecting-websocket'; class Chat extends Component { constructor(props) { super(props); } state = { messages: [], value:'', connected: false, peer_connected: false, }; rws = new ReconnectingWebSocket('ws://' + window.location.host + '/ws/chat/' + this.props.orderId + '/'); componentDidMount() { this.rws.addEventListener('open', () => { console.log('Connected!'); this.setState({connected: true}); this.rws.send(JSON.stringify({ type: "message", message: 'just-connected', nick: this.props.ur_nick, })); }); this.rws.addEventListener('message', (message) => { const dataFromServer = JSON.parse(message.data); console.log('Got reply!', dataFromServer.type); if (dataFromServer){ if (dataFromServer.message != 'just-connected' & dataFromServer.message != 'peer-disconnected'){ this.setState((state) => ({ messages: [...state.messages, { msg: dataFromServer.message, userNick: dataFromServer.user_nick, }], }) ) } this.setState({peer_connected: dataFromServer.peer_connected}) } }); this.rws.addEventListener('close', () => { console.log('Socket is closed. Reconnect will be attempted'); this.setState({connected: false}); }); this.rws.addEventListener('error', () => { console.error('Socket encountered error: Closing socket'); }); } componentDidUpdate() { this.scrollToBottom(); } scrollToBottom = () => { this.messagesEnd.scrollIntoView({ behavior: "smooth" }); } onButtonClicked = (e) => { if(this.state.value!=''){ this.rws.send(JSON.stringify({ type: "message", message: this.state.value, nick: this.props.ur_nick, })); this.state.value = '' } e.preventDefault(); } render() { const { t } = this.props; return ( {t("You")+": "}{this.state.connected ? t("connected"): t("disconnected")} {t("Peer")+": "}{this.state.peer_connected ? t("connected"): t("disconnected")} {this.state.messages.map(message => <> {/* If message sender is not our nick, gray color, if it is our nick, green color */} {message.userNick == this.props.ur_nick ? } style={{backgroundColor: '#eeeeee'}} title={message.userNick} subheader={message.msg} subheaderTypographyProps={{sx: {wordWrap: "break-word", width: '200px', color: '#444444'}}} /> : } style={{backgroundColor: '#fafafa'}} title={message.userNick} subheader={message.msg} subheaderTypographyProps={{sx: {wordWrap: "break-word", width: '200px', color: '#444444'}}} />} )}
{ this.messagesEnd = el; }}>
{ this.setState({ value: e.target.value }); this.value = this.state.value; }} sx={{width: 214}} />
{t("The chat has no memory: if you leave, messages are lost.")} {t("Learn easy PGP encryption.")}
) } } export default withTranslation()(Chat);