File size: 9,605 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// @flow
import * as React from 'react';
import { btoa } from 'b2a';
import compose from 'recompose/compose';
import { connect } from 'react-redux';
import type { Dispatch } from 'redux';
import { withRouter, type Location, type History } from 'react-router';
import queryString from 'query-string';
import Clipboard from 'react-clipboard.js';
import { openGallery } from 'src/actions/gallery';
import Tooltip from 'src/components/tooltip';
import Reaction from 'src/components/reaction';
import { ReactionWrapper } from 'src/components//reaction/style';
import OutsideClickHandler from 'src/components/outsideClickHandler';
import { Body } from './view';
import { openModal } from 'src/actions/modals';
import { CLIENT_URL } from 'src/api/constants';
import type { MessageInfoType } from 'shared/graphql/fragments/message/messageInfo';
import type { UserInfoType } from 'shared/graphql/fragments/user/userInfo';
import { withCurrentUser } from 'src/components/withCurrentUser';
import { UserAvatar } from 'src/components/avatar';
import AuthorByline from './authorByline';
import Icon from 'src/components/icon';
import { addToastWithTimeout } from 'src/actions/toasts';
import {
  convertTimestampToTime,
  convertTimestampToDate,
} from 'shared/time-formatting';
import ConditionalWrap from 'src/components/conditionalWrap';
import {
  OuterMessageContainer,
  InnerMessageContainer,
  GutterContainer,
  GutterTimestamp,
  AuthorAvatarContainer,
  ActionsContainer,
  Actions,
  Action,
  EditedIndicator,
} from './style';
import getThreadLink from 'src/helpers/get-thread-link';
import type { GetThreadType } from 'shared/graphql/queries/thread/getThread';
import deleteMessage from 'shared/graphql/mutations/message/deleteMessage';
import { deleteMessageWithToast } from 'src/components/modals/DeleteDoubleCheckModal';

type Props = {|
  me: boolean,
  showAuthorContext: boolean,
  message: MessageInfoType,
  canModerateMessage: boolean,
  thread: GetThreadType,
  threadType: 'directMessageThread' | 'story',
  location: Location,
  history: History,
  dispatch: Dispatch<Object>,
  currentUser: UserInfoType,
  deleteMessage: Function,
|};

class Message extends React.Component<Props> {
  wrapperRef: React$Node;

  setWrapperRef = (node: React$Node) => {
    this.wrapperRef = node;
  };

  shouldComponentUpdate(nextProps) {
    const newMessage = nextProps.message.id !== this.props.message.id;
    const updatedReactionCount =
      nextProps.message.reactions.count !== this.props.message.reactions.count;
    const updatedReactionState =
      nextProps.message.reactions.hasReacted !==
      this.props.message.reactions.hasReacted;

    if (newMessage || updatedReactionCount || updatedReactionState) {
      return true;
    }

    return false;
  }

  toggleOpenGallery = (e: any, selectedMessageId: string) => {
    e.stopPropagation();

    const { thread } = this.props;
    this.props.dispatch(openGallery(thread.id, selectedMessageId));
  };

  deleteMessage = (e: any) => {
    e.stopPropagation();

    if (e.shiftKey) {
      // If Shift key is pressed, we assume confirmation
      return deleteMessageWithToast(
        this.props.dispatch,
        this.props.deleteMessage,
        this.props.message.id
      );
    }

    const message = 'Are you sure you want to delete this message?';

    return this.props.dispatch(
      openModal('DELETE_DOUBLE_CHECK_MODAL', {
        id: this.props.message.id,
        entity: 'message',
        message,
        threadType: this.props.threadType,
        threadId: this.props.thread.id,
      })
    );
  };

  // prettier-ignore
  handleSelectMessage = (e: any, selectMessage: Function,	messageId: string) => {
    // $FlowFixMe
    if (window && window.innerWidth < 768 && this.wrapperRef && this.wrapperRef.contains(e.target)) {
      e.stopPropagation();
      return selectMessage(messageId);
    }
  };

  clearSelectedMessage = () => {
    const { history, location } = this.props;
    const { pathname } = location;
    history.push({ pathname });
  };

  render() {
    const {
      showAuthorContext,
      me,
      currentUser,
      dispatch,
      message,
      canModerateMessage,
      thread,
      threadType,
      location,
    } = this.props;

    const selectedMessageId = btoa(new Date(message.timestamp).getTime() - 1);
    const messageUrl =
      threadType === 'story' && thread
        ? `${getThreadLink(thread)}?m=${selectedMessageId}`
        : threadType === 'directMessageThread'
        ? `/messages/${thread.id}?m=${selectedMessageId}`
        : `/thread/${thread.id}?m=${selectedMessageId}`;

    const searchObj = queryString.parse(location.search);
    const { m = null } = searchObj;
    const isSelected = m && m === selectedMessageId;
    const isOptimistic =
      message && typeof message.id === 'number' && message.id < 0;
    return (
      <ConditionalWrap
        condition={!!isSelected}
        wrap={children => (
          <OutsideClickHandler
            onOutsideClick={this.clearSelectedMessage}
            style={{ width: '100%' }}
          >
            {children}
          </OutsideClickHandler>
        )}
      >
        <OuterMessageContainer
          data-cy={isSelected ? 'message-selected' : 'message'}
          selected={isSelected}
          ref={this.setWrapperRef}
          tabIndex={0}
        >
          <GutterContainer>
            {showAuthorContext ? (
              <AuthorAvatarContainer onClick={e => e.stopPropagation()}>
                <UserAvatar user={message.author.user} size={40} />
              </AuthorAvatarContainer>
            ) : (
              <GutterTimestamp to={messageUrl}>
                {convertTimestampToTime(new Date(message.timestamp))}
              </GutterTimestamp>
            )}
          </GutterContainer>

          <InnerMessageContainer>
            {showAuthorContext && (
              <AuthorByline
                timestamp={message.timestamp}
                user={message.author.user}
                roles={message.author.roles}
                bot={message.bot}
                messageUrl={messageUrl}
              />
            )}

            <Body
              me={me}
              openGallery={e => this.toggleOpenGallery(e, message.id)}
              message={message}
            />

            {message.modifiedAt && (
              <Tooltip
                content={`Edited ${convertTimestampToDate(
                  new Date(message.modifiedAt)
                )}`}
              >
                <EditedIndicator data-cy="edited-message-indicator">
                  Edited
                </EditedIndicator>
              </Tooltip>
            )}

            {message.reactions.count > 0 && (
              <Reaction
                message={message}
                me={me}
                currentUser={currentUser}
                dispatch={dispatch}
                render={({ me, count, hasReacted }) => (
                  <ReactionWrapper
                    hasCount={count}
                    hasReacted={hasReacted}
                    me={me}
                  >
                    <Icon
                      data-cy={
                        hasReacted
                          ? 'inline-unlike-action'
                          : 'inline-like-action'
                      }
                      glyph="like-fill"
                      size={16}
                      color={'text.reverse'}
                    />
                    <span>{count}</span>
                  </ReactionWrapper>
                )}
              />
            )}

            {!isOptimistic && (
              <ActionsContainer>
                <Actions>
                  {canModerateMessage && (
                    <Tooltip content={'Delete'}>
                      <Action onClick={this.deleteMessage}>
                        <Icon
                          data-cy="delete-message"
                          glyph="delete"
                          size={20}
                        />
                      </Action>
                    </Tooltip>
                  )}

                  {threadType === 'story' && (
                    <Clipboard
                      style={{
                        background: 'none',
                      }}
                      data-clipboard-text={
                        thread
                          ? `${CLIENT_URL}${getThreadLink(
                              thread
                            )}?m=${selectedMessageId}`
                          : `${CLIENT_URL}/thread/${
                              thread.id
                            }?m=${selectedMessageId}`
                      }
                      onSuccess={() =>
                        this.props.dispatch(
                          addToastWithTimeout('success', 'Copied to clipboard')
                        )
                      }
                    >
                      <Tooltip content={'Link to message'}>
                        <Action>
                          <Icon
                            data-cy="link-to-message"
                            glyph="link"
                            size={20}
                          />
                        </Action>
                      </Tooltip>
                    </Clipboard>
                  )}
                </Actions>
              </ActionsContainer>
            )}
          </InnerMessageContainer>
        </OuterMessageContainer>
      </ConditionalWrap>
    );
  }
}

export default compose(
  deleteMessage,
  withCurrentUser,
  withRouter,
  connect()
)(Message);