summaryrefslogtreecommitdiffstats
path: root/web/react/components/post_list.jsx
blob: 5be58704b3654d12408bc59efec119d5d9b8c356 (plain)
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

var PostStore = require('../stores/post_store.jsx');
var ChannelStore = require('../stores/channel_store.jsx');
var UserStore = require('../stores/user_store.jsx');
var UserProfile = require('./user_profile.jsx');
var AsyncClient = require('../utils/async_client.jsx');
var Post = require('./post.jsx');
var LoadingScreen = require('./loading_screen.jsx');
var SocketStore = require('../stores/socket_store.jsx');
var utils = require('../utils/utils.jsx');
var Client = require('../utils/client.jsx');
var AppDispatcher = require('../dispatcher/app_dispatcher.jsx');
var Constants = require('../utils/constants.jsx');
var ActionTypes = Constants.ActionTypes;

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

        this.gotMorePosts = false;
        this.scrolled = false;
        this.prevScrollTop = 0;
        this.seenNewMessages = false;
        this.isUserScroll = true;
        this.userHasSeenNew = false;
        this.loadInProgress = false;

        this.onChange = this.onChange.bind(this);
        this.onTimeChange = this.onTimeChange.bind(this);
        this.onSocketChange = this.onSocketChange.bind(this);
        this.createChannelIntroMessage = this.createChannelIntroMessage.bind(this);
        this.loadMorePosts = this.loadMorePosts.bind(this);
        this.loadFirstPosts = this.loadFirstPosts.bind(this);
        this.activate = this.activate.bind(this);
        this.deactivate = this.deactivate.bind(this);
        this.resize = this.resize.bind(this);

        const state = this.getStateFromStores(props.channelId);
        state.numToDisplay = Constants.POST_CHUNK_SIZE;
        state.isFirstLoadComplete = false;

        this.state = state;
    }
    getStateFromStores(id) {
        var postList = PostStore.getPosts(id);

        if (postList != null) {
            var deletedPosts = PostStore.getUnseenDeletedPosts(id);

            if (deletedPosts && Object.keys(deletedPosts).length > 0) {
                for (var pid in deletedPosts) {
                    if (deletedPosts.hasOwnProperty(pid)) {
                        postList.posts[pid] = deletedPosts[pid];
                        postList.order.unshift(pid);
                    }
                }

                postList.order.sort(function postSort(a, b) {
                    if (postList.posts[a].create_at > postList.posts[b].create_at) {
                        return -1;
                    }
                    if (postList.posts[a].create_at < postList.posts[b].create_at) {
                        return 1;
                    }
                    return 0;
                });
            }

            var pendingPostList = PostStore.getPendingPosts(id);

            if (pendingPostList) {
                postList.order = pendingPostList.order.concat(postList.order);
                for (var ppid in pendingPostList.posts) {
                    if (pendingPostList.posts.hasOwnProperty(ppid)) {
                        postList.posts[ppid] = pendingPostList.posts[ppid];
                    }
                }
            }
        }

        return {
            postList: postList
        };
    }
    componentDidMount() {
        window.onload = () => this.scrollToBottom();
        if (this.props.isActive) {
            this.activate();
            this.loadFirstPosts(this.props.channelId);
        }
    }
    componentWillUnmount() {
        this.deactivate();
    }
    activate() {
        this.gotMorePosts = false;
        this.scrolled = false;
        this.prevScrollTop = 0;
        this.seenNewMessages = false;
        this.isUserScroll = true;
        this.userHasSeenNew = false;

        PostStore.clearUnseenDeletedPosts(this.props.channelId);
        PostStore.addChangeListener(this.onChange);
        UserStore.addStatusesChangeListener(this.onTimeChange);
        SocketStore.addChangeListener(this.onSocketChange);

        const postHolder = $(React.findDOMNode(this.refs.postlist));

        $(window).resize(() => {
            this.resize();
            if (!this.scrolled) {
                this.scrollToBottom();
            }
        });

        postHolder.on('scroll', () => {
            const position = postHolder.scrollTop() + postHolder.height() + 14;
            const bottom = postHolder[0].scrollHeight;

            if (position >= bottom) {
                this.scrolled = false;
            } else {
                this.scrolled = true;
            }

            if (this.isUserScroll) {
                this.userHasSeenNew = true;
            }
            this.isUserScroll = true;

            $('.top-visible-post').removeClass('top-visible-post');

            $(React.findDOMNode(this.refs.postlistcontent)).children().each(function select() {
                if ($(this).position().top + $(this).height() / 2 > 0) {
                    $(this).addClass('top-visible-post');
                    return false;
                }
            });
        });

        $('.post-list__content div .post').removeClass('post--last');
        $('.post-list__content div:last-child .post').addClass('post--last');

        if (!this.state.isFirstLoadComplete) {
            this.loadFirstPosts(this.props.channelId);
        }

        this.resize();
        this.onChange();
        this.scrollToBottom();
    }
    deactivate() {
        PostStore.removeChangeListener(this.onChange);
        UserStore.removeStatusesChangeListener(this.onTimeChange);
        SocketStore.removeChangeListener(this.onSocketChange);
        $('body').off('click.userpopover');
        $(window).off('resize');
        var postHolder = $(React.findDOMNode(this.refs.postlist));
        postHolder.off('scroll');
    }
    componentDidUpdate(prevProps, prevState) {
        if (!this.props.isActive) {
            return;
        }

        $('.post-list__content div .post').removeClass('post--last');
        $('.post-list__content div:last-child .post').addClass('post--last');

        if (this.state.postList == null || prevState.postList == null) {
            this.scrollToBottom();
            return;
        }

        var order = this.state.postList.order || [];
        var posts = this.state.postList.posts || {};
        var oldOrder = prevState.postList.order || [];
        var oldPosts = prevState.postList.posts || {};
        var userId = UserStore.getCurrentId();
        var firstPost = posts[order[0]] || {};
        var isNewPost = oldOrder.indexOf(order[0]) === -1;

        if (this.props.isActive && !prevProps.isActive) {
            this.scrollToBottom();
        } else if (oldOrder.length === 0) {
            this.scrollToBottom();

        // the user is scrolled to the bottom
        } else if (!this.scrolled) {
            this.scrollToBottom();

        // there's a new post and
        // it's by the user and not a comment
        } else if (isNewPost &&
                    userId === firstPost.user_id &&
                    !utils.isComment(firstPost)) {
            this.scrollToBottom(true);

        // the user clicked 'load more messages'
        } else if (this.gotMorePosts && oldOrder.length > 0) {
            let index;
            if (prevState.numToDisplay >= oldOrder.length) {
                index = oldOrder.length - 1;
            } else {
                index = prevState.numToDisplay;
            }
            const lastPost = oldPosts[oldOrder[index]];
            $('#post_' + lastPost.id)[0].scrollIntoView();
            this.gotMorePosts = false;
        } else {
            this.scrollTo(this.prevScrollTop);
        }
    }
    componentWillUpdate() {
        var postHolder = $(React.findDOMNode(this.refs.postlist));
        this.prevScrollTop = postHolder.scrollTop();
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps.isActive === true && this.props.isActive === false) {
            this.activate();
        } else if (nextProps.isActive === false && this.props.isActive === true) {
            this.deactivate();
        }
    }
    resize() {
        const postHolder = $(React.findDOMNode(this.refs.postlist));
        if ($('#create_post').length > 0) {
            const height = $(window).height() - $('#create_post').height() - $('#error_bar').outerHeight() - 50;
            postHolder.css('height', height + 'px');
        }
    }
    scrollTo(val) {
        this.isUserScroll = false;
        var postHolder = $(React.findDOMNode(this.refs.postlist));
        postHolder[0].scrollTop = val;
    }
    scrollToBottom(force) {
        this.isUserScroll = false;
        var postHolder = $(React.findDOMNode(this.refs.postlist));
        if ($('#new_message_' + this.props.channelId)[0] && !this.userHasSeenNew && !force) {
            $('#new_message_' + this.props.channelId)[0].scrollIntoView();
        } else {
            postHolder.addClass('hide-scroll');
            postHolder[0].scrollTop = postHolder[0].scrollHeight;
            postHolder.removeClass('hide-scroll');
        }
    }
    loadFirstPosts(id) {
        if (this.loadInProgress) {
            return;
        }

        if (this.props.channelId == null) {
            return;
        }

        this.loadInProgress = true;
        Client.getPosts(
            id,
            PostStore.getLatestUpdate(id),
            function success() {
                this.loadInProgress = false;
                this.setState({isFirstLoadComplete: true});
            }.bind(this),
            function fail() {
                this.loadInProgress = false;
                this.setState({isFirstLoadComplete: true});
            }.bind(this)
        );
    }
    onChange() {
        var newState = this.getStateFromStores(this.props.channelId);

        if (!utils.areStatesEqual(newState.postList, this.state.postList)) {
            this.setState(newState);
        }
    }
    onSocketChange(msg) {
        var post;
        if (msg.action === 'posted' || msg.action === 'post_edited') {
            post = JSON.parse(msg.props.post);
            PostStore.storePost(post);
        } else if (msg.action === 'post_deleted') {
            var activeRoot = $(document.activeElement).closest('.comment-create-body')[0];
            var activeRootPostId = '';
            if (activeRoot && activeRoot.id.length > 0) {
                activeRootPostId = activeRoot.id;
            }

            post = JSON.parse(msg.props.post);

            PostStore.storeUnseenDeletedPost(post);
            PostStore.removePost(post, true);
            PostStore.emitChange();

            if (activeRootPostId === msg.props.post_id && UserStore.getCurrentId() !== msg.user_id) {
                $('#post_deleted').modal('show');
            }
        } else if (msg.action === 'new_user') {
            AsyncClient.getProfiles();
        }
    }
    onTimeChange() {
        if (!this.state.postList) {
            return;
        }

        for (var id in this.state.postList.posts) {
            if (!this.refs[id]) {
                continue;
            }
            this.refs[id].forceUpdateInfo();
        }
    }
    createDMIntroMessage(channel) {
        var teammate = utils.getDirectTeammate(channel.id);

        if (teammate) {
            var teammateName = teammate.username;
            if (teammate.nickname.length > 0) {
                teammateName = teammate.nickname;
            }

            return (
                <div className='channel-intro'>
                    <div className='post-profile-img__container channel-intro-img'>
                        <img
                            className='post-profile-img'
                            src={'/api/v1/users/' + teammate.id + '/image?time=' + teammate.update_at}
                            height='50'
                            width='50'
                        />
                    </div>
                    <div className='channel-intro-profile'>
                        <strong><UserProfile userId={teammate.id} /></strong>
                    </div>
                    <p className='channel-intro-text'>
                        {'This is the start of your direct message history with ' + teammateName + '.'}<br/>
                        {'Direct messages and files shared here are not shown to people outside this area.'}
                    </p>
                    <a
                        className='intro-links'
                        href='#'
                        data-toggle='modal'
                        data-target='#edit_channel'
                        data-desc={channel.description}
                        data-title={channel.display_name}
                        data-channelid={channel.id}
                    >
                        <i className='fa fa-pencil'></i>Set a description
                    </a>
                </div>
            );
        }

        return (
            <div className='channel-intro'>
                <p className='channel-intro-text'>{'This is the start of your direct message history with this teammate. Direct messages and files shared here are not shown to people outside this area.'}</p>
            </div>
        );
    }
    createChannelIntroMessage(channel) {
        if (channel.type === 'D') {
            return this.createDMIntroMessage(channel);
        } else if (ChannelStore.isDefault(channel)) {
            return this.createDefaultIntroMessage(channel);
        } else if (channel.name === Constants.OFFTOPIC_CHANNEL) {
            return this.createOffTopicIntroMessage(channel);
        } else if (channel.type === 'O' || channel.type === 'P') {
            return this.createStandardIntroMessage(channel);
        }
    }
    createDefaultIntroMessage(channel) {
        return (
            <div className='channel-intro'>
                <h4 className='channel-intro__title'>Beginning of {channel.display_name}</h4>
                <p className='channel-intro__content'>
                    Welcome to {channel.display_name}!
                    <br/><br/>
                    This is the first channel teammates see when they
                    <br/>
                    sign up - use it for posting updates everyone needs to know.
                    <br/><br/>
                    To create a new channel or join an existing one, go to
                    <br/>
                    the Left Hand Sidebar under “Channels” and click “More…”.
                    <br/>
                </p>
            </div>
        );
    }
    createOffTopicIntroMessage(channel) {
        return (
            <div className='channel-intro'>
                <h4 className='channel-intro__title'>Beginning of {channel.display_name}</h4>
                <p className='channel-intro__content'>
                    {'This is the start of ' + channel.display_name + ', a channel for non-work-related conversations.'}
                    <br/>
                </p>
                <a
                    className='intro-links'
                    href='#'
                    data-toggle='modal'
                    data-target='#edit_channel'
                    data-desc={channel.description}
                    data-title={channel.display_name}
                    data-channelid={channel.id}
                >
                    <i className='fa fa-pencil'></i>Set a description
                </a>
                <a
                    className='intro-links'
                    href='#'
                    data-toggle='modal'
                    data-target='#channel_invite'
                >
                    <i className='fa fa-user-plus'></i>Invite others to this channel
                </a>
            </div>
        );
    }
    getChannelCreator(channel) {
        if (channel.creator_id.length > 0) {
            var creator = UserStore.getProfile(channel.creator_id);
            if (creator) {
                return creator.username;
            }
        }

        var members = ChannelStore.getExtraInfo(channel.id).members;
        for (var i = 0; i < members.length; i++) {
            if (utils.isAdmin(members[i].roles)) {
                return members[i].username;
            }
        }
    }
    createStandardIntroMessage(channel) {
        var uiName = channel.display_name;
        var creatorName = '';

        var uiType;
        var memberMessage;
        if (channel.type === 'P') {
            uiType = 'private group';
            memberMessage = ' Only invited members can see this private group.';
        } else {
            uiType = 'channel';
            memberMessage = ' Any member can join and read this channel.';
        }

        var createMessage;
        if (creatorName === '') {
            createMessage = 'This is the start of the ' + uiName + ' ' + uiType + ', created on ' + utils.displayDate(channel.create_at) + '.';
        } else {
            createMessage = (<span>This is the start of the <strong>{uiName}</strong> {uiType}, created by <strong>{creatorName}</strong> on <strong>{utils.displayDate(channel.create_at)}</strong></span>);
        }

        return (
            <div className='channel-intro'>
                <h4 className='channel-intro__title'>Beginning of {uiName}</h4>
                <p className='channel-intro__content'>
                    {createMessage}
                    {memberMessage}
                    <br/>
                </p>
                <a
                    className='intro-links'
                    href='#'
                    data-toggle='modal'
                    data-target='#edit_channel'
                    data-desc={channel.description}
                    data-title={channel.display_name}
                    data-channelid={channel.id}
                >
                    <i className='fa fa-pencil'></i>Set a description
                </a>
                <a
                    className='intro-links'
                    href='#'
                    data-toggle='modal'
                    data-target='#channel_invite'
                >
                    <i className='fa fa-user-plus'></i>Invite others to this {uiType}
                </a>
            </div>
        );
    }
    createPosts(posts, order) {
        var postCtls = [];
        var previousPostDay = new Date(0);
        var userId = UserStore.getCurrentId();

        var renderedLastViewed = false;
        var lastViewed = Number.MAX_VALUE;

        if (ChannelStore.getMember(this.props.channelId) != null) {
            lastViewed = ChannelStore.getMember(this.props.channelId).last_viewed_at;
        }

        var numToDisplay = this.state.numToDisplay;
        if (order.length - 1 < numToDisplay) {
            numToDisplay = order.length - 1;
        }

        for (var i = numToDisplay; i >= 0; i--) {
            var post = posts[order[i]];
            var parentPost = posts[post.parent_id];

            var sameUser = false;
            var sameRoot = false;
            var hideProfilePic = false;
            var prevPost = posts[order[i + 1]];

            if (prevPost) {
                sameUser = prevPost.user_id === post.user_id && post.create_at - prevPost.create_at <= 1000 * 60 * 5;

                sameRoot = utils.isComment(post) && (prevPost.id === post.root_id || prevPost.root_id === post.root_id);

                // hide the profile pic if:
                //     the previous post was made by the same user as the current post,
                //     the previous post is not a comment,
                //     the current post is not a comment,
                //     the current post is not from a webhook
                //     and the previous post is not from a webhook
                if ((prevPost.user_id === post.user_id) &&
                        !utils.isComment(prevPost) &&
                        !utils.isComment(post) &&
                        (!post.props || !post.props.from_webhook) &&
                        (!prevPost.props || !prevPost.props.from_webhook)) {
                    hideProfilePic = true;
                }
            }

            // check if it's the last comment in a consecutive string of comments on the same post
            // it is the last comment if it is last post in the channel or the next post has a different root post
            var isLastComment = utils.isComment(post) && (i === 0 || posts[order[i - 1]].root_id !== post.root_id);

            var postCtl = (
                <Post
                    key={post.id + 'postKey'}
                    ref={post.id}
                    sameUser={sameUser}
                    sameRoot={sameRoot}
                    post={post}
                    parentPost={parentPost}
                    posts={posts}
                    hideProfilePic={hideProfilePic}
                    isLastComment={isLastComment}
                />
            );

            let currentPostDay = utils.getDateForUnixTicks(post.create_at);
            if (currentPostDay.toDateString() !== previousPostDay.toDateString()) {
                postCtls.push(
                    <div
                        key={currentPostDay.toDateString()}
                        className='date-separator'
                    >
                        <hr className='separator__hr' />
                        <div className='separator__text'>{currentPostDay.toDateString()}</div>
                    </div>
                );
            }

            if (post.user_id !== userId && post.create_at > lastViewed && !renderedLastViewed) {
                renderedLastViewed = true;

                // Temporary fix to solve ie10/11 rendering issue
                let newSeparatorId = '';
                if (!utils.isBrowserIE()) {
                    newSeparatorId = 'new_message_' + this.props.channelId;
                }
                postCtls.push(
                    <div
                        id={newSeparatorId}
                        key='unviewed'
                        className='new-separator'
                    >
                        <hr
                            className='separator__hr'
                        />
                        <div className='separator__text'>New Messages</div>
                    </div>
                );
            }
            postCtls.push(postCtl);
            previousPostDay = currentPostDay;
        }

        return postCtls;
    }
    loadMorePosts() {
        if (this.state.postList == null) {
            return;
        }

        var posts = this.state.postList.posts;
        var order = this.state.postList.order;
        var channelId = this.props.channelId;

        $(React.findDOMNode(this.refs.loadmore)).text('Retrieving more messages...');

        Client.getPostsPage(
            channelId,
            order.length,
            Constants.POST_CHUNK_SIZE,
            function success(data) {
                $(React.findDOMNode(this.refs.loadmore)).text('Load more messages');
                this.gotMorePosts = true;
                this.setState({numToDisplay: this.state.numToDisplay + Constants.POST_CHUNK_SIZE});

                if (!data) {
                    return;
                }

                if (data.order.length === 0) {
                    return;
                }

                var postList = {};
                postList.posts = $.extend(posts, data.posts);
                postList.order = order.concat(data.order);

                AppDispatcher.handleServerAction({
                    type: ActionTypes.RECIEVED_POSTS,
                    id: channelId,
                    post_list: postList
                });

                Client.getProfiles();
            }.bind(this),
            function fail(err) {
                $(React.findDOMNode(this.refs.loadmore)).text('Load more messages');
                AsyncClient.dispatchError(err, 'getPosts');
            }.bind(this)
        );
    }
    render() {
        var order = [];
        var posts;
        var channel = ChannelStore.get(this.props.channelId);

        if (this.state.postList != null) {
            posts = this.state.postList.posts;
            order = this.state.postList.order;
        }

        var moreMessages = <p className='beginning-messages-text'>Beginning of Channel</p>;
        if (channel != null) {
            if (order.length >= this.state.numToDisplay) {
                moreMessages = (
                    <a
                        ref='loadmore'
                        className='more-messages-text theme'
                        href='#'
                        onClick={this.loadMorePosts}
                    >
                            Load more messages
                    </a>
                );
            } else {
                moreMessages = this.createChannelIntroMessage(channel);
            }
        }

        var postCtls = [];
        if (posts && this.state.isFirstLoadComplete) {
            postCtls = this.createPosts(posts, order);
        } else {
            postCtls.push(
                <LoadingScreen
                    position='absolute'
                    key='loading'
                />);
        }

        var activeClass = '';
        if (!this.props.isActive) {
            activeClass = 'inactive';
        }

        return (
            <div
                ref='postlist'
                className={'post-list-holder-by-time ' + activeClass}
            >
                <div className='post-list__table'>
                    <div
                        ref='postlistcontent'
                        className='post-list__content'
                    >
                        {moreMessages}
                        {postCtls}
                    </div>
                </div>
            </div>
        );
    }
}

PostList.defaultProps = {
    isActive: false,
    channelId: null
};
PostList.propTypes = {
    isActive: React.PropTypes.bool,
    channelId: React.PropTypes.string
};