All files / components/DataTable DataTable.jsx

100% Statements 40/40
90.91% Branches 40/44
100% Functions 10/10
100% Lines 40/40
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                              120x   120x                 120x               120x                                                                                                                                               120x                                                               120x                   100x               10x   10x           1x   1x             10x   10x 10x 10x             5x   5x 5x 5x 5x                           33x     33x 33x 94x 88x   6x 6x   12x               33x   82x     33x   33x                                                     94x                                               30x                                   182x                             760x 760x   760x                             140x             200x                                      
import _ from 'lodash';
import React from 'react';
import { lucidClassNames } from '../../util/style-helpers';
import { createClass, findTypes, filterTypes, getFirst, omitProps } from '../../util/component-types';
 
import Checkbox from '../Checkbox/Checkbox';
import EmptyStateWrapper from '../EmptyStateWrapper/EmptyStateWrapper';
import ScrollTable from '../ScrollTable/ScrollTable';
 
const {
	Thead,
	Tbody,
	Tr,
	Th,
	Td,
} = ScrollTable;
 
const cx = lucidClassNames.bind('&-DataTable');
 
const {
	any,
	func,
	object,
	string,
	bool,
	arrayOf,
} = React.PropTypes;
 
/**
 *
 * {"categories": ["table"], "madeFrom": ["Checkbox", "EmptyStateWrapper", "ScrollTable"]}
 *
 * `DataTable` provides a simple abstraction over the `Table` component to make it easier to define data-driven tables and render an array of objects.
 */
const DataTable = createClass({
	displayName: 'DataTable',
 
	propTypes: {
		/**
		 * Class names that are appended to the defaults.
		 */
		className: string,
		/**
		 * Array of objects to be rendered in the table. Object keys match the `field` of each defined `DataTable.Column`.
		 */
		data: arrayOf(object),
		/**
		 * The text to display in cells which have no data.
		 */
		emptyCellText: string,
		/**
		 * Render each row item to be navigable, allowing `onRowClick` to be triggered.
		 */
		isActionable: bool,
		/**
		 * If `true`, the table will be set to fill the width of its parent container.
		 */
		isFullWidth: bool,
		/**
		 * Controls the visibility of the `LoadingMessage`.
		 */
		isLoading: bool,
		/**
		 * Render a checkbox in the first column allowing `onSelect` and `onSelectAll` to be triggered.
		 */
		isSelectable: bool,
		/**
		 * Styles that are passed through to the root container.
		 */
		style: object,
		/**
		 * Handler for row click. Signature is `(object, index, { props, event }) => {...}`
		 */
		onRowClick: func,
		/**
		 * Handler for checkbox selection. Signature is `(object, index, { props, event }) => {...}`
		 */
		onSelect: func,
		/**
		 * Handler for checkbox selection in the table header. Signature is `({ props, event }) => {...}`
		 */
		onSelectAll: func,
		/**
		 * Handler for column header click (for sorting). Signature is `(field, { props, event }) => {...}`
		 */
		onSort: func,
		/**
		 * *Child Element*
		 *
		 * Used to define a column of the table. It accepts the same props as `Table.Th` in addition to:
		 *
		 * - the required prop `field`
		 * - the optional prop `title`
		 */
		Column: any,
		/**
		 * *Child Element*
		 *
		 * Used to Group defined `Column`s in the table. It accepts the same props as `Table.Th` in addition to:
		 *
		 * - the optional prop `title`
		 */
		ColumnGroup: any,
	},
 
	getDefaultProps() {
		return {
			emptyCellText: '--',
			isActionable: false,
			isSelectable: false,
			onRowClick: _.noop,
			onSelect: _.noop,
			onSelectAll: _.noop,
			onSort: _.noop,
		};
	},
 
	components: {
		/**
		 * Renders a `Th` for the table.
		 */
		Column: createClass({
			displayName: 'DataTable.Column',
			propName: 'Column',
			propTypes: {
				field: string.isRequired,
				title: string,
			},
		}),
		/**
		 * Renders a group of `Th`s.
		 */
		ColumnGroup: createClass({
			displayName: 'DataTable.ColumnGroup',
			propName: 'ColumnGroup',
			propTypes: {
				title: string,
			},
			getDefaultProps: () => ({ align: 'center' }),
		}),
		/**
		 * Renders wrapper when the data table has no data.
		 */
		EmptyStateWrapper: EmptyStateWrapper,
	},
 
	statics: {
		shouldColumnHandleSort(column) {
			return _.isNil(column.isSortable) ? column.isSorted : column.isSortable;
		},
	},
 
	handleSelect(rowIndex, { event }) {
		const {
			data,
			onSelect,
		} = this.props;
 
		onSelect(data[rowIndex], rowIndex, { props: this.props, event });
	},
 
	handleSelectAll({ event }) {
		const {
			onSelectAll,
		} = this.props;
 
		onSelectAll({ props: this.props, event });
	},
 
	handleRowClick(rowIndex, event) {
		const {
			data,
			onRowClick,
		} = this.props;
 
		const targetTagName = event.target.tagName.toLowerCase();
		Eif (targetTagName === 'td' || targetTagName === 'tr') {
			onRowClick(data[rowIndex], rowIndex, { props: this.props, event });
		}
	},
 
	handleSort(field, event) {
		const {
			onSort,
		} = this.props;
 
		event.stopPropagation();
		event.preventDefault();
		event.bubbles = false;
		onSort(field, {props: this.props, event});
	},
 
	render() {
		const {
			className,
			data,
			emptyCellText,
			isActionable,
			isFullWidth,
			isLoading,
			isSelectable,
			style,
			...passThroughs,
		} = this.props;
 
 
		const childComponentElements = findTypes(this.props, [DataTable.Column, DataTable.ColumnGroup]);
		const flattenedColumns = _.reduce(childComponentElements, (acc, childComponentElement) => {
			if (childComponentElement.type === DataTable.Column) {
				return acc.concat([{props: childComponentElement.props, columnGroupProps: null}]);
			}
			Eif (childComponentElement.type === DataTable.ColumnGroup) {
				return acc.concat(_.map(
					findTypes(childComponentElement.props, DataTable.Column),
					(columnChildComponent) => ({
						props: columnChildComponent.props,
						columnGroupProps: childComponentElement.props,
					})
				));
			}
		}, []);
 
		const hasGroupedColumns = _.some(
			childComponentElements,
			(childComponentElement) => childComponentElement.type === DataTable.ColumnGroup
		);
 
		const emptyStateWrapper = getFirst(this.props, DataTable.EmptyStateWrapper, <DataTable.EmptyStateWrapper Title='You have no items.' />);
 
		return (
			<EmptyStateWrapper
				{...emptyStateWrapper.props}
				isEmpty={_.isEmpty(data)}
				isLoading={isLoading}
			>
				{emptyStateWrapper.props.children}
				<ScrollTable
					style={style}
					tableWidth={isFullWidth ? '100%' : null}
					{...omitProps(passThroughs, DataTable)}
					className={cx('&', {
						'&-full-width': isFullWidth,
					}, className)}
				>
					<Thead>
						<Tr>
							{isSelectable ? (
								<Th
									rowSpan={hasGroupedColumns ? 2 : null}
								>
									<Checkbox
										isSelected={_.every(data, 'isSelected')}
										onSelect={this.handleSelectAll}
									/>
								</Th>
							) : null}
							{_.map(childComponentElements, ({ props, type }, index) => type === DataTable.Column ? (
								<Th
									{..._.omit(props, ['field', 'children', 'width', 'title'])}
									onClick={DataTable.shouldColumnHandleSort(props) ? _.partial(this.handleSort, props.field) : null}
									style={{
										width: props.width,
									}}
									rowSpan={hasGroupedColumns ? 2 : null}
									key={_.get(props, 'field', index)}
								>
									{props.title || props.children}
								</Th>
							) : (
								<Th
									colSpan={_.size(filterTypes(props.children, DataTable.Column))}
									{..._.omit(props, ['field', 'children', 'width', 'title'])}
									key={_.get(props, 'field', index)}
								>
									{props.title || props.children}
								</Th>
							))}
						</Tr>
						{hasGroupedColumns ? (
							<Tr>
								{_.reduce(flattenedColumns, (acc, { props: columnProps, columnGroupProps }, index) => acc.concat(_.isNull(columnGroupProps) ? [] : [(
									<Th
										{...omitProps(columnProps, DataTable.Column)}
										onClick={DataTable.shouldColumnHandleSort(columnProps) ? _.partial(this.handleSort, columnProps.field) : null}
										style={{
											width: columnProps.width,
										}}
										key={_.get(columnProps, 'field', index)}
									>
										{columnProps.title || columnProps.children}
									</Th>
								)]), [])}
							</Tr>
						) : null}
					</Thead>
					<Tbody>
						{data && data.length > 0 ?
							_.map(data, (row, index) => (
								<Tr
									{..._.pick(row, ['isDisabled', 'isActive', 'isSelected'])}
									onClick={_.partial(this.handleRowClick, index)}
									isActionable={isActionable}
									key={'row' + index}
								>
									{isSelectable ? (
										<Td>
											<Checkbox
												isSelected={row.isSelected}
												onSelect={_.partial(this.handleSelect, index)}
											/>
										</Td>
									) : null}
									{_.map(flattenedColumns, ({ props: columnProps }, columnIndex) => {
										const cellValue = _.get(row, columnProps.field);
										const isEmpty = _.isEmpty(_.toString(cellValue));
 
										return (
											<Td
												{..._.omit(columnProps, ['field', 'children', 'width', 'title', 'isSortable', 'isSorted'])}
												style={{
													width: columnProps.width,
												}}
												key={'row' + index + _.get(columnProps, 'field', columnIndex)}
											>
												{isEmpty ? emptyCellText : cellValue}
											</Td>
									)})}
								</Tr>
						))
						:
						_.times(10, (index) => (
							<Tr
								isDisabled
								key={'row' + index}
								style={{height: '32px'}}
							>
								{isSelectable ? (<Td />) : null}
								{_.map(flattenedColumns, ({ props: columnProps }, columnIndex) => (
									<Td
										{..._.omit(columnProps, ['field', 'children', 'width', 'title', 'isSortable', 'isSorted'])}
										style={{
											width: columnProps.width,
										}}
										key={'row' + index + _.get(columnProps, 'field', columnIndex)}
									/>
								))}
							</Tr>
						))
					}
					</Tbody>
				</ScrollTable>
			</EmptyStateWrapper>
		);
	},
});
 
export default DataTable;