aboutsummaryrefslogtreecommitdiff
path: root/vnext/src/ui/Chat.js
diff options
context:
space:
mode:
authorGravatar Vitaly Takmazov2019-05-04 21:13:12 +0300
committerGravatar Vitaly Takmazov2023-01-13 10:37:54 +0300
commitf470636a70943a8ecad8bddc791a1c2dddd28e1e (patch)
treec43d109d88adbde9a696084070cdd92c6b9a004b /vnext/src/ui/Chat.js
parent3d7d213e3ddc5bf4f71d536f31677b768aa3b7c0 (diff)
Components -> UI
Diffstat (limited to 'vnext/src/ui/Chat.js')
-rw-r--r--vnext/src/ui/Chat.js85
1 files changed, 85 insertions, 0 deletions
diff --git a/vnext/src/ui/Chat.js b/vnext/src/ui/Chat.js
new file mode 100644
index 00000000..a1254a10
--- /dev/null
+++ b/vnext/src/ui/Chat.js
@@ -0,0 +1,85 @@
+import React, { useEffect, useState, useCallback } from 'react';
+import PropTypes from 'prop-types';
+import ReactRouterPropTypes from 'react-router-prop-types';
+import { UserType } from './Types';
+import moment from 'moment';
+
+import PM from './PM';
+import MessageInput from './MessageInput';
+import UserInfo from './UserInfo';
+
+import { getChat, pm } from '../api';
+
+import './Chat.css';
+
+export default function Chat(props) {
+ const [chats, setChats] = useState([]);
+ useEffect(() => {
+ if (props.connection.addEventListener) {
+ props.connection.addEventListener('msg', onMessage);
+ }
+ loadChat(props.match.params.user);
+ console.log(props.connection);
+ return () => {
+ if (props.connection.removeEventListener) {
+ props.connection.removeEventListener('msg', onMessage);
+ }
+ };
+ }, [props.connection, onMessage, loadChat, props.match.params.user]);
+
+ let loadChat = useCallback((uname) => {
+ const { hash } = props.visitor;
+ setChats([]);
+ if (hash && uname) {
+ getChat(uname)
+ .then(response => {
+ setChats(response.data);
+ });
+ }
+ }, [props.visitor]);
+
+ let onMessage = useCallback((json) => {
+ const msg = JSON.parse(json.data);
+ if (msg.user.uname === props.match.params.user) {
+ setChats((oldChat) => {
+ return [msg, ...oldChat];
+ });
+ }
+ }, [props.match.params.user]);
+
+ let onSend = (template) => {
+ pm(template.to.uname, template.body)
+ .then(res => {
+ loadChat(props.match.params.user);
+ }).catch(console.log);
+ };
+ const uname = props.match.params.user;
+ return (
+ <div className="msg-cont">
+ <UserInfo user={uname} />
+ {uname ? (
+ <div className="chatroom">
+ <ul className="Chat_messages">
+ {
+ chats.map((chat) =>
+ <PM key={moment.utc(chat.timestamp).valueOf()} chat={chat} {...props} />
+ )
+ }
+ </ul>
+ <MessageInput data={{ mid: 0, timestamp: '0', to: { uname: uname } }} onSend={onSend}>
+ Reply...
+ </MessageInput>
+ </div>
+ ) : (
+ <div className="chatroom no-selection"><p>No chat selected</p></div>
+ )
+ }
+ </div>
+ );
+}
+
+Chat.propTypes = {
+ visitor: UserType.isRequired,
+ match: ReactRouterPropTypes.match.isRequired,
+ connection: PropTypes.object.isRequired
+};