All files / PieChart PieChart.tsx

100% Statements 37/37
95% Branches 19/20
100% Functions 4/4
100% Lines 37/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538                                      1x   1x   1x 1x 1x                                                                                                                                                                                                                                       1x                                                             1x                                                         1x                                                   39x   39x         39x   39x             39x 5x                     34x 34x   34x   34x 34x       34x           34x   34x 1x           34x 1x           34x                                               141x   141x   141x                                                                                                     1x   1x                                                                                                                                                                                                                                                                                           1x           1x             1x   1x   1x   1x                
import _, { omit } from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
 
import { lucidClassNames } from '../../util/style-helpers';
import { StandardProps, Overwrite } from '../../util/component-types';
import * as d3Shape from 'd3-shape';
import * as chartConstants from '../../constants/charts';
import { buildModernHybridComponent } from '../../util/state-management';
 
import Line from '../../components/Line/Line';
import {
	ToolTipDumb as ToolTip,
	IToolTipProps,
	nonPassThroughs as toolTipNonPassThroughs,
} from '../../components/ToolTip/ToolTip';
 
import reducers, { IPieChartState } from './PieChart.reducers';
 
const cx = lucidClassNames.bind('&-PieChart');
 
const { string, number, arrayOf, bool, shape, object, func } = PropTypes;
 
const DONUT_WIDTH = 15;
const HOVER_SCALE = 1.1; // duplicated in .less file
const INNER_RADIUS = 0.5;
 
interface IPieChartMargin {
	top?: number;
	right?: number;
	bottom?: number;
	left?: number;
}
 
export interface IPieChartPropsRaw extends StandardProps {
	/** Height of the chart. */
	height: number;
 
	/** Width of the chart. */
	width: number;
 
	/**
	 * An object defining the margins of the chart. These margins typically
	 * contain the axis and labels.
	 */
	margin?: IPieChartMargin;
 
	/**
	 * Data for the chart. E.g.
	 *
	 * [
	 *	{ x: 'Monday'    , y: 1 } ,
	 *	{ x: 'Tuesday'   , y: 2 } ,
	 *  { x: 'Wednesday' , y: 3 } ,
	 *  { x: 'Thursday'  , y: 2 } ,
	 *  { x: 'Friday'    , y: 5 } ,
	 * ]
	 */
	data?: Array<{ [key: string]: string | number }>;
 
	/** Show tool tips on hover. */
	hasToolTips: boolean;
 
	/** Determines if the pie slices have a stroke around them. */
	hasStroke: boolean;
 
	/**			
	 * Takes one of the palettes exported from \`lucid.chartConstants\`.
			Available palettes:
 
			- \`PALETTE_7\` (default)
			- \`PALETTE_30\`
			- \`PALETTE_MONOCHROME_0_5\`
			- \`PALETTE_MONOCHROME_1_5\`
			- \`PALETTE_MONOCHROME_2_5\`
			- \`PALETTE_MONOCHROME_3_5\`
			- \`PALETTE_MONOCHROME_4_5\`
			- \`PALETTE_MONOCHROME_5_5\`
			- \`PALETTE_MONOCHROME_6_5\` 
	*/
	palette: string[];
 
	/** You can pass in an object if you want to map x values to
	\`lucid.chartConstants\` or custom colors:
 
		{
			'imps': COLOR_0,
			'rev': COLOR_3,
			'clicks': '#abc123',
		}*/
	colorMap?: object;
 
	/** 
	An object of ToolTip props that are passed through to the underlying
			ToolTip component.
			*/
	ToolTip: IToolTipProps;
 
	/** Show the pie chart as a donut with a hollow center. */
	isDonut: boolean;
 
	/** Controls the visibility of the tooltip and the size of the currently
			hovered slice. */
	isHovering: boolean;
 
	/**
	Determines which slice to scale up and which data to display in he
		tooltip. */
	hoveringIndex: number;
 
	/** Called when the user hovers over a slice. */
	onMouseOver: (
		index: number,
		{ event, props }: { event: React.MouseEvent; props: IPieChartProps }
	) => void;
 
	/** Called when the user hovers away from either the pie or the tooltip. */
	onMouseOut: ({
		event,
		props,
	}: {
		event: React.MouseEvent;
		props: IPieChartProps;
	}) => void;
 
	/** Width of the donut in px. */
	donutWidth: number;
 
	/** The field we should look up your x data by. The data should be strings. */
	xAxisField: string;
 
	/** An optional function used to format your x axis data. */
	xAxisFormatter: (x: string | number) => string | number;
 
	/** The field we should look up your y data by. The data should be numeric. */
	yAxisField: string;
 
	/** An optional function used to format your y axis data. */
	yAxisFormatter: (y: number) => string | number;
}
 
const nonPassThroughs = [
	'style',
	'className',
	'height',
	'width',
	'margin',
	'data',
	'hasToolTips',
	'hasStroke',
	'palette',
	'colorMap',
	'ToolTip',
	'isDonut',
	'isHovering',
	'hoveringIndex',
	'onMouseOver',
	'onMouseOut',
	'donutWidth',
	'xAxisField',
	'xAxisFormatter',
	'yAxisField',
	'yAxisFormatter',
	'initialState',
	'callbackId',
];
 
export type IPieChartProps = Overwrite<
	React.SVGProps<SVGGElement>,
	IPieChartPropsRaw
>;
 
const defaultProps = {
	height: 200,
	width: 200,
	// duplicated because `statics` aren't available during getDefaultProps
	margin: {
		top: 10,
		right: 10,
		bottom: 10,
		left: 10,
	},
	palette: chartConstants.PALETTE_7,
	hasToolTips: true,
	hasStroke: true,
	isDonut: false,
	donutWidth: DONUT_WIDTH,
	ToolTip: ToolTip.defaultProps,
 
	isHovering: false,
	hoveringIndex: 0,
	onMouseOver: _.noop,
	onMouseOut: _.noop,
 
	xAxisField: 'x',
	xAxisFormatter: _.identity,
 
	yAxisField: 'y',
	yAxisFormatter: _.identity,
};
 
const PieChart = (props: IPieChartProps) => {
	const {
		style,
		className,
		height,
		width,
		margin: marginOriginal,
		data,
		hasToolTips,
		hasStroke,
		palette,
		colorMap,
		isDonut,
		donutWidth,
		ToolTip: toolTipProps,
 
		isHovering,
		hoveringIndex,
 
		xAxisField,
		xAxisFormatter,
 
		yAxisField,
		yAxisFormatter,
 
		...passThroughs
	} = props;
 
	const margin = {
		...PieChart.MARGIN,
		...marginOriginal,
	};
 
	const svgClasses = cx(className, '&');
 
	const pieChartProps: any = omit(
		omit(passThroughs, toolTipNonPassThroughs.concat(['callbackId'])),
		nonPassThroughs
	);
 
	// TODO: Consider displaying something specific when there is no data,
	// perhaps a loading indicator.
	if (_.isEmpty(data) || width < 1 || height < 1) {
		return (
			<svg
				{...pieChartProps}
				style={style}
				className={svgClasses}
				width={width}
				height={height}
			/>
		);
	}
 
	const innerWidth = width - margin.left - margin.right;
	const innerHeight = height - margin.top - margin.bottom;
 
	const outerRadius = Math.min(innerWidth, innerHeight) / 2;
 
	const pie = d3Shape.pie().sort(null); // needed to put the slices in proper order
	const pieData = pie(
		_.map(data as Array<{ [key: string]: number }>, yAxisField)
	);
 
	const arc = d3Shape
		.arc()
		.innerRadius(isDonut ? outerRadius - donutWidth : INNER_RADIUS)
		.outerRadius(outerRadius);
 
	// Useful for capturing hovers when we're in donut mode
	const arcFull = d3Shape.arc().innerRadius(0).outerRadius(outerRadius);
 
	const handleMouseOut = ({ event }: { event: React.MouseEvent }): void => {
		props.onMouseOut({
			props,
			event,
		});
	};
 
	const handleMouseOver = (index: number, event: React.MouseEvent): void => {
		props.onMouseOver(index, {
			props,
			event,
		});
	};
 
	return (
		<svg
			{...pieChartProps}
			style={style}
			className={svgClasses}
			width={width}
			height={height}
		>
			<ToolTip
				{...toolTipProps}
				isLight={true}
				isExpanded={hasToolTips && isHovering}
				onMouseOver={_.noop}
				onMouseOut={handleMouseOut}
			>
				<ToolTip.Target elementType='g'>
					<g transform={`translate(${margin.left}, ${margin.top})`}>
						<g transform={`translate(${innerWidth / 2}, ${innerHeight / 2})`}>
							{_.map(pieData, (pieDatum, index) => {
								/* Even though innerRadius and outerRadius are set when
									constructing arc and arcFull, these functions still expect a type
									that includes innerRadius and outerRadius */
 
								//@ts-ignore
								const arcFullData = arcFull(pieDatum);
								//@ts-ignore
								const arcData = arc(pieDatum);
 
								return (
									<g
										key={index}
										className={cx('&-slice-group', {
											'&-slice-group-is-hovering':
												isHovering && hoveringIndex === index,
										})}
									>
										<Line
											key={index}
											className={cx('&-slice', {
												'&-slice-has-stroke': hasStroke,
											})}
											d={arcData}
											color={_.get(
												colorMap,
												(data && data[index][xAxisField]) || '',
												palette[index % palette.length]
											)}
											transform={`scale(${
												isHovering && hoveringIndex === index ? HOVER_SCALE : 1
											})`}
										/>
 
										{/* This hidden path is useful for capturing hovers when we're in donut mode */}
										<path
											className={cx('&-slice-hover')}
											d={arcFullData}
											transform={`scale(${HOVER_SCALE})`}
											onMouseOver={_.partial(handleMouseOver, index)}
											onMouseOut={hasToolTips ? _.noop : handleMouseOut}
										/>
									</g>
								);
							})}
						</g>
					</g>
				</ToolTip.Target>
 
				<ToolTip.Title>
					{xAxisFormatter(_.get(data, `[${hoveringIndex}].${xAxisField}`))}
				</ToolTip.Title>
 
				<ToolTip.Body>
					{yAxisFormatter(_.get(data, `[${hoveringIndex}].${yAxisField}`))}
				</ToolTip.Body>
			</ToolTip>
		</svg>
	);
};
 
PieChart.displayName = 'PieChart';
 
PieChart.propTypes = {
	/**
			Styles that are passed through to the root container.
		*/
	style: object,
 
	/**
			Appended to the component-specific class names set on the root element.
		*/
	className: string,
 
	/**
			Height of the chart.
		*/
	height: number,
 
	/**
			Width of the chart.
		*/
	width: number,
 
	/**
		An object defining the margins of the chart. These margins typically
		contain the axis and labels.
	*/
	margin: shape({
		top: number,
		right: number,
		bottom: number,
		left: number,
	}),
 
	/**
			Data for the chart. E.g.
 
				[
					{ x: 'Monday'    , y: 1 } ,
					{ x: 'Tuesday'   , y: 2 } ,
					{ x: 'Wednesday' , y: 3 } ,
					{ x: 'Thursday'  , y: 2 } ,
					{ x: 'Friday'    , y: 5 } ,
				]
		*/
	data: arrayOf(object),
 
	/**
			Show tool tips on hover.
		*/
	hasToolTips: bool,
 
	/**
			Determines if the pie slices have a stroke around them.
		*/
	hasStroke: bool,
 
	/**
			Takes one of the palettes exported from \`lucid.chartConstants\`.
			Available palettes:
 
			- \`PALETTE_7\` (default)
			- \`PALETTE_30\`
			- \`PALETTE_MONOCHROME_0_5\`
			- \`PALETTE_MONOCHROME_1_5\`
			- \`PALETTE_MONOCHROME_2_5\`
			- \`PALETTE_MONOCHROME_3_5\`
			- \`PALETTE_MONOCHROME_4_5\`
			- \`PALETTE_MONOCHROME_5_5\`
			- \`PALETTE_MONOCHROME_6_5\`
		*/
	palette: arrayOf(string),
 
	/**
			You can pass in an object if you want to map x values to
			\`lucid.chartConstants\` or custom colors:
 
				{
					'imps': COLOR_0,
					'rev': COLOR_3,
					'clicks': '#abc123',
				}
		*/
	colorMap: object,
 
	/**
			An object of ToolTip props that are passed through to the underlying
			ToolTip component.
		*/
	ToolTip: shape(ToolTip.propTypes),
 
	/**
			Show the pie chart as a donut with a hollow center.
		*/
	isDonut: bool,
 
	/**
			Controls the visibility of the tooltip and the size of the currently
			hovered slice.
		*/
	isHovering: bool,
 
	/**
			Determines which slice to scale up and which data to display in he
			tooltip.
		*/
	hoveringIndex: number,
 
	/**
			Called when the user hovers over a slice.  Signature:
		*/
	onMouseOver: func,
 
	/**
			Called when the user hovers away from either the pie or the tooltip.
		*/
	onMouseOut: func,
 
	/**
			Width of the donut in px.
		*/
	donutWidth: number,
 
	/**
			The field we should look up your x data by. The data should be strings.
		*/
	xAxisField: string,
 
	/**
			An optional function used to format your x axis data.
		*/
	xAxisFormatter: func,
 
	/**
			The field we should look up your y data by. The data should be numeric.
		*/
	yAxisField: string,
 
	/**
			An optional function used to format your y axis data.
		*/
	yAxisFormatter: func,
};
 
PieChart.peek = {
	description: `\`PieChart\` is used for categorical data when you want to show the relative size of each category to the whole. We use similar "x" and "y" terms to keep parity with the other charts even though a pie chart is really just key value based.`,
	categories: ['visualizations', 'charts'],
	madeFrom: ['ToolTip'],
};
 
PieChart.MARGIN = {
	top: 10,
	right: 10,
	bottom: 10,
	left: 10,
};
 
PieChart.DONUT_WIDTH = DONUT_WIDTH;
 
PieChart.HOVER_SCALE = HOVER_SCALE;
 
PieChart.reducers = reducers;
 
PieChart.defaultProps = defaultProps;
 
export default buildModernHybridComponent<
	IPieChartProps,
	IPieChartState,
	typeof PieChart
>(PieChart as any, { reducers });
export { PieChart as PieChartDumb };