]> git.apps.os.sepia.ceph.com Git - ceph-ci.git/blob
de004797ccbc3b038b2189a34820ded7c07509cd
[ceph-ci.git] /
1 import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
2
3 import * as _ from 'lodash';
4
5 import { CellTemplate } from '../../enum/cell-template.enum';
6 import { CdTableColumn } from '../../models/cd-table-column';
7
8 /**
9  * Display the given data in a 2 column data table. The left column
10  * shows the 'key' attribute, the right column the 'value' attribute.
11  * The data table has the following characteristics:
12  * - No header and footer is displayed
13  * - The relation of the width for the columns 'key' and 'value' is 1:3
14  * - The 'key' column is displayed in bold text
15  */
16 @Component({
17   selector: 'cd-table-key-value',
18   templateUrl: './table-key-value.component.html',
19   styleUrls: ['./table-key-value.component.scss']
20 })
21 export class TableKeyValueComponent implements OnInit, OnChanges {
22
23   columns: Array<CdTableColumn> = [];
24
25   @Input() data: any;
26   @Input() autoReload: any = 5000;
27
28   tableData: {
29     key: string,
30     value: any
31   }[];
32
33   /**
34    * The function that will be called to update the input data.
35    */
36   @Output() fetchData = new EventEmitter();
37
38   constructor() { }
39
40   ngOnInit() {
41     this.columns = [
42       {
43         prop: 'key',
44         flexGrow: 1,
45         cellTransformation: CellTemplate.bold
46       },
47       {
48         prop: 'value',
49         flexGrow: 3
50       }
51     ];
52     this.useData();
53   }
54
55   ngOnChanges(changes) {
56     this.useData();
57   }
58
59   useData() {
60     let temp = [];
61     if (!this.data) {
62       return; // Wait for data
63     } else if (_.isArray(this.data)) {
64       const first = this.data[0];
65       if (_.isPlainObject(first) && _.has(first, 'key') && _.has(first, 'value')) {
66         temp = [...this.data];
67       } else {
68         if (_.isArray(first)) {
69           if (first.length === 2) {
70             temp = this.data.map(a => ({
71               key: a[0],
72               value: a[1]
73             }));
74           } else {
75             throw new Error('Wrong array format');
76           }
77         }
78       }
79     } else if (_.isPlainObject(this.data)) {
80       temp = Object.keys(this.data).map(k => ({
81         key: k,
82         value: this.data[k]
83       }));
84     } else {
85       throw new Error('Wrong data format');
86     }
87     this.tableData = temp.map(o => {
88       if (_.isArray(o.value)) {
89         o.value = o.value.join(', ');
90       } else if (_.isObject(o.value)) {
91         return;
92       }
93       return o;
94     }).filter(o => o); // Filters out undefined
95   }
96
97   reloadData() {
98     // Forward event triggered by the 'cd-table' datatable.
99     this.fetchData.emit();
100   }
101 }