All files / src/gadgets/list table.js

100% Statements 148/148
100% Branches 81/81
100% Functions 47/47
100% Lines 143/143

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 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630                                                                                                                                  51x 51x                             636x         7x 1x 1x           52x 91x 91x 1x 3x 3x     91x         107x 107x       706x       175x       5x                     17x     17x 17x   17x 1x   16x               5x               6x 6x 2x             4x 4x         4x 4x 4x 4x 4x       1x     1x       1x       1x 1x         2x         1x         4x 4x   1x     3x           2x         2x 2x 1x           6x                 3x 3x 3x 3x         1x             3x 3x 3x         3x       3x 3x               1x 1x 1x 1x       264x 264x 264x 264x 264x 264x 2x   264x 263x       264x 515x 515x 515x               264x                 264x 515x       264x 264x 264x   264x 264x                                             102x 102x     265x     102x 2x 6x 6x 6x 6x 3x     3x         102x 16x 52x 52x   52x 52x 52x       262x       1x                 187x 187x 187x 187x                                                             1x                                                     101x                                                   74x                   4x                             102x 102x 102x 102x   102x 102x 46x     102x 16x     102x 12x   102x                           102x                         102x   102x   102x 102x 187x 187x 187x 187x             102x   102x 102x           102x 102x               102x                   102x                                                                        
/* Copyright © 2016 Kuali, Inc. - All Rights Reserved
 * You may use and modify this code under the terms of the Kuali, Inc.
 * Pre-Release License Agreement. You may not distribute it.
 *
 * You should have received a copy of the Kuali, Inc. Pre-Release License
 * Agreement with this file. If not, please write to license@kuali.co.
 */
 
import Cell from './cell'
import classnames from 'classnames'
import ColumnVisibility from './column-visibility'
import { compare } from '../../utils/compare'
import FilterDialog from './filter-dialog'
import ItemDialog from './item-dialog'
import PropTypes from 'prop-types'
import React from 'react'
import styles from './style.css'
import {
  cloneDeep,
  get,
  includes,
  intersection,
  isEmpty,
  isEqual,
  keys,
  noop,
  omit,
  partial,
  set
} from 'lodash'
import {
  FlatButton,
  Icon,
  IconButton,
  Popover,
  RaisedButton
} from '@kuali/kuali-ui'
 
export default class Table extends React.Component {
  static propTypes = {
    className: PropTypes.string,
    columns: PropTypes.array,
    addId: PropTypes.func.isRequired,
    decorate: PropTypes.func,
    formbotOptions: PropTypes.object,
    headers: PropTypes.array.isRequired,
    initialHiddenColumns: PropTypes.array,
    listType: PropTypes.string,
    mode: PropTypes.string,
    onChange: PropTypes.func,
    onColumnVisibilityChange: PropTypes.func,
    rows: PropTypes.array,
    renderRow: PropTypes.func,
    showColumnVisibilityControl: PropTypes.bool,
    template: PropTypes.object
  }
 
  static defaultProps = {
    initialHiddenColumns: [],
    listType: 'inline',
    onColumnVisibilityChange: noop,
    showColumnVisibilityControl: true
  }
 
  constructor (props) {
    super(props)
    this.state = {
      dialogItem: null,
      dialogItemReadOnly: false,
      filterValues: {},
      hiddenColumns: this.props.initialHiddenColumns,
      dialogItemIndex: -1,
      showItemDialog: false,
      showColumnVisibility: false,
      sortCol: null,
      sortAsc: true,
      valueMap: this.generateValueMap(props.headers)
    }
  }
 
  get isDialog () {
    return this.props.listType === 'dialog'
  }
 
  // React lifecycle
  componentWillReceiveProps = nextProps => {
    if (!isEqual(nextProps.headers, this.props.headers)) {
      const valueMap = this.generateValueMap(nextProps.headers)
      this.setState({ valueMap })
    }
  }
 
  // Helpers
  generateValueMap = headers => {
    return headers.reduce((map, header) => {
      const options = get(header, ['template', 'details', 'options'], [])
      if (!isEmpty(options)) {
        map[header.key] = options.reduce((acc, option) => {
          acc[option.key] = option.lbl
          return acc
        }, {})
      }
      return map
    }, {})
  }
 
  mappedGadgetValue = (formKey, value) => {
    const { valueMap } = this.state
    return get(valueMap, [formKey, value], value)
  }
 
  filterHeaders = (headers, hiddenColumns) => {
    return headers.filter(header => !includes(hiddenColumns, header.key))
  }
 
  createRowControl = (name, handler, row, disabled) => {
    return (
      <div className={styles.rowControlsCell} style={{ flex: '0 0 50px' }}>
        <IconButton
          data-test={name}
          onClick={() => handler(row)}
          disabled={disabled}
        >
          <Icon name={name} />
        </IconButton>
      </div>
    )
  }
 
  // Sorting
  handleSort = headerKey => {
    const { sortCol, sortAsc } = this.state
 
    // Clicking on the same header repeatedly toggles through asc, desc, and unsort.
    const clickedHeaderOnce = sortCol === headerKey
    const clickedHeaderTwice = clickedHeaderOnce && !sortAsc
 
    if (clickedHeaderTwice) {
      this.resetSort()
    } else {
      this.setState({
        sortCol: headerKey,
        sortAsc: !clickedHeaderOnce
      })
    }
  }
 
  resetSort = () => {
    this.setState({
      sortAsc: true,
      sortCol: null
    })
  }
 
  // Event Handlers
  handleAddRowClicked = () => {
    const { rows } = this.props
    if (this.isDialog) {
      this.setState({
        dialogItemEditable: true,
        showItemDialog: true,
        dialogItem: null,
        dialogItemIndex: rows.length
      })
    } else {
      this.resetSort()
      this.addNewRow()
    }
  }
 
  addNewRow = () => {
    const { createNewRow, onChange, rows } = this.props
    const newListRows = cloneDeep(rows)
    let newLine = createNewRow()
    newListRows.push(newLine)
    onChange(newListRows)
  }
 
  handleShowColumnVisibility = evt => {
    this.setState({
      showColumnVisibility: !this.state.showColumnVisibility
    })
    evt.stopPropagation()
  }
 
  handleHideColumnVisibility = evt => {
    this.setState({ showColumnVisibility: false })
  }
 
  handleColumnVisibilityChange = hiddenColumns => {
    this.setState({ hiddenColumns })
    this.props.onColumnVisibilityChange(hiddenColumns)
  }
 
  handleRowKeyPress = (rowIndex, e) => {
    // Add new row on shift + return when on last row
    if (
      e.shiftKey &&
      e.which === 13 &&
      rowIndex === this.props.rows.length - 1
    ) {
      this.handleAddRowClicked()
    }
  }
 
  handleFilterClicked = (colKey, e) => {
    e.stopPropagation() // Prevent column from being sorted
    if (this.filterPopoverClosed) {
      // Debounce
      return
    }
    // Toggle which column should display the filter dialog
    this.setState(prevState => ({
      filterDialogCol: prevState.filterDialogCol === colKey ? null : colKey
    }))
  }
 
  handleFilterPopoverClosed = () => {
    this.setState({
      filterDialogCol: null
    })
 
    // Set flag used to debounce
    this.filterPopoverClosed = true
    setTimeout(() => {
      this.filterPopoverClosed = false
    }, 100)
  }
 
  // Row control handlers
  handleViewEditItem = (readOnly, row) => {
    this.setState({
      dialogItemReadOnly: readOnly,
      dialogItemIndex: row.index,
      dialogItem: cloneDeep(row),
      showItemDialog: true
    })
  }
 
  handleRemoveRow = row => {
    const { onChange, rows } = this.props
    const newListRows = cloneDeep(rows)
    newListRows.splice(row.index, 1)
    onChange(newListRows)
  }
 
  // Dialog Handlers
  handleItemDialogClose = () => {
    this.setState({
      dialogItem: null,
      showItemDialog: false
    })
  }
 
  handleOnChange = item => {
    const { dialogItemIndex } = this.state
    const { onChange, rows } = this.props
    const newRows = set(
      rows,
      dialogItemIndex,
      item.id ? item : this.props.addId(item)
    )
    onChange(newRows)
  }
 
  handleItemDialogSave = item => {
    this.handleOnChange(item)
    this.setState({
      dialogItem: null,
      dialogItemIndex: -1,
      showItemDialog: false
    })
  }
 
  handleGadgetChange = (rowIndex, formKey, newValue) => {
    const { rows, onChange } = this.props
    const newListRows = cloneDeep(rows)
    set(newListRows, [rowIndex, formKey], newValue)
    onChange(newListRows)
  }
 
  createRow = (row, renderIndex, showControls, additionalContext, readOnly) => {
    const { headers, template, mode, renderRow } = this.props
    const { hiddenColumns } = this.state
    const rowIndex = row.index
    const gadgetMode = this.isDialog ? 'view' : mode
    const columns = this.filterHeaders(headers, hiddenColumns)
    if (showControls === undefined || showControls === null) {
      showControls = mode === 'edit'
    }
    if (readOnly === undefined || readOnly === null) {
      readOnly = mode === 'view'
    }
 
    // Never show a label from within a row
    const childTemplates = columns.map((column, index) => {
      const template = cloneDeep(column.template)
      template.id = `${column.key}-${rowIndex}`
      return omit(template, [
        'label',
        'desc',
        'question',
        'progressiveDisclosure'
      ])
    })
 
    let newRow = renderRow(
      gadgetMode,
      childTemplates,
      row,
      partial(this.handleGadgetChange, rowIndex),
      rowIndex,
      additionalContext
    )
 
    newRow = React.Children.map(newRow, child => {
      return <Cell id={get(child, ['key'])}>{child}</Cell>
    })
 
    const showViewEditControl =
      this.isDialog && (showControls || mode === 'view')
    const buttonViewMode = mode === 'view' || readOnly
    const viewEditIcon = buttonViewMode ? 'remove_red_eye' : 'create'
 
    const key = `${template.id}-${row.id}`
    return (
      // Pass down the original index in case we need to map from original rows to sorted rows later
      <div
        className={styles.row}
        data-index={row.index}
        key={key}
        onKeyPress={partial(this.handleRowKeyPress, renderIndex)}
      >
        {newRow}
        {showViewEditControl &&
          this.createRowControl(
            viewEditIcon,
            partial(this.handleViewEditItem, readOnly),
            row,
            false
          )}
        {showControls &&
          this.createRowControl('delete', this.handleRemoveRow, row, readOnly)}
      </div>
    )
  }
 
  transformChildRows = showControls => {
    const { rows } = this.props
    const { sortCol, sortAsc, filterValues } = this.state
 
    // Keep track of original index
    let renderRows = rows.map((row, index) => ({ ...row, index }))
 
    // Filter rows
    if (!isEmpty(filterValues)) {
      renderRows = renderRows.filter(row => {
        const filterCols = intersection(keys(row), keys(filterValues))
        for (var i = 0; i < filterCols.length; i++) {
          const col = filterCols[i]
          if (includes(filterValues[col], row[col])) {
            return false // This value has been hidden
          }
        }
        return true
      })
    }
 
    // Sort rows if necessary
    if (sortCol) {
      renderRows.sort((a, b) => {
        a = a[sortCol]
        b = b[sortCol]
 
        a = this.mappedGadgetValue(sortCol, a)
        b = this.mappedGadgetValue(sortCol, b)
        return compare(a, b, sortAsc)
      })
    }
 
    return renderRows.map((row, idx) => this.createRow(row, idx, showControls))
  }
 
  updateFilterValuesForCol = (colKey, values) => {
    this.setState(prevState => ({
      filterValues: {
        ...prevState.filterValues,
        [colKey]: values
      }
    }))
  }
 
  headerControl = (header, rows, sortOpts, filterOpts) => {
    const { hiddenValues, showFilterDialog } = filterOpts
    const { sortAsc, sorted } = sortOpts
    const filtersApplied = !isEmpty(hiddenValues)
    return (
      <Popover
        align='left'
        contentClassName={styles.filterPopoverContent}
        content={
          <FilterDialog
            colKey={header.key}
            hiddenValues={hiddenValues}
            rows={rows}
            labelForValue={this.mappedGadgetValue}
            updateHiddenValues={partial(
              this.updateFilterValuesForCol,
              header.key
            )}
          />
        }
        hideArrow
        key={header.key}
        position='bottom'
        onRequestClose={this.handleFilterPopoverClosed}
        trapFocus={false}
        visible={showFilterDialog}
      >
        <div
          key={header.key}
          className={`${styles.headerColumn} ${sorted ? styles.sorted : ''} ${
            showFilterDialog ? styles.filterDialogShown : ''
          }`}
          onClick={partial(this.handleSort, header.key)}
          onMouseDown={e =>
            /* Prevents text highlighting when clicked multiple times */
            e.preventDefault()
          }
        >
          <div className={styles.headerColumnLabel}>{header.label}</div>
          <div>
            <div style={{ display: 'flex' }}>
              {sorted && (
                <Icon
                  name={`arrow_drop_${sortAsc ? 'up' : 'down'}`}
                  style={{ color: 'white' }}
                />
              )}
              <Icon
                className={`${styles.filterButton} ${
                  filtersApplied ? styles.applied : ''
                }`}
                name='filter_list'
                onClick={partial(this.handleFilterClicked, header.key)}
              />
            </div>
          </div>
        </div>
      </Popover>
    )
  }
 
  columnVisibilityControl = (headers, hiddenColumns, showColumnVisibility) => {
    return (
      <Popover
        content={
          <ColumnVisibility
            initialHiddenColumns={hiddenColumns}
            headers={headers}
            onChange={this.handleColumnVisibilityChange}
          />
        }
        onRequestClose={this.handleHideColumnVisibility}
        position='bottom'
        title='Columns'
        trapFocus={false}
        visible={showColumnVisibility}
      >
        <RaisedButton
          label='Columns'
          onMouseDown={this.handleShowColumnVisibility}
        >
          <Icon name='remove_red_eye' />
        </RaisedButton>
      </Popover>
    )
  }
 
  addSpacer (spacers, column) {
    return [
      ...spacers,
      <div
        className={`${styles.headerColumn} ${styles.rowControls}`}
        key={`spacer-${column}`}
      />
    ]
  }
 
  addInfo () {
    return (
      <div className={classnames(styles.row, styles.addRow)}>
        <FlatButton
          data-test='add_info'
          label='Add Info'
          onClick={this.handleAddRowClicked}
          variant='clear'
        >
          <Icon name='add' />
        </FlatButton>
      </div>
    )
  }
 
  spacerHeaderColumns = () => {
    const { mode } = this.props
    const hasDeleteIcon = mode === 'edit'
    const hasEditIcon = mode === 'edit' && this.isDialog
    const hasViewIcon = mode === 'view' && this.isDialog
 
    let spacers = []
    if (hasDeleteIcon) {
      spacers = this.addSpacer(spacers, 'delete')
    }
 
    if (hasEditIcon) {
      spacers = this.addSpacer(spacers, 'edit')
    }
 
    if (hasViewIcon) {
      spacers = this.addSpacer(spacers, 'view')
    }
    return spacers
  }
 
  render () {
    const {
      className = '',
      decorate,
      headers,
      mode,
      rows,
      renderRow,
      showColumnVisibilityControl,
      template,
      headingParts
    } = this.props
 
    const {
      dialogItem,
      dialogItemIndex,
      dialogItemReadOnly,
      filterDialogCol,
      filterValues,
      hiddenColumns,
      showItemDialog,
      showColumnVisibility,
      sortCol,
      sortAsc
    } = this.state
 
    const showControls = mode === 'edit'
 
    const filteredHeaders = this.filterHeaders(headers, hiddenColumns)
    let listHeader = filteredHeaders.map((header, index) => {
      const sorted = header.key === sortCol
      const showFilterDialog = header.key === filterDialogCol
      const hiddenValues = filterValues[header.key] || []
      return this.headerControl(
        header,
        rows,
        { sorted, sortAsc },
        { hiddenValues, showFilterDialog }
      )
    })
    listHeader = listHeader.concat(this.spacerHeaderColumns())
 
    const renderRows = this.transformChildRows(showControls)
    const decorated = {
      ...decorate(headingParts),
      ...decorate({ listHeader }),
      ...decorate({ gadgetChildren: renderRows }, this.createRow)
    }
 
    const wrapperStyle = classnames(styles.wrapper, className)
    const columnVisibilityControl = showColumnVisibilityControl
      ? this.columnVisibilityControl(
        headers,
        hiddenColumns,
        showColumnVisibility
      )
      : null
 
    const addButton = showControls ? (
      <RaisedButton
        id='addButton'
        label='Add Line'
        onClick={this.handleAddRowClicked}
      >
        <Icon name='add' />
      </RaisedButton>
    ) : null
 
    return (
      <div className={wrapperStyle} key={template.id}>
        {showItemDialog && (
          <ItemDialog
            readOnly={dialogItemReadOnly}
            item={dialogItem}
            itemIndex={dialogItemIndex}
            visible={showItemDialog}
            headers={headers}
            renderRow={renderRow}
            onSave={this.handleItemDialogSave}
            onChange={this.handleOnChange}
            onClose={this.handleItemDialogClose}
          />
        )}
        <div className={styles.row} style={{ alignItems: 'flex-end' }}>
          <div>
            <div className={styles.title}>
              {decorated.label}
              {decorated.question}
              {decorated.desc}
            </div>
          </div>
          <div className={styles.controls}>
            {columnVisibilityControl}
            {addButton}
          </div>
        </div>
        <div className={styles.row}>{decorated.listHeader}</div>
        {isEmpty(decorated.gadgetChildren) && showControls
          ? this.addInfo()
          : decorated.gadgetChildren}
      </div>
    )
  }
}