summaryrefslogtreecommitdiffstats
path: root/webapp/components/at_mention/at_mention.jsx
blob: 760884b88e831d8a69c512f631ef6570ea84c736 (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) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

import React from 'react';
import PropTypes from 'prop-types';

export default class AtMention extends React.PureComponent {
    static propTypes = {
        mentionName: PropTypes.string.isRequired,
        usersByUsername: PropTypes.object.isRequired,
        actions: PropTypes.shape({
            searchForTerm: PropTypes.func.isRequired
        }).isRequired
    };

    constructor(props) {
        super(props);

        this.state = {
            username: this.getUsernameFromMentionName(props)
        };
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.mentionName !== this.props.mentionName || nextProps.usersByUsername !== this.props.usersByUsername) {
            this.setState({
                username: this.getUsernameFromMentionName(nextProps)
            });
        }
    }

    getUsernameFromMentionName(props) {
        let mentionName = props.mentionName;

        while (mentionName.length > 0) {
            if (props.usersByUsername[mentionName]) {
                return props.usersByUsername[mentionName].username;
            }

            // Repeatedly trim off trailing punctuation in case this is at the end of a sentence
            if ((/[._-]$/).test(mentionName)) {
                mentionName = mentionName.substring(0, mentionName.length - 1);
            } else {
                break;
            }
        }

        return '';
    }

    search = (e) => {
        e.preventDefault();

        this.props.actions.searchForTerm(this.state.username);
    }

    render() {
        const username = this.state.username;

        if (!username) {
            return <span>{'@' + this.props.mentionName}</span>;
        }

        const suffix = this.props.mentionName.substring(username.length);

        return (
            <span>
                <a
                    className='mention-link'
                    href='#'
                    onClick={this.search}
                >
                    {'@' + username}
                </a>
                {suffix}
            </span>
        );
    }
}