File size: 7,802 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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import { Tooltip } from '@automattic/components';
import { formatNumber } from '@automattic/number-formatters';
import clsx from 'clsx';
import { localize, withRtl } from 'i18n-calypso';
import PropTypes from 'prop-types';
import { useState, useCallback, useMemo, useEffect } from 'react';
import Notice from 'calypso/components/notice';
import { hasTouch } from 'calypso/lib/touch-detect';
import { useWindowResizeCallback } from 'calypso/lib/track-element-size';
import BarContainer from './bar-container';
import './style.scss';

const isTouch = hasTouch();

/**
 * Auxiliary method to calculate the maximum value for the Y axis, based on a dataset.
 * @param {Array} values An array of numeric values.
 * @returns {number} The maximum value for the Y axis.
 */
function getYAxisMax( values ) {
	// Calculate max value in a dataset.
	const max = Math.max.apply( null, values );
	if ( 0 === max ) {
		return 2;
	}

	const log10 = Math.log10( max );
	const sign = Math.sign( log10 );

	// Magnitude of the number by a factor fo 10 (e.g. thousands, hundreds, tens, ones, tenths, hundredths, thousandths).
	const magnitude = Math.ceil( Math.abs( log10 ) ) * sign;

	// Determine the base unit size, based on the magnitude of the number.
	const unitSize =
		sign > 0 && 1 < magnitude ? Math.pow( 10, magnitude - sign ) : Math.pow( 10, magnitude );

	// Determine how many units are needed to accommodate the chart's max value.
	const numberOfUnits = Math.ceil( max / unitSize );

	return unitSize * numberOfUnits;
}

// The Chart component.
function Chart( {
	barClick,
	children,
	data,
	isPlaceholder = false,
	isRtl,
	minBarWidth = 15,
	minTouchBarWidth = 42,
	translate,
	chartXPadding = 20,
	sliceFromBeginning = true,
	onChangeMaxBars,
	minBarsToBeShown,
	hideYAxis = false,
	hideXAxis = false,
} ) {
	const [ tooltip, setTooltip ] = useState( { isTooltipVisible: false } );
	const [ sizing, setSizing ] = useState( { clientWidth: 0, hasResized: false } );
	const [ yAxisSize, setYAxisSize ] = useState( { clientWidth: 0, hasResized: false } );

	// Callback to handle tooltip changes.
	// Needs to be memoized to avoid assigning children a new function every render.
	const handleTooltipChange = useCallback( ( tooltipContext, tooltipPosition, tooltipData ) => {
		if ( ! tooltipContext || ! tooltipPosition || ! tooltipData ) {
			setTooltip( { isTooltipVisible: false } );
		} else {
			setTooltip( { tooltipContext, tooltipPosition, tooltipData, isTooltipVisible: true } );
		}
	}, [] );

	const handleYAxisSizeChange = ( contentRect ) => {
		if ( ! contentRect ) {
			return;
		}
		setYAxisSize( ( prevSizing ) => {
			const clientWidth = contentRect.width;
			if ( ! prevSizing.hasResized || clientWidth !== prevSizing.clientWidth ) {
				return { clientWidth, hasResized: true };
			}
			return prevSizing;
		} );
	};

	const yAxisRef = useWindowResizeCallback( handleYAxisSizeChange );

	// Callback to handle element size changes.
	// Needs to be memoized to avoid causing the `useWindowResizeCallback` custom hook to re-subscribe.
	const handleContentRectChange = useCallback(
		( contentRect ) => {
			if ( ! contentRect ) {
				return;
			}
			setSizing( ( prevSizing ) => {
				const effectiveYAxisSize =
					yAxisRef && yAxisRef.current ? yAxisRef.current.clientWidth : yAxisSize.clientWidth;
				const clientWidth = contentRect.width - effectiveYAxisSize;
				if ( ! prevSizing.hasResized || clientWidth !== prevSizing.clientWidth ) {
					return { clientWidth, hasResized: true };
				}
				return prevSizing;
			} );
		},
		[ yAxisRef, yAxisSize.clientWidth ]
	);

	// Subscribe to changes to element size and position.
	const resizeRef = useWindowResizeCallback( handleContentRectChange );

	const minWidth = isTouch ? minTouchBarWidth : minBarWidth;

	const width = isTouch && sizing.clientWidth <= 0 ? 350 : sizing.clientWidth - chartXPadding; // mobile safari bug with zero width
	// Max number of bars that can fit in the chart. If minBarsToBeShown is set, use that instead.
	const maxBars = minBarsToBeShown ?? Math.floor( width / minWidth );

	useEffect( () => {
		if ( onChangeMaxBars ) {
			onChangeMaxBars( maxBars );
		}
	}, [ maxBars, onChangeMaxBars ] );

	useEffect( () => {
		// Invalidate (hide) the tooltip if the underlying data changes.
		setTooltip( { isTooltipVisible: false } );
	}, [ data ] );

	// Memoize data calculations to avoid performing them too often.
	const { chartData, isEmptyChart, yMax } = useMemo( () => {
		const nextData = ( () => {
			if ( data.length > maxBars ) {
				if ( sliceFromBeginning ) {
					return data.slice( 0 - maxBars );
				}
				return data.slice( 0, maxBars );
			}
			return data;
		} )();

		const nextVals = nextData.map( ( { value } ) => value );

		return {
			chartData: nextData,
			isEmptyChart: Boolean( ! nextVals.some( ( a ) => a > 0 ) ),
			yMax: getYAxisMax( nextVals ),
		};
	}, [ data, maxBars, sliceFromBeginning ] );

	const { isTooltipVisible, tooltipContext, tooltipPosition, tooltipData } = tooltip;

	const ChartYAxis = () => (
		<div ref={ yAxisRef } className="chart__y-axis">
			<div className="chart__y-axis-width-spacer">{ formatNumber( 1e5 ) }</div>
			<div className="chart__y-axis-label is-hundred">
				{ yMax > 1 ? formatNumber( yMax ) : formatNumber( yMax, { decimals: 2 } ) }
			</div>
			<div className="chart__y-axis-label is-fifty">
				{ yMax > 1 ? formatNumber( yMax / 2 ) : formatNumber( yMax / 2, { decimals: 2 } ) }
			</div>
			<div className="chart__y-axis-label is-zero">{ formatNumber( 0 ) }</div>
		</div>
	);

	// This is a hack to avoid the flickering on page load.
	// The component listens on the resize event of its own, which would resize on initialization.
	// The hack renders an empty div, which triggers the resize event, and then the actual component would be rendered.
	if ( sizing.clientWidth <= 0 || yAxisSize.clientWidth <= 0 ) {
		return (
			<div ref={ resizeRef } className="chart">
				<ChartYAxis />
			</div>
		);
	}

	return (
		<div ref={ resizeRef } className={ clsx( 'chart', { 'is-placeholder': isPlaceholder } ) }>
			<div className="chart__y-axis-markers">
				<div className="chart__y-axis-marker is-hundred" />
				<div className="chart__y-axis-marker is-fifty" />
				<div className="chart__y-axis-marker is-zero" />

				{ ( isPlaceholder || isEmptyChart ) && (
					<div className="chart__empty">
						{ children || (
							<Notice
								className="chart__empty-notice"
								status="is-warning"
								isCompact
								text={ translate( 'No activity this period', {
									context: 'Message on empty bar chart in Stats',
									comment: 'Should be limited to 32 characters to prevent wrapping',
								} ) }
								showDismiss={ false }
							/>
						) }
					</div>
				) }
			</div>
			{ ! isPlaceholder && ! hideYAxis && <ChartYAxis /> }
			<BarContainer
				barClick={ barClick }
				chartWidth={ width }
				data={ chartData }
				isPlaceholder={ isPlaceholder }
				isRtl={ isRtl }
				isTouch={ hasTouch() }
				setTooltip={ handleTooltipChange }
				yAxisMax={ yMax }
				hideXAxis={ hideXAxis }
			/>
			{ isTooltipVisible && (
				<Tooltip
					className="chart__tooltip"
					id="popover__chart-bar"
					context={ tooltipContext }
					isVisible={ isTooltipVisible }
					position={ tooltipPosition }
				>
					<ul>{ tooltipData }</ul>
				</Tooltip>
			) }
		</div>
	);
}

Chart.propTypes = {
	barClick: PropTypes.func,
	data: PropTypes.array,
	isPlaceholder: PropTypes.bool,
	isRtl: PropTypes.bool,
	minBarWidth: PropTypes.number,
	minTouchBarWidth: PropTypes.number,
	translate: PropTypes.func,
	chartXPadding: PropTypes.number,
	sliceFromBeginning: PropTypes.bool,
	minBarsToBeShown: PropTypes.number,
	hideYAxis: PropTypes.bool,
	hideXAxis: PropTypes.bool,
};

export default withRtl( localize( Chart ) );