summaryrefslogtreecommitdiffstats
path: root/webapp/components/post_view/post_view_cache.jsx
blob: d7cb360d1f30cf38c9b66f72c568d8dd8a0d2f7e (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
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information

import PostViewController from './post_view_controller.jsx';

import ChannelStore from 'stores/channel_store.jsx';
import UserStore from 'stores/user_store.jsx';
import * as AsyncClient from 'utils/async_client.jsx';

import React from 'react';

const MAXIMUM_CACHED_VIEWS = 5;

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

        this.onChannelChange = this.onChannelChange.bind(this);

        const currentChannelId = ChannelStore.getCurrentId();
        const channel = ChannelStore.getCurrent();

        this.state = {
            currentChannelId,
            channels: channel ? [channel] : []
        };
    }

    componentDidMount() {
        ChannelStore.addChangeListener(this.onChannelChange);
    }

    componentWillUnmount() {
        if (UserStore.getCurrentUser()) {
            AsyncClient.viewChannel('', this.state.currentChannelId || '');
        }
        ChannelStore.removeChangeListener(this.onChannelChange);
    }

    onChannelChange() {
        const channels = Object.assign([], this.state.channels);
        const currentChannel = ChannelStore.getCurrent();

        if (!currentChannel) {
            return;
        }

        // make sure current channel really changed
        if (currentChannel.id === this.state.currentChannelId) {
            return;
        }

        if (channels.length > MAXIMUM_CACHED_VIEWS) {
            channels.shift();
        }

        const index = channels.map((c) => c.id).indexOf(currentChannel.id);
        if (index !== -1) {
            channels.splice(index, 1);
        }

        channels.push(currentChannel);

        this.setState({
            currentChannelId: currentChannel.id,
            channels
        });
    }

    render() {
        const channels = this.state.channels;
        const currentChannelId = this.state.currentChannelId;

        const postViews = [];
        for (let i = 0; i < channels.length; i++) {
            postViews.push(
                <PostViewController
                    key={'postviewcontroller_' + channels[i].id}
                    channel={channels[i]}
                    active={channels[i].id === currentChannelId}
                />
            );
        }

        return (
            <div id='post-list'>
                {postViews}
            </div>
        );
    }
}