aboutsummaryrefslogtreecommitdiff
path: root/vnext/src/components/Chat.js
blob: 8f3a26c0dc45b2ce92ea1455fd33c316efc07a4e (plain) (blame)
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
84
85
86
87
import React from 'react';
import moment from 'moment';

import PM from './PM';
import MessageInput from './MessageInput';

export default class Chat extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            chats: []
        };
    }
    componentWillMount() {
        this.loadChat(this.props.match.params.user);
    }

    loadChat = (uname) => {
        const { hash } = this.props.visitor;
        this.setState({
            chats: []
        });
        if (hash && uname) {
            fetch(`https://api.juick.com/pm?uname=${uname}&hash=${hash}`)
                .then(response => response.json())
                .then(jsonResponse => {
                    this.setState({
                        chats: jsonResponse
                    });
                });
        }
    }

    onSend = (template) => {
        const url = `https://api.juick.com/pm?hash=${this.props.visitor.hash}`;
        let form = new FormData();
        form.append('body', template.body);
        form.append('uname', template.to.uname);
        fetch(url, {
            method: 'POST',
            body: form
        }).then(response => {
            return response.json()
        }).then(res => {
            this.loadChat(this.props.match.params.user);
        })
            .catch(console.log)
    }

    render() {
        const { chats } = this.state;
        const uname = this.props.match.params.user;
        return (
            <div id="content">
                <article>

                    {uname ? (
                        <div className="chatroom">
                            <ul style={chatStyle} ref="chats">
                                {
                                    chats.map((chat) =>
                                        <PM key={moment.utc(chat.timestamp).valueOf()} chat={chat} />
                                    )
                                }
                            </ul>
                            <MessageInput data={{ mid: 0, timestamp: "0", to: { uname: uname } }} onSend={this.onSend} />
                        </div>
                    ) : (
                            <div className="chatroom no-selection"><p>No chat selected</p></div>
                        )
                    }
                </article>
            </div>
        )
    }
}

const chatStyle = {
    boxSizing: 'border-box',
    padding: '0 20px',
    overflowY: 'scroll',
    height: '450px',
    display: 'flex',
    flexDirection: 'column-reverse',
    width: '100%'
}