-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSingleChatContainer.js
405 lines (387 loc) · 12 KB
/
SingleChatContainer.js
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import React, { useEffect, useState, Fragment, useRef, useContext } from 'react'
import NProgress from 'nprogress'
import { Mutation, withApollo } from 'react-apollo'
import { useMutation } from 'react-apollo-hooks'
import Router, { withRouter } from 'next/router'
import moment from 'moment'
import gql from 'graphql-tag'
import { ChatCtx } from './ConvoContainer'
import { withStyles, ButtonBase, Tooltip } from '@material-ui/core'
import Verify from './verifyPhone'
import styles from '../static/jss/material-kit-pro-react/views/componentsSections/javascriptStyles.jsx'
import Button from '../styledComponents/CustomButtons/Button'
import CustomInput from '../styledComponents/CustomInput/CustomInput.jsx'
import Media from '../styledComponents/Media/Media.jsx'
import { Send } from '@material-ui/icons'
import TextareaAutosize from 'react-autosize-textarea'
import scrollbar from '../static/jss/ScrollbarStyles'
import date from '../utils/formatDate'
const TOGGLE_TYPING_MUTATION = gql`
mutation TOGGLE_TYPING_MUTATION($chatId: String!, $isTyping: Boolean!) {
toggleTyping(chatId: $chatId, isTyping: $isTyping) {
typing {
id
firstName
}
}
}
`
const SEND_MESSAGE_MUTATION = gql`
mutation SEND_MESSAGE_MUTATION($id: String!, $message: String!) {
sendMessage(id: $id, message: $message) {
id
users {
id
firstName
img {
id
img_url
default
}
}
messages {
id
text
seen
createdAt
from {
id
firstName
img {
id
img_url
default
}
}
updatedAt
}
}
}
`
const MARK_SEEN = gql`
mutation MARK_SEEN($chatId: String!) {
markAllAsSeen(chatId: $chatId) {
id
}
}
`
const REMAINING_MESSAGES = gql`
query {
remainingMessages
}
`
const ChatContainer = ({ classes, client, router, small }) => {
const { chat, currentUser } = useContext(ChatCtx)
const [message, setMessage] = useState('')
const msgRef = useRef(null)
const pageRef = useRef(null)
const [error, setError] = useState(null)
const markAllAsSeen = useMutation(MARK_SEEN)
const [isTyping, setIsTyping] = useState(false)
const toggleTyping = useMutation(TOGGLE_TYPING_MUTATION)
useEffect(() => {
// if (!currentUser.verified) {
// setError({
// msg: 'You must verify your account before you can send messages!',
// link: null,
// linkText: 'Verify now?',
// });
// } else
if (currentUser.permissions === 'FREE') {
getRemainingMessages()
}
}, [])
useEffect(() => {
if (chat) {
return () => {
setMessage('')
toggleTyping({
variables: {
chatId: chat.id,
isTyping: false
}
})
}
} else {
return () => {
setMessage('')
}
}
}, [chat && chat.id])
useEffect(() => {
if (msgRef.current) {
msgRef.current.focus()
}
if (pageRef.current) {
pageRef.current.scrollTop = pageRef.current.scrollHeight
}
}, [chat])
useEffect(() => {
if (chat && isTyping && !message.trim()) {
toggleTyping({
variables: {
chatId: chat.id,
isTyping: false
}
})
setIsTyping(false)
}
if (chat && !isTyping && message.trim()) {
toggleTyping({
variables: {
chatId: chat.id,
isTyping: true
}
})
setIsTyping(true)
}
}, [message])
useEffect(() => {
const unSeen = chat && chat.messages.filter(msg => !msg.seen && msg.from.id !== currentUser.id)
if (unSeen && unSeen.length > 0) {
markAllAsSeen({
variables: {
chatId: chat.id
}
})
}
})
const getRemainingMessages = async () => {
let messagesRemaining = await client.query({
query: REMAINING_MESSAGES,
fetchPolicy: 'no-cache'
})
if (messagesRemaining.data.remainingMessages === 0) {
setError({
msg: 'You are out of weekly messages allowed on a free account!',
link: '/profile/billing',
linkText: 'Go Pro?'
})
}
}
let friend
if (chat) {
friend = chat.users.find(user => user.id !== currentUser.id)
}
function groupByUser(messages) {
const grouped = []
let fromSameUser = [messages[0]]
let user = messages[0].from.id
for (let i = 1; i < messages.length; i++) {
if (messages[i].from.id !== user) {
grouped.push(fromSameUser)
fromSameUser = [messages[i]]
user = messages[i].from.id
} else {
fromSameUser.push(messages[i])
}
}
grouped.push(fromSameUser)
return grouped
}
let messages = chat && chat.messages.length ? groupByUser(chat.messages) : null
let lastSeenMessage = chat
? [...chat.messages].reverse().find(x => x.from.id === currentUser.id && x.seen)
: null
return (
<Fragment>
<div className={small ? classes.smallMessageList : classes.messageList} ref={pageRef}>
{chat &&
messages.map(msg => {
let fromMatch = msg[0].from.id !== currentUser.id
const img = msg[0].from.img.find(x => x.default).img_url
return (
<Media
currentUser={!fromMatch}
key={msg[0].id}
avatar={img}
small={small}
avatarClick={() =>
fromMatch
? Router.push(
{
pathname: router.pathname === '/' ? '/home' : router.pathname,
query: {
slug: router.query.slug,
user: friend.id
}
},
router.query.slug
? `${router.pathname}/${router.query.slug}/user/${friend.id}`
: router.pathname === '/'
? `/user/${friend.id}`
: `${router.pathname}/user/${friend.id}`,
{ shallow: true },
{ scroll: false }
)
: null
}
title={<span style={{ color: '#fafafa' }}>{msg[0].from.firstName}</span>}
body={
<span>
{msg.map((m, i) => {
return (
<div key={m.id}>
<div
style={{
display: 'inline-flex',
alignItems: 'center',
flexDirection: fromMatch ? 'row' : 'row-reverse'
}}
>
<Tooltip
title={moment(m.createdAt).format('MMM Do h:mm a')}
placement={fromMatch ? 'bottom-start' : 'bottom-end'}
>
<p
style={{
wordBreak: 'break-word',
fontSize: small ? '13px' : '14px',
cursor: 'default',
marginBottom: small ? '2px' : '10px'
}}
>
{m.text}
</p>
</Tooltip>
<small
style={{
marginBottom: '10px',
marginLeft: '5px',
marginRight: '5px',
display: 'none'
}}
>
{' '}
{date(msg.createdAt)}
</small>
</div>
{currentUser.permissions !== 'FREE' &&
!fromMatch &&
lastSeenMessage &&
lastSeenMessage.id === m.id ? (
<div>
<small>
<span style={{ marginRight: '2px' }}>seen</span>
{date(lastSeenMessage.updatedAt)}
</small>
</div>
) : null}
</div>
)
})}
</span>
}
/>
)
})}
</div>
{chat && (
<Mutation
mutation={SEND_MESSAGE_MUTATION}
variables={{ id: friend.id, message }}
onCompleted={() => {
NProgress.done()
if (currentUser.permissions === 'FREE') {
getRemainingMessages()
}
}}
onError={e => {
NProgress.done()
// e.message.includes('free')
// ? setError({
// msg: 'You are out of weekly messages allowed on a free account!',
// link: '/profile/billing',
// linkText: 'Go Pro?',
// })
// : null;
}}
>
{sendMessage =>
error ? (
!error.link ? (
<Verify />
) : (
<div>
<h4>{error.msg}</h4>
<Button onClick={() => Router.push(error.link)}>{error.linkText}</Button>
</div>
)
) : (
<form
className={small ? classes.smallExpanded : classes.expandedChat}
onSubmit={e => {
e.preventDefault()
NProgress.start()
sendMessage()
setMessage('')
}}
>
{/* <CustomInput
id='logged'
formControlProps={{
fullWidth: true,
}}
inputProps={{
multiline: true,
rows: '3',
// rows: Math.ceil(message.length / 60),
placeholder: `Respond to ${friend.firstName}`,
value: message,
onChange: e => setMessage(e.target.value),
style: { color: '#fafafa', width: '80%' },
}}
/> */}
<TextareaAutosize
className={classes.textareaAutosize}
onChange={e => {
setMessage(e.target.value)
}}
ref={msgRef}
placehotruncatelder={`Respond to ${friend.firstName}`}
rows={1}
maxRows={4}
value={message}
onKeyDown={e => {
if (e.keyCode === 13) {
sendMessage()
setMessage('')
}
}}
/>
<ButtonBase
type="submit"
style={{ marginLeft: small && '12px', marginRight: small && '5px' }}
>
<Button
style={{
background: 'transparent',
borderRadius: '6px !important',
width: small && '24px',
height: small && '24px',
minWidth: small && '33px',
marginRight: small && '2px'
}}
justIcon
className={classes.floatRight}
component="div"
>
<Send />
</Button>
</ButtonBase>
</form>
)
}
</Mutation>
)}
{chat && (
<div>
{chat.typing.find(user => user.firstName === friend.firstName)
? `${friend.firstName} is typing...`
: ''}
</div>
)}
</Fragment>
)
}
export default withRouter(withApollo(withStyles(styles)(ChatContainer)))