File size: 1,481 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { formatNumber } from '@automattic/number-formatters';
import PropTypes from 'prop-types';
import { useLayoutEffect, useState } from 'react';
import Label from './label';

const ModuleChartXAxis = ( { data, isRtl, labelWidth, chartWidth } ) => {
	const dataCount = data.length || 1;
	const [ spacing, setSpacing ] = useState( labelWidth );
	const [ divisor, setDivisor ] = useState( 1 );

	useLayoutEffect( () => {
		const resize = () => {
			const width = chartWidth;
			const newSpacing = width / dataCount;

			setSpacing( newSpacing );
			setDivisor( Math.ceil( labelWidth / newSpacing ) );
		};

		resize();

		window.addEventListener( 'resize', resize );

		return () => {
			window.removeEventListener( 'resize', resize );
		};
	}, [ dataCount, labelWidth, chartWidth ] );

	const labels = data.map( function ( item, index ) {
		const x = index * spacing + ( spacing - labelWidth ) / 2;
		const rightIndex = data.length - index - 1;
		let label;

		if ( rightIndex % divisor === 0 ) {
			label = (
				<Label isRtl={ isRtl } key={ index } label={ item.label } width={ labelWidth } x={ x } />
			);
		}

		return label;
	} );

	return (
		<div className="chart__x-axis">
			{ labels }
			<div className="chart__x-axis-label chart__x-axis-width-spacer">{ formatNumber( 1e5 ) }</div>
		</div>
	);
};

ModuleChartXAxis.propTypes = {
	data: PropTypes.array.isRequired,
	isRtl: PropTypes.bool,
	labelWidth: PropTypes.number.isRequired,
};

export default ModuleChartXAxis;