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

import Constants from 'utils/constants.jsx';

const TYPE_POST = 'post';
const TYPE_COMMENT = 'comment';

class MessageHistoryStoreClass {
    constructor() {
        this.messageHistory = [];
        this.index = [];
        this.index[TYPE_POST] = 0;
        this.index[TYPE_COMMENT] = 0;
    }

    getMessageInHistory(type) {
        if (this.index[type] >= this.messageHistory.length) {
            return '';
        } else if (this.index[type] < 0) {
            return null;
        }

        return this.messageHistory[this.index[type]];
    }

    getHistoryLength() {
        if (this.messageHistory === null) {
            return 0;
        }
        return this.messageHistory.length;
    }

    storeMessageInHistory(message) {
        this.messageHistory.push(message);
        this.resetAllHistoryIndex();
        if (this.messageHistory.length > Constants.MAX_PREV_MSGS) {
            this.messageHistory = this.messageHistory.slice(1, Constants.MAX_PREV_MSGS + 1);
        }
    }

    storeMessageInHistoryByIndex(index, message) {
        this.messageHistory[index] = message;
    }

    resetAllHistoryIndex() {
        this.index[TYPE_POST] = this.messageHistory.length;
        this.index[TYPE_COMMENT] = this.messageHistory.length;
    }

    resetHistoryIndex(type) {
        this.index[type] = this.messageHistory.length;
    }

    nextMessageInHistory(keyCode, messageText, type) {
        if (messageText !== '' && messageText !== this.getMessageInHistory(type)) {
            return null;
        }

        if (keyCode === Constants.KeyCodes.UP) {
            this.index[type]--;
        } else if (keyCode === Constants.KeyCodes.DOWN) {
            this.index[type]++;
        }

        if (this.index[type] < 0) {
            this.index[type] = 0;
            return null;
        } else if (this.index[type] >= this.getHistoryLength()) {
            this.index[type] = this.getHistoryLength();
        }

        return this.getMessageInHistory(type);
    }
}

var MessageHistoryStore = new MessageHistoryStoreClass();

export default MessageHistoryStore;