All files / src/app/shared/datatable/table table.component.ts

97.14% Statements 238/245
83.87% Branches 52/62
96.43% Functions 54/56
96.71% Lines 206/213

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 54990x                             90x           90x 90x   90x   90x 90x               90x   90x   90x   90x   90x   90x   90x   90x   90x       90x     90x     90x     325x     325x     325x     325x     325x               325x         325x       325x       325x     325x     325x       90x                       325x                     325x         325x     325x     325x 325x 325x 325x 325x           325x   325x     325x           325x   278x 278x     278x     278x           146x     278x 278x   311x     211x     1501x     278x           105x     208x 208x 1x 1x         70x       278x   246x 246x 246x     79x     79x     79x   199x 1153x         90x 246x   32x   2720x 2720x 23045x   2720x   246x     1376x           90x 246x   199x       90x 246x 246x     90x 246x   164x 164x 164x         90x 164x     90x 405x             90x 1558x     90x   184x     214x       90x             264x 264x       90x 278x 278x 278x 278x 278x 278x 278x     90x   1x   9x 9x 36x 36x   9x     90x 274x     90x 2x   1x       90x   74x 74x   2x     1x       2x   74x 74x       90x         591x 591x                 90x   114x   176x       176x 176x               90x 176x 176x               182x   11x   171x 171x 40x   4x               168x   3x 3x     90x 3x 3x     90x 7x 7x   1x 1x   9x 6x     90x 13x 13x 13x 21x 5x 5x   13x 13x     90x 286x               90x 5x     90x   1x     25x 105x   4x 6x       47x   25x     90x   20x   22x       22x 22x 22x 64x   13x   22x 22x     2x   22x     90x   1x   21x 1389x   3645x     16x             1252x   2377x   3645x           591x   591x 102x         90x  
import {
  AfterContentChecked,
  ChangeDetectorRef,
  Component,
  EventEmitter,
  Input,
  NgZone,
  OnChanges,
  OnDestroy,
  OnInit,
  Output,
  TemplateRef,
  ViewChild
} from '@angular/core';
 
import {
  DatatableComponent,
  SortDirection,
  SortPropDir,
  TableColumnProp
} from '@swimlane/ngx-datatable';
import * as _ from 'lodash';
import { Observable, timer as observableTimer } from 'rxjs';
 
import { CellTemplate } from '../../enum/cell-template.enum';
import { CdTableColumn } from '../../models/cd-table-column';
import { CdTableFetchDataContext } from '../../models/cd-table-fetch-data-context';
import { CdTableSelection } from '../../models/cd-table-selection';
import { CdUserConfig } from '../../models/cd-user-config';
 
@Component({
  selector: 'cd-table',
  template: require('./table.component.html'),
  styles: []
})
export class TableComponent implements AfterContentChecked, OnInit, OnChanges, OnDestroy {
  @ViewChild(DatatableComponent)
  table: DatatableComponent;
  @ViewChild('tableCellBoldTpl')
  tableCellBoldTpl: TemplateRef<any>;
  @ViewChild('sparklineTpl')
  sparklineTpl: TemplateRef<any>;
  @ViewChild('routerLinkTpl')
  routerLinkTpl: TemplateRef<any>;
  @ViewChild('checkIconTpl')
  checkIconTpl: TemplateRef<any>;
  @ViewChild('perSecondTpl')
  perSecondTpl: TemplateRef<any>;
  @ViewChild('executingTpl')
  executingTpl: TemplateRef<any>;
  @ViewChild('classAddingTpl')
  classAddingTpl: TemplateRef<any>;
 
  // This is the array with the items to be shown.
  @Input()
  data: any[];
  // Each item -> { prop: 'attribute name', name: 'display name' }
  @Input()
  columns: CdTableColumn[];
  // Each item -> { prop: 'attribute name', dir: 'asc'||'desc'}
  @Input()
  sorts?: SortPropDir[];
  // Method used for setting column widths.
  @Input()
  columnMode? = 'flex';
  // Display the tool header, including reload button, pagination and search fields?
  @Input()
  toolHeader? = true;
  // Display the table header?
  @Input()
  header? = true;
  // Display the table footer?
  @Input()
  footer? = true;
  // Page size to show. Set to 0 to show unlimited number of rows.
  @Input()
  limit? = 10;
 
  /**
   * Auto reload time in ms - per default every 5s
   * You can set it to 0, undefined or false to disable the auto reload feature in order to
   * trigger 'fetchData' if the reload button is clicked.
   */
  @Input()
  autoReload: any = 5000;
 
  // Which row property is unique for a row. If the identifier is not specified in any
  // column, then the property name of the first column is used. Defaults to 'id'.
  @Input()
  identifier = 'id';
  // If 'true', then the specified identifier is used anyway, although it is not specified
  // in any column. Defaults to 'false'.
  @Input()
  forceIdentifier = false;
  // Allows other components to specify which type of selection they want,
  // e.g. 'single' or 'multi'.
  @Input()
  selectionType: string = undefined;
  // By default selected item details will be updated on table refresh, if data has changed
  @Input()
  updateSelectionOnRefresh: 'always' | 'never' | 'onChange' = 'onChange';
 
  @Input()
  autoSave = true;
 
  // Only needed to set if the classAddingTpl is used
  @Input()
  customCss?: { [css: string]: number | string | ((any) => boolean) };
 
  /**
   * Should be a function to update the input data if undefined nothing will be triggered
   *
   * Sometimes it's useful to only define fetchData once.
   * Example:
   * Usage of multiple tables with data which is updated by the same function
   * What happens:
   * The function is triggered through one table and all tables will update
   */
  @Output()
  fetchData = new EventEmitter();
 
  /**
   * This should be defined if you need access to the selection object.
   *
   * Each time the table selection changes, this will be triggered and
   * the new selection object will be sent.
   *
   * @memberof TableComponent
   */
  @Output()
  updateSelection = new EventEmitter();
 
  /**
   * Use this variable to access the selected row(s).
   */
  selection = new CdTableSelection();
 
  tableColumns: CdTableColumn[];
  cellTemplates: {
    [key: string]: TemplateRef<any>;
  } = {};
  search = '';
  rows = [];
  loadingIndicator = true;
  loadingError = false;
  paginationClasses = {
    pagerLeftArrow: 'i fa fa-angle-double-left',
    pagerRightArrow: 'i fa fa-angle-double-right',
    pagerPrevious: 'i fa fa-angle-left',
    pagerNext: 'i fa fa-angle-right'
  };
  userConfig: CdUserConfig = {};
  tableName: string;
  localStorage = window.localStorage;
  private saveSubscriber;
  private reloadSubscriber;
  private updating = false;
 
  // Internal variable to check if it is necessary to recalculate the
  // table columns after the browser window has been resized.
  private currentWidth: number;
 
  constructor(private ngZone: NgZone, private cdRef: ChangeDetectorRef) {}
 
  ngOnInit() {
    this._addTemplates();
    if (!this.sorts) {
      // Check whether the specified identifier exists.
      const exists = _.findIndex(this.columns, ['prop', this.identifier]) !== -1;
      // Auto-build the sorting configuration. If the specified identifier doesn't exist,
      // then use the property of the first column.
      this.sorts = this.createSortingDefinition(
        exists ? this.identifier : this.columns[0].prop + ''
      );
      // If the specified identifier doesn't exist and it is not forced to use it anyway,
      // then use the property of the first column.
      if (!exists && !this.forceIdentifier) {
        this.identifier = this.columns[0].prop + '';
      }
    }
    this.initUserConfig();
    this.columns.forEach((c) => {
      if (c.cellTransformation) {
        c.cellTemplate = this.cellTemplates[c.cellTransformation];
      }
      if (!c.flexGrow) {
        c.flexGrow = c.prop + '' === this.identifier ? 1 : 2;
      }
      if (!c.resizeable) {
        c.resizeable = false;
      }
    });
    this.filterHiddenColumns();
    // Load the data table content every N ms or at least once.
    // Force showing the loading indicator if there are subscribers to the fetchData
    // event. This is necessary because it has been set to False in useData() when
    // this method was triggered by ngOnChanges().
    if (this.fetchData.observers.length > 0) {
      this.loadingIndicator = true;
    }
    if (_.isInteger(this.autoReload) && this.autoReload > 0) {
      this.ngZone.runOutsideAngular(() => {
        this.reloadSubscriber = observableTimer(0, this.autoReload).subscribe(() => {
          this.ngZone.run(() => {
            return this.reloadData();
          });
        });
      });
    } else {
      this.reloadData();
    }
  }
 
  initUserConfig() {
    if (this.autoSave) {
      this.tableName = this._calculateUniqueTableName(this.columns);
      this._loadUserConfig();
      this._initUserConfigAutoSave();
    }
    if (!this.userConfig.limit) {
      this.userConfig.limit = this.limit;
    }
    if (!this.userConfig.sorts) {
      this.userConfig.sorts = this.sorts;
    }
    if (!this.userConfig.columns) {
      this.updateUserColumns();
    } else {
      this.columns.forEach((c, i) => {
        c.isHidden = this.userConfig.columns[i].isHidden;
      });
    }
  }
 
  _calculateUniqueTableName(columns) {
    const stringToNumber = (s) => {
      if (!_.isString(s)) {
        return 0;
      }
      let result = 0;
      for (let i = 0; i < s.length; i++) {
        result += s.charCodeAt(i) * i;
      }
      return result;
    };
    return columns
      .reduce(
        (result, value, index) =>
          (stringToNumber(value.prop) + stringToNumber(value.name)) * (index + 1) + result,
        0
      )
      .toString();
  }
 
  _loadUserConfig() {
    const loaded = this.localStorage.getItem(this.tableName);
    if (loaded) {
      this.userConfig = JSON.parse(loaded);
    }
  }
 
  _initUserConfigAutoSave() {
    const source = Observable.create(this._initUserConfigProxy.bind(this));
    this.saveSubscriber = source.subscribe(this._saveUserConfig.bind(this));
  }
 
  _initUserConfigProxy(observer) {
    this.userConfig = new Proxy(this.userConfig, {
      set(config, prop, value) {
        config[prop] = value;
        observer.next(config);
        return true;
      }
    });
  }
 
  _saveUserConfig(config) {
    this.localStorage.setItem(this.tableName, JSON.stringify(config));
  }
 
  updateUserColumns() {
    this.userConfig.columns = this.columns.map((c) => ({
      prop: c.prop,
      name: c.name,
      isHidden: !!c.isHidden
    }));
  }
 
  filterHiddenColumns() {
    this.tableColumns = this.columns.filter((c) => !c.isHidden);
  }
 
  ngOnDestroy() {
    if (this.reloadSubscriber) {
      this.reloadSubscriber.unsubscribe();
    }
    if (this.saveSubscriber) {
      this.saveSubscriber.unsubscribe();
    }
  }
 
  ngAfterContentChecked() {
    // If the data table is not visible, e.g. another tab is active, and the
    // browser window gets resized, the table and its columns won't get resized
    // automatically if the tab gets visible again.
    // https://github.com/swimlane/ngx-datatable/issues/193
    // https://github.com/swimlane/ngx-datatable/issues/193#issuecomment-329144543
    if (this.table && this.table.element.clientWidth !== this.currentWidth) {
      this.currentWidth = this.table.element.clientWidth;
      this.table.recalculate();
    }
  }
 
  _addTemplates() {
    this.cellTemplates.bold = this.tableCellBoldTpl;
    this.cellTemplates.checkIcon = this.checkIconTpl;
    this.cellTemplates.sparkline = this.sparklineTpl;
    this.cellTemplates.routerLink = this.routerLinkTpl;
    this.cellTemplates.perSecond = this.perSecondTpl;
    this.cellTemplates.executing = this.executingTpl;
    this.cellTemplates.classAdding = this.classAddingTpl;
  }
 
  useCustomClass(value: any): string {
    if (!this.customCss) {
      throw new Error('Custom classes are not set!');
    }
    const classes = Object.keys(this.customCss);
    const css = Object.values(this.customCss)
      .map((v, i) => ((_.isFunction(v) && v(value)) || v === value) && classes[i])
      .filter((x) => x)
      .join(' ');
    return _.isEmpty(css) ? undefined : css;
  }
 
  ngOnChanges() {
    this.useData();
  }
 
  setLimit(e) {
    const value = parseInt(e.target.value, 10);
    if (value > 0) {
      this.userConfig.limit = value;
    }
  }
 
  reloadData() {
    if (!this.updating) {
      this.loadingError = false;
      const context = new CdTableFetchDataContext(() => {
        // Do we have to display the error panel?
        this.loadingError = context.errorConfig.displayError;
        // Force data table to show no data?
        if (context.errorConfig.resetData) {
          this.data = [];
        }
        // Stop the loading indicator and reset the data table
        // to the correct state.
        this.useData();
      });
      this.fetchData.emit(context);
      this.updating = true;
    }
  }
 
  refreshBtn() {
    this.loadingIndicator = true;
    this.reloadData();
  }
 
  rowIdentity() {
    return (row) => {
      const id = row[this.identifier];
      if (_.isUndefined(id)) {
        throw new Error(`Wrong identifier "${this.identifier}" -> "${id}"`);
      }
      return id;
    };
  }
 
  useData() {
    if (!this.data) {
      return; // Wait for data
    }
    this.rows = [...this.data];
    if (this.search.length > 0) {
      this.updateFilter();
    }
    this.reset();
    this.updateSelected();
  }
 
  /**
   * Reset the data table to correct state. This includes:
   * - Disable loading indicator
   * - Reset 'Updating' flag
   */
  reset() {
    this.loadingIndicator = false;
    this.updating = false;
  }
 
  /**
   * After updating the data, we have to update the selected items
   * because details may have changed,
   * or some selected items may have been removed.
   */
  updateSelected() {
    if (this.updateSelectionOnRefresh === 'never') {
      return;
    }
    const newSelected = [];
    this.selection.selected.forEach((selectedItem) => {
      for (const row of this.data) {
        if (selectedItem[this.identifier] === row[this.identifier]) {
          newSelected.push(row);
        }
      }
    });
    if (
      this.updateSelectionOnRefresh === 'onChange' &&
      _.isEqual(this.selection.selected, newSelected)
    ) {
      return;
    }
    this.selection.selected = newSelected;
    this.onSelect();
  }
 
  onSelect() {
    this.selection.update();
    this.updateSelection.emit(_.clone(this.selection));
  }
 
  toggleColumn($event: any) {
    const prop: TableColumnProp = $event.target.name;
    const hide = !$event.target.checked;
    if (hide && this.tableColumns.length === 1) {
      $event.target.checked = true;
      return;
    }
    _.find(this.columns, (c: CdTableColumn) => c.prop === prop).isHidden = hide;
    this.updateColumns();
  }
 
  updateColumns() {
    this.updateUserColumns();
    this.filterHiddenColumns();
    const sortProp = this.userConfig.sorts[0].prop;
    if (!_.find(this.tableColumns, (c: CdTableColumn) => c.prop === sortProp)) {
      this.userConfig.sorts = this.createSortingDefinition(this.tableColumns[0].prop);
      this.table.onColumnSort({ sorts: this.userConfig.sorts });
    }
    this.table.recalculate();
    this.cdRef.detectChanges();
  }
 
  createSortingDefinition(prop: TableColumnProp): SortPropDir[] {
    return [
      {
        prop: prop,
        dir: SortDirection.asc
      }
    ];
  }
 
  changeSorting({ sorts }) {
    this.userConfig.sorts = sorts;
  }
 
  updateFilter(clearSearch = false) {
    if (clearSearch) {
      this.search = '';
    }
    // prepare search strings
    let search = this.search.toLowerCase().replace(/,/g, '');
    const columns = this.columns.filter((c) => c.cellTransformation !== CellTemplate.sparkline);
    if (search.match(/['"][^'"]+['"]/)) {
      search = search.replace(/['"][^'"]+['"]/g, (match: string) => {
        return match.replace(/(['"])([^'"]+)(['"])/g, '$2').replace(/ /g, '+');
      });
    }
    // update the rows
    this.rows = this.subSearch(this.data, search.split(' ').filter((s) => s.length > 0), columns);
    // Whenever the filter changes, always go back to the first page
    this.table.offset = 0;
  }
 
  subSearch(data: any[], currentSearch: string[], columns: CdTableColumn[]) {
    if (currentSearch.length === 0 || data.length === 0) {
      return data;
    }
    const searchTerms: string[] = currentSearch
      .pop()
      .replace('+', ' ')
      .split(':');
    const columnsClone = [...columns];
    const dataClone = [...data];
    const filterColumns = (columnName: string) =>
      columnsClone.filter((c) => c.name.toLowerCase().indexOf(columnName) !== -1);
    if (searchTerms.length === 2) {
      columns = filterColumns(searchTerms[0]);
    }
    const searchTerm: string = _.last(searchTerms);
    data = this.basicDataSearch(searchTerm, data, columns);
    // Checks if user searches for column but he is still typing
    if (data.length === 0 && searchTerms.length === 1 && filterColumns(searchTerm).length > 0) {
      data = dataClone;
    }
    return this.subSearch(data, currentSearch, columnsClone);
  }
 
  basicDataSearch(searchTerm: string, rows: any[], columns: CdTableColumn[]) {
    if (searchTerm.length === 0) {
      return rows;
    }
    return rows.filter((row) => {
      return (
        columns.filter((col) => {
          let cellValue: any = _.get(row, col.prop);
 
          if (!_.isUndefined(col.pipe)) {
            cellValue = col.pipe.transform(cellValue);
          }
          if (_.isUndefined(cellValue) || _.isNull(cellValue)) {
            return false;
          }
 
          if (_.isArray(cellValue)) {
            cellValue = cellValue.join(' ');
          } else if (_.isNumber(cellValue) || _.isBoolean(cellValue)) {
            cellValue = cellValue.toString();
          }
          return cellValue.toLowerCase().indexOf(searchTerm) !== -1;
        }).length > 0
      );
    });
  }
 
  getRowClass() {
    // Return the function used to populate a row's CSS classes.
    return () => {
      return {
        clickable: !_.isUndefined(this.selectionType)
      };
    };
  }
}