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

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

import {postListScrollChange} from 'actions/global_actions.jsx';

const WAIT_FOR_HEIGHT_TIMEOUT = 100;

export default class MarkdownImage extends React.PureComponent {
    static propTypes = {

        /*
         * The href of the image to be loaded
         */
        href: PropTypes.string
    }

    constructor(props) {
        super(props);

        this.heightTimeout = 0;
    }

    componentDidMount() {
        this.waitForHeight();
    }

    componentDidUpdate(prevProps) {
        if (this.props.href !== prevProps.href) {
            this.waitForHeight();
        }
    }

    componentWillUnmount() {
        this.stopWaitingForHeight();
    }

    waitForHeight = () => {
        if (this.refs.image.height) {
            setTimeout(postListScrollChange, 0);

            this.heightTimeout = 0;
        } else {
            this.heightTimeout = setTimeout(this.waitForHeight, WAIT_FOR_HEIGHT_TIMEOUT);
        }
    }

    stopWaitingForHeight = () => {
        if (this.heightTimeout !== 0) {
            clearTimeout(this.heightTimeout);
            this.heightTimeout = 0;
        }
    }

    render() {
        return (
            <img
                {...this.props}
                ref='image'
                onLoad={this.stopWaitingForHeight}
                onError={this.stopWaitingForHeight}
            />
        );
    }
}