aboutsummaryrefslogtreecommitdiff
path: root/vnext/src/ui/Thread.js
blob: a290acd7355494c5841ff1b353f3c6da548c2eec (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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import { useEffect, useState, useRef, useCallback } from 'react';
import { useLocation, useParams } from 'react-router-dom';

import Message from './Message';
import MessageInput from './MessageInput';
import Spinner from './Spinner';
import Avatar from './Avatar';
import { UserLink } from './UserInfo';
import Button from './Button';

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

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

import { chatItemStyle } from './helpers/BubbleStyle';

import './Thread.css';

let isMounted;
/**
   * @type import('../api').Message
   */
const emptyMessage = {};

/**
 * @param {{
    msg: import('../api').Message,
    draft: string,
    visitor: import('../api').User,
    active: number,
    setActive: function,
    onStartEditing: function,
    postComment: function
  }} props
 */
function Comment({ msg, draft, visitor, active, setActive, onStartEditing, postComment }) {
  const embedRef = useRef();
  const msgRef = useRef();
  const [author, setAuthor] = useState(msg.user);
  useEffect(() => {
    if (msgRef.current) {
      embedUrls(msgRef.current.querySelectorAll('a'), embedRef.current);
      if (!embedRef.current.hasChildNodes()) {
        embedRef.current.style.display = 'none';
      }
    }
  }, []);
  const userRef = useRef(author);
  useEffect(() => {
    isMounted = true;
    if (userRef.current.uri) {
      fetchUserUri(userRef.current.uri).then(remote_user => {
        if (isMounted) {
          setAuthor({
            uid: 0,
            uname: remote_user.data.preferredUsername,
            avatar: remote_user.data.icon && remote_user.data.icon.url,
            uri: author.uri
          });
        }
      });
    }
    return () => {
      isMounted = false;
    };
  }, [author.uri, msg.user]);
  return (
    <div style={chatItemStyle(visitor, msg)}>
      <div className="msg-header">
        <Avatar user={author} link={author.uri}>
          <div className="msg-ts">
            {msg.replyto > 0 &&
              (
                <UserLink user={msg.to} />
              )}
          </div>
        </Avatar>
      </div>
      {
        msg.body &&
        <div className={visitor.uid === msg.user.uid ? 'msg-bubble msg-bubble-my' : 'msg-bubble'}>
          <div ref={msgRef}>
            <p dangerouslySetInnerHTML={{ __html: format(msg.body, msg.mid.toString(), (msg.tags || []).indexOf('code') >= 0) }} />
          </div>
        </div>
      }
      {
        msg.photo &&
        <div className="msg-media">
          <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/photos-512/${msg.mid}-${msg.rid}.${msg.attach}`} alt="" />
          </a>
        </div>
      }
      <div className="embedContainer" ref={embedRef} />
      {
        active === msg.rid && <MessageInput data={msg} text={draft || ''} onSend={postComment}>Write a comment...</MessageInput>
      }
      <div className="msg-links">
        {
          visitor.uid > 0 ? (
            <>
              {active === msg.rid || <span style={linkStyle} onClick={() => setActive(msg.rid)}>Reply</span>}
              {
                visitor.uid == msg.user.uid &&
                <>
                  <span>&nbsp;&middot;&nbsp;</span>
                  <span style={linkStyle} onClick={() => onStartEditing(msg)}>Edit</span>
                </>
              }
            </>
          ) : (
            <>
              <span>&nbsp;&middot;&nbsp;</span>{active === msg.rid || <Button>Reply</Button>}
            </>
          )
        }
      </div>
    </div>
  );
}

/**
 * @param {{
     visitor: import('../api').SecureUser
     connection: EventSource?
  }} props
 */
export default function Thread(props) {
  const location = useLocation();
  const params = useParams();
  const [message, setMessage] = useState((location.state || {}).msg || {});
  const [replies, setReplies] = useState([]);
  const [loading, setLoading] = useState(false);
  const [active, setActive] = useState(0);

  const [editing, setEditing] = useState(emptyMessage);
  const [hash, setHash] = useState(props.visitor.hash);
  const { mid } = params;

  let loadReplies = useCallback(() => {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
    setReplies([]);
    setLoading(true);
    let params = {
      mid: mid
    };
    params.hash = hash;
    getMessages('/api/thread', params)
      .then(response => {
        let updatedMessage = response.data.shift();
        if (!message.mid) {
          setMessage(updatedMessage);
        }
        setReplies(response.data);
        setLoading(false);
        setActive(0);
      }
      ).catch(ex => {
        console.log(ex);
      });
  }, [hash, message.mid, mid]);
  let onReply = useCallback((json) => {
    const msg = JSON.parse(json.data);
    if (msg.mid == message.mid) {
      setReplies(oldReplies => {
        return [...oldReplies, msg];
      });
    }
  }, [message]);

  let postComment = useCallback((template) => {
    const { mid, rid, body, attach } = template;
    let commentAction = editing.rid ? update(mid, editing.rid, body) : comment(mid, rid, body, attach);
    commentAction.then(res => {
      setEditing(emptyMessage);
      loadReplies();
    })
      .catch(console.log);
  }, [editing.rid, loadReplies]);

  let startEditing = (reply) => {
    setActive(reply.replyto);
    setEditing(reply);
  };

  useEffect(() => {
    setActive(0);
    loadReplies();
  }, [loadReplies]);
  useEffect(() => {
    if (props.connection.addEventListener && message.mid) {
      props.connection.addEventListener('msg', onReply);
    }
    return () => {
      if (props.connection.removeEventListener && message.mid) {
        props.connection.removeEventListener('msg', onReply);
      }
    };
  }, [props.connection, message.mid, onReply]);

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

/**
 * @type React.CSSProperties
 */
const linkStyle = {
  cursor: 'pointer'
};