1
1
import {
2
- LitElement , html ,
2
+ LitElement , html , css , nothing ,
3
3
} from 'lit' ;
4
4
5
+ import { TableColumn } from './TableColumn' ;
6
+
5
7
/**
6
8
* TableElement - A class that can be used to display a table
7
9
*
8
10
* @example
9
- * <wc-table>
10
- * <tr>
11
- * <th>Column A</th>
12
- * <th>Column B</th>
13
- * </tr>
14
- * <tr>
15
- * <td>Row 1, Column A</td>
16
- * <td>Row 1, Column B</td>
17
- * </tr>
18
- * </wc-table>
11
+ * <wc-table data="...">Table Caption</wc-table>
19
12
*/
20
13
export class TableElement extends LitElement {
21
14
static get localName ( ) {
@@ -24,28 +17,82 @@ export class TableElement extends LitElement {
24
17
25
18
static get properties ( ) {
26
19
return {
20
+ /**
21
+ * @property {Array } data
22
+ * @memberof TableElement
23
+ *
24
+ * The array of data loaded into the table. Each element may be an array or object.
25
+ */
27
26
data : { type : Array } ,
28
27
} ;
29
28
}
30
29
31
- get tableHeader ( ) {
30
+ static get styles ( ) {
31
+ return css `
32
+ table {
33
+ width: 100%;
34
+ border-collapse: collapse;
35
+ border: 1px solid gray;
36
+ }
37
+ table th {
38
+ background-color: lightgray;
39
+ border: 1px solid gray;
40
+ text-align: left;
41
+ }
42
+ table td,th {
43
+ padding: 2px;
44
+ }
45
+ ` ;
46
+ }
47
+
48
+ // eslint-disable-next-line class-methods-use-this
49
+ get tableColumns ( ) {
50
+ return [
51
+ new TableColumn ( 'fruit' ) ,
52
+ new TableColumn ( 'color' ) ,
53
+ new TableColumn ( 'weight' ) ,
54
+ ] ;
55
+ }
56
+
57
+ renderTableHeader ( ) {
32
58
return html `
33
59
< tr >
34
- < th > A </ th > < th > B < /th >
60
+ ${ this . tableColumns . map ( ( column ) => html ` < th > ${ column . name } < /th > ` ) }
35
61
</ tr >
36
62
` ;
37
63
}
38
64
39
- // eslint-disable-next-line class-methods-use-this
65
+ renderTableCell ( column , i , j ) {
66
+ const row = this . data [ i ] ;
67
+ if ( Array . isArray ( row ) && row . length <= j ) {
68
+ return row [ j ] ;
69
+ }
70
+ if ( typeof row === 'object' && column . name in row ) {
71
+ return row [ column . name ] ;
72
+ }
73
+ return nothing ;
74
+ }
75
+
76
+ renderTableRow ( i ) {
77
+ return this . tableColumns . map ( ( column , j ) => html `< td > ${ this . renderTableCell ( column , i , j ) } </ td > ` ) ;
78
+ }
79
+
80
+ renderTableRows ( ) {
81
+ return html `
82
+ ${ this . data . map ( ( _ , i ) => html `< tr > ${ this . renderTableRow ( i ) } </ tr > ` ) }
83
+ ` ;
84
+ }
85
+
40
86
render ( ) {
41
- // eslint-disable-next-line no-console
42
- console . log ( 'TableElement render' , this . data ) ;
87
+ const tableHeader = this . renderTableHeader ( ) ;
88
+ const tableRows = this . renderTableRows ( ) ;
43
89
return html `
44
90
< table >
45
91
< thead >
46
- ${ this . tableHeader }
92
+ ${ tableHeader }
47
93
</ thead >
48
94
< tbody >
95
+ ${ tableRows }
49
96
</ tbody >
50
97
</ table >
51
98
< caption > < slot > </ slot > </ caption >
0 commit comments