File size: 2,314 Bytes
8fd7a1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/*
 * Attempts to balance the length of each line of wrapped text.
 * If the text does not wrap, this component will have no effect.
 * See https://developer.chrome.com/blog/css-text-wrap-balance/
 * Patterned after `react-balance-text` with adjustments to support our method of styling.
 * We may want to replace this with react-wrap-balancer once we use React >= 16.8
 */

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

import balanceText from 'balance-text';
import bindAll from 'lodash.bindall';

class BalancedText extends React.Component {
    constructor (props) {
        super(props);
        bindAll(this, [
            'balanceText',
            'handleResize'
        ]);
        this.state = {
            forceHide: true
        };
    }

    componentDidMount () {
        self.addEventListener('resize', this.handleResize);
        this.stopHiding();
    }

    componentDidUpdate () {
        this.balanceText();
    }

    componentWillUnmount () {
        self.removeEventListener('resize', this.handleResize);
    }

    handleResize () {
        if (this.props.resize) {
            this.balanceText();
        }
    }

    balanceText () {
        const {container} = this;
        if (container) {
            balanceText(container, {});
        }
    }

    stopHiding () {
        this.setState({forceHide: false});
        setTimeout(() => this.balanceText(), 0);
    }

    render () {
        let {
            children,
            resize, // eslint-disable-line no-unused-vars
            style,
            ...otherProps
        } = this.props;

        if (this.state.forceHide) {
            style = Object.assign({}, style, {visibility: 'hidden'});
        }

        return (
            <div
                {...otherProps}
                style={style}
            >
                <span
                    ref={container => {
                        this.container = container;
                    }}
                >
                    {children}
                </span>
            </div>
        );
    }
}

BalancedText.propTypes = {
    children: PropTypes.node,
    resize: PropTypes.bool,
    style: PropTypes.object // eslint-disable-line react/forbid-prop-types
};

BalancedText.defaultProps = {
    resize: true
};

export default BalancedText;