aboutsummaryrefslogtreecommitdiff
path: root/vnext/src/components/Thread.js
blob: 3fa0ce1000cac358d291cf949176d26b637ff878 (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import React, { useEffect, useState, useRef } from 'react';

import ReactRouterPropTypes from 'react-router-prop-types';
import { UserType } from './Types';

import { Link } from 'react-router-dom';
import moment from 'moment';

import Message from './Message';
import MessageInput from './MessageInput';
import Spinner from './Spinner';
import Avatar from './Avatar';
import Button from './Button';

import { format, embedUrls } from '../utils/embed';

import { getMessages, comment, markReadTracker } from '../api';

function Comment({ msg, visitor, active, setActive }) {
  const embedRef = useRef();
  const msgRef = useRef();
  useEffect(() => {
    if (msgRef.current) {
      embedUrls(msgRef.current.querySelectorAll('a'), embedRef.current);
      if (!embedRef.current.hasChildNodes()) {
        embedRef.current.style.display = 'none';
      }
    }
  }, []);
  return (
    <div className="msg-cont">
      <div className="msg-header">
        <Avatar user={msg.user}>
          <div className="msg-ts">
            {msg.replyto > 0 &&
              (
                <a href={`#${msg.replyto}`} className="info-avatar"><img src={msg.to.avatar} /> {msg.to.uname}&nbsp;</a>
              )}
          </div>
        </Avatar>
      </div>
      {
        msg.html ? <div className="msg-txt" dangerouslySetInnerHTML={{ __html: msg.body }} ref={msgRef} />
          :
          <div className="msg-txt" ref={msgRef}>
            <p dangerouslySetInnerHTML={{ __html: format(msg.body, msg.mid, (msg.tags || []).indexOf('code') >= 0) }} />
          </div>
      }
      {
        msg.photo &&
        <p className="ir"><a href={`//i.juick.com/p/${msg.mid}-${msg.rid}.${msg.attach}`} data-fname={`${msg.mid}-${msg.rid}.${msg.attach}`}>
          <img src={`//i.juick.com/p/${msg.mid}-${msg.rid}.${msg.attach}`} alt="" /></a>
        </p>
      }
      <div className="embedContainer" ref={embedRef} />
      <div className="msg-links">
        {
          visitor.uid > 0 ? (
            <>
              {active === msg.rid || <span style={linkStyle} onClick={() => setActive(msg.rid)}>Reply</span>}
              {active === msg.rid && <MessageInput data={msg} onSend={postComment}>Write a comment...</MessageInput>}
            </>
          ) : (
              <>
                <span>&nbsp;&middot;&nbsp;</span>{active === msg.rid || <Button>Reply</Button>}
              </>
            )
        }
      </div>
    </div>
  );
}

export default function Thread(props) {
  const [message, setMessage] = useState(props.location.state || {});
  const [replies, setReplies] = useState([]);
  const [loading, setLoading] = useState(false);
  const [active, setActive] = useState(0);
  useEffect(() => {
    if (props.connection) {
      props.connection.addEventListener('msg', onReply);
    }
    setActive(0);
    loadReplies();
    return () => {
      if (props.connection) {
        props.connection.removeEventListener('msg', onReply);
      }
    }
  }, [props.connection]);
  let loadReplies = () => {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;

    setReplies([]);
    setLoading(true);
    const { mid } = props.match.params;
    let params = {
      mid: mid
    };
    if (props.visitor && props.visitor.hash) {
      params.hash = props.visitor.hash;
    }
    getMessages('/api/thread', params)
      .then(response => {
        setMessage(response.data.shift());
        setReplies(response.data);
        setLoading(false);
        setActive(0);
      }
      ).catch(ex => {
        console.log(ex);
      });
  }
  let onReply = (json) => {
    const msg = JSON.parse(json.data);
    if (msg.mid == message.mid) {
      setReplies([...this.state.replies, msg]);
    }
  }
  let postComment = (template) => {
    const { mid, rid, body, attach } = template;
    comment(mid, rid, body, attach).then(res => {
      loadReplies();
    })
      .catch(console.log);
  }

  const loaders = Math.min(message.replies || 0, 10);
  return (
    <>
      {
        message.mid ? (
          <Message data={message} visitor={props.visitor}>
            {active === (message.rid || 0) && <MessageInput data={message} onSend={postComment}>Write a comment...</MessageInput>}
          </Message>
        ) : (
            <Spinner />
          )
      }
      <ul id="replies">
        {
          !loading ? replies.map((msg) => (
            <li id={msg.rid} key={msg.rid} className="msg">
              <Comment msg={msg} visitor={props.visitor} active={active} setActive={setActive} />
            </li>
          )) : (
              <>
                {Array(loaders).fill().map((it, i) => <Spinner key={i} />)}
              </>
            )
        }
      </ul>
    </>
  );
}

const linkStyle = {
  cursor: 'pointer'
};

Thread.propTypes = {
  location: ReactRouterPropTypes.location,
  history: ReactRouterPropTypes.history,
  match: ReactRouterPropTypes.match,
  visitor: UserType.isRequired
};