-
Notifications
You must be signed in to change notification settings - Fork 792
/
x-axis.jsx
93 lines (74 loc) · 2.1 KB
/
x-axis.jsx
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
/**
* External dependencies
*/
const React = require( 'react' ),
PropTypes = require( 'prop-types' ),
throttle = require( 'lodash/throttle' );
/**
* Internal dependencies
*/
const Label = require( './label' );
export default class ModuleChartXAxis extends React.Component {
static displayName = 'ModuleChartXAxis';
static propTypes = {
labelWidth: PropTypes.number.isRequired,
data: PropTypes.array.isRequired
};
state = {
divisor: 1,
spacing: this.props.labelWidth
};
// Add listener for window resize
componentDidMount() {
this.resizeThrottled = throttle( this.resize, 400 );
window.addEventListener( 'resize', this.resizeThrottled );
this.resize();
}
// Remove listener
componentWillUnmount() {
if ( this.resizeThrottled.cancel ) {
this.resizeThrottled.cancel();
}
window.removeEventListener( 'resize', this.resizeThrottled );
}
UNSAFE_componentWillReceiveProps( nextProps ) {
this.resize( nextProps );
}
resize = ( nextProps ) => {
let props = this.props;
const node = this.refs.axis;
if ( nextProps && ! ( nextProps instanceof Event ) ) {
props = nextProps;
}
/**
* Overflow needs to be hidden to calculate the desired width,
* but visible to display each labels' overflow :/
*/
node.style.overflow = 'hidden';
const width = node.clientWidth;
node.style.overflow = 'visible';
const dataCount = props.data.length || 1;
const spacing = width / dataCount;
const labelWidth = props.labelWidth;
const divisor = Math.ceil( labelWidth / spacing );
this.setState( {
divisor: divisor,
spacing: spacing
} );
};
render() {
const data = this.props.data;
const labels = data.map( function( item, index ) {
const x = ( index * this.state.spacing ) + ( ( this.state.spacing - this.props.labelWidth ) / 2 );
const rightIndex = data.length - index - 1;
let label;
if ( rightIndex % this.state.divisor === 0 ) {
label = <Label key={ index } label={ item.label } width={ this.props.labelWidth } x={ x } />;
}
return label;
}, this );
return (
<div ref="axis" className="dops-chart__x-axis">{ labels }</div>
);
}
}