-
Notifications
You must be signed in to change notification settings - Fork 83
/
aha-table.html
1833 lines (1602 loc) · 61 KB
/
aha-table.html
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!--
Copyright (c) 2018, General Electric
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!--
/**
* @module aha-table
*
* Internal table helper component used by px-data-table.
*
* Originally based on https://github.com/liuwenchao/aha-table, but heavily modified.
*
*/
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="px-pagination.html">
<link rel="import" href="px-data-table-cell.html">
<link rel="import" href="../px-icon-set/px-icon-set.html">
<link rel="import" href="../px-icon-set/px-icon.html">
<link rel="import" href="../app-localize-behavior/app-localize-behavior.html"/>
<link rel="import" href="css/aha-table-styles.html">
<dom-module id="aha-table">
<template>
<style include="aha-table-styles"></style>
<content id="columndefs"></content>
<template is="dom-if" if="{{showColumnChooser}}">
<div class="flex columnChooser u-mb-">
<px-dropdown class="u-ml--" display-value="{{localize('Show/Hide Column')}}" items='{{_columnChooserItems}}' multi hide-selected clear-selections-on-change>
</px-dropdown>
</div>
</template>
<div class="scroll-body">
<div id="scrollBodyTableContainer" class$="table {{_getTableClass(tableCells, tableColumns)}}" role="grid">
<!-- Header -->
<div class="tr tr--header" role="row">
<template is="dom-repeat" items="{{meta}}" as="column">
<template is="dom-if" if="{{!column.hide}}">
<span role="columnheader" class$="{{_getHeaderClass(column)}}" draggable="{{enableColumnReorder}}" on-touchstart="_dragStartColumnHeader" on-touchmove="_touchMoveHeader" on-touchleave="_dragLeave" on-touchend="_touchDropColumnHeader" on-dragleave="_dragLeave" on-dragstart="_dragStartColumnHeader" on-dragover="_dragOverHeader" on-drop="_dragDropColumnHeader" on-dragend="_dragEndColumnHeader">
<div class="flex header--container">
<span
class$="{{_getTextSortingClass(sortable, column, sortedColumn)}}"
on-tap="_sort">{{column.label}}<px-icon icon$="{{_getSortingIcon(sortable, column, sortedColumn, descending)}}" class$="{{_getSortingClass(sortable, column, sortedColumn, descending)}}"></px-icon>
</span>
<template is="dom-if" if="{{!_isEqual(column.type, 'selected')}}">
<template is="dom-if" if="{{enableColumnResize}}">
<div class="header--drag-handle" on-down="_headerResizeMouseDown" on-track="_headerTrack"></div>
</template>
</template>
</div>
</span>
</template>
</template>
</div>
<!-- Second Header (filter/select all) -->
<div class$="{{_getSecondHeaderClass(_enableFilterRow)}}" role="row">
<template is="dom-repeat" items="{{meta}}" as="column" id="filterRepeat">
<span class$="{{_getFilterHeaderClass(column)}}" role="gridcell" hidden$="{{column.hide}}">
<!-- select all checkbox -->
<template is="dom-if" if="{{_isEqual(column.type, 'selected')}}">
<span class="flex" hidden$="{{column.hide}}">
<template is="dom-if" if="{{!singleSelect}}">
<input id="selectAllCheckbox" role="checkbox" aria-label="Click to select or deselect all rows" type="checkbox" on-change="_clickSelectAll"/>
</template>
</span>
</template>
<!-- filter entry -->
<template is="dom-if" if="{{_isFilterableColumn(column, filterable, column.hide)}}">
<input role="textbox" aria-label="Enter text to filter column" placeholder="{{localize('Filter')}}" class="text-input text-input--filter" type="text" on-input="_filter" />
</template>
</span>
</template>
</div>
<!-- Data rows -->
<template id="recordList" is="dom-repeat" items="{{displayedRows}}" as="internalRow" strip-whitespace>
<div role="row" class$="{{_getRowClass(internalRow,striped)}}">
<!-- Data cells -->
<template is="dom-repeat" items="{{meta}}" as="column">
<!-- selected column checkbox or radio button -->
<template is="dom-if" if="{{_isEqual(column.type, 'selected')}}">
<span role="gridcell" class$="{{_getSelectedCellClass(internalRow._selected, internalRow._highlight)}}" hidden$="{{column.hide}}" on-tap="_clickRow">
<span class="flex flex--middle">
<template is="dom-if" if="{{!singleSelect}}">
<input role="checkbox" aria-label="Click to select row" type="checkbox" checked="{{internalRow._selected::change}}"/>
</template>
<template is="dom-if" if="{{singleSelect}}">
<input role="checkbox" aria-label="Click to select row" type="radio" name="selected" checked="{{internalRow._selected::change}}"/>
</template>
</span>
</span>
</template>
<template id="cellRepeat" is="dom-if" if="{{!_isEqual(column.type, 'selected')}}">
<template is="dom-if" if="{{!column.hide}}">
<px-data-table-cell
on-save="_save"
row-highlighted="[[internalRow._highlight]]"
cell-highlighted="[[_getHighlightValue(internalRow, column, column.highlightdefined)]]"
cell-selected="[[internalRow._selected]]"
on-validate="_handleValidateEvent"
cell-type="{{column.type}}"
dropdown-items="{{column.dropdownItems}}"
placeholder="{{column.placeholder}}"
cell-display-value="{{_readContent(internalRow, column)}}"
cell-value="{{_getInternalDataAt(internalRow, column.name)}}"
cell-display-tooltip="{{_shouldClipDatumString(internalRow, column)}}"
cell-editable="{{column.editable}}"
cell-validation="{{_getInternalCellValidationStateAt(internalRow, column.name)}}"
column-name="{{column.name}}"
on-tap="_clickCell">
</px-data-table-cell>
</template>
</template>
</template>
</div>
</template>
</div>
<template is="dom-if" if="{{!displayedRows.length}}">
<div class="flex flex--center no-results">{{localize('No Results')}}</div>
</template>
</div>
<!-- Pagination controls -->
<div class="pagination">
<px-pagination class$="{{_getPaginationVisibility(hidePaginationControl)}}"
id="pagination"
data-remote="{{dataRemote}}"
number-of-items="{{_adaptedNumberOfItems}}"
page-size="{{pageSize}}"
page-size-options="{{pageSizeOptions}}"
first-item-index-to-display="{{firstItemIndex}}"
language="{{language}}"
use-key-if-missing="{{useKeyIfMissing}}"
resources="{{resources}}">
</px-pagination>
</div>
</template>
</dom-module>
<script>
Polymer({
is: 'aha-table',
behaviors: [
Polymer.AppLocalizeBehavior
],
properties: {
//data: instance of the model data
data: {
type: Array,
notify: true,
value: function () {
return [];
}
},
//meta: instance of the model meta
meta: {
type: Array,
value: function () {
return [];
}
},
//selected: all selected row will be referenced here. Really only readable.
selectedRows: {
type: Array,
value: function () {
return [];
},
notify: true
},
//selectable: if table row is selectable
selectable: {
type: Boolean,
value: false,
observer: "_selectableChanged"
},
//single-select: if only one row can be selected
singleSelect: {
type: Boolean,
value: false,
observer: "_singleSelectChanged"
},
//striped: if table row is striped
striped: {
type: Boolean,
value: false
},
//tableCells: if table row is striped
tableCells: {
type: Boolean,
value: false
},
//tableColumns: if table row is striped
tableColumns: {
type: Boolean,
value: false
},
//filterable: if table row is filterable
filterable: {
type: Boolean,
value: false,
},
//filterable: if table columns are sortable
sortable: {
type: Boolean,
value: false,
},
includeAllColumns: {
type: Boolean,
value: false,
observer: '_includeAllColumnsChanged'
},
//_enableFilterRow: if table row is _enableFilterRow
_enableFilterRow: {
type: Boolean,
value: false
},
//sortedColumn: sorted column name
sortedColumn: {
type: String,
value: ""
},
// the column names that are filtered on
filteredColumns: {
type: Array,
value: function () {
return [];
}
},
//all rows that are currently displayed on the page (visible right now)
displayedRows: {
type: Array,
value: function () {
return [];
}
},
//descending: current sorting order
descending: {
type: Boolean,
value: false
},
/**
* Property to set the the total number of entries in the table,
* assuming that dataRemote is true and the data provided is only
* for the visible page.
*
* Requires dataRemote="true" to take effect
*
* <px-data-table data-remote="true" page-size total-entries="100" first-item-index="0" table-data="{{data}}"></px-data-table>
*
* @default false
*/
totalEntries: {
type: Number,
value: 10,
observer: '_calculateAdaptedNumberOfItems'
},
/**
* Property to set the the remote index of the first item on this page,
* assuming that dataRemote is true and the data provided is only
* for the visible page.
*
* Requires dataRemote="true" to take effect
*
* If on page 2 with a page size of 10, then the first-item-index would be 11.
*
* <px-data-table data-remote="true" page-size total-entries="100" first-item-index="0" table-data="{{data}}"></px-data-table>
*
* @default false
*/
firstItemIndex: {
type: Number,
value: 1
},
/**
* Property to set the the data paradigm.
*
* If this is false, then px-data-table expects all of the data to be provided to it.
*
* If this is true, then px-data-table will expect only one page's worth of data to be supplied.
* This will require other fields to be set, e.g. page-size, total-entries, and first-item-index
*
* <px-data-table data-remote="true" page-size total-entries="100" first-item-index="0" table-data="{{data}}"></px-data-table>
*
* @default false
*/
dataRemote: {
type: Boolean,
value: false
},
/**
* Property to set the page size instead of the default of 10.
*
* In data-remote mode, page size may not match count of data provided.
* Page size could be 50, but only 40 items are provided.
*
* <px-data-table page-size="50" table-data="{{data}}"></px-data-table>
*
* @default 10
*/
pageSize: {
type: Number,
value: 10,
observer: '_setPageSize'
},
/**
* When dataRemote is true, then this reflects the total count on observer
* and numberOfItems reflects count of items in tableProperty to track the number of items in the table
*/
_adaptedNumberOfItems: {
type: Number,
},
/**
* Property to track the number of items in the table
*
* Without dataRemote==true, this will be the total number of items
* With dataRemote==true this will either be the page size or the number of items if less than the page size
*/
numberOfItems: {
type: Number,
observer: '_calculateAdaptedNumberOfItems'
},
/**
* Property to set the visibility of the table pagination controls.
*
* <px-data-table hide-pagination-control="false" table-data="{{data}}"></px-data-table>
*
* @default false
*/
hidePaginationControl: {
type: Boolean,
value: false
},
/**
* Property to set the visibility of the table column chooser (used
* to show and hide columns)
*
* @default false
*/
showColumnChooser: {
type: Boolean,
value: false
},
/**
* Property to enable draggability of column headers for reordering
* columns
*
* @default false
*/
enableColumnReorder: {
type: Boolean,
value: false
},
/**
* Property to enable resizing of column headers through click and drag
*
* @default false
*/
enableColumnResize: {
type: Boolean,
value: false
},
_internalData: {
type: Array,
value: function(){
return [];
}
},
/**
* Array holding the column names in their displayed order
*
*/
_columnChooserItems: {
type: Array,
value: function() {
return [];
}
},
/**
* Whether we're currently displaying an insertion column (when dragging columns)
*
*/
_displayingInsertion: {
type: Boolean,
value: false
},
_requestInsertionIndicatorRemoval: {
type: Boolean,
value: false
},
/**
* When currently resizing a header
*/
_headerInitialSize: {
type: Number,
value: 0
},
_columnDragged: {
type: String,
value: ''
},
_isAttached: {
type: Boolean,
value: false
},
//scroll body html element
scrollBody: {
type: String,
value: '#scrollBodyTableContainer'
},
dataChangeTrigger: {
type: Boolean,
value: false
},
/**
* Options displayed in the page size dropdown.
*/
pageSizeOptions: {
type: Array,
value: function() {
return [{"key":"1","val":"10"},
{"key":"2","val":"20"},
{"key":"3","val":"50"},
{"key":"4","val":"100"}];
}
}
},
observers: [
'_updateDisplayedRows(firstItemIndex)', // when the first item to display changes
'_updateDisplayedRows(pageSize)', // when the size of the page changes
'_dataChanged(data.*)',
'_computeColumnChooserItems(meta, meta.*)',
'_computeIfColumnFilterEnabled(meta.splices, filterable, meta.*, selectable, singleSelect)'
],
listeners: {
'validate': '_handleValidateEvent',
'px-dropdown-selection-changed': '_columnChooserChanged'
},
ready: function() {
this.addEventListener('px-data-table-highlight-loaded', this._highlightLoaded.bind(this));
var boundHandler = this._columnChanged.bind(this);
this._observer = Polymer.dom(this.$.columndefs).observeNodes(boundHandler);
},
attached: function () {
this._isAttached = true;
},
_columnChanged: function(info){
if(this.selectable && this.meta.length === 0) this.push('meta', this._generateMetaForColumn("_selected", "selected", true, this.localize("Selected") + " (0)"));
var addedColumns = info.addedNodes.filter(function(node) {
return (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'PX-DATA-TABLE-COLUMN');
});
var removedColumns = info.removedNodes.filter(function (node) {
return (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'PX-DATA-TABLE-COLUMN');
});
if(addedColumns.length > 0) {
for (var i = 0; i < addedColumns.length; i++) {
// default the type of the column to a string
if (!addedColumns[i].type) {
addedColumns[i].type = 'string';
}
if (!addedColumns[i]['label']) {
var name = addedColumns[i]['name'] || '';
addedColumns[i].label = name.charAt(0).toUpperCase() + name.slice(1);
}
this._addColumn(addedColumns[i]);
}
}
removedColumns.forEach(function (columnToRemove) {
this.meta.forEach(function (column, idx) {
if (columnToRemove === column) {
this.splice('meta', idx, 1);
}
}.bind(this));
}.bind(this));
},
_addColumn: function(addedColumn) {
//meta needs to reflect the order in light dom. Find the node just before this one
var previousNode,
notFound = this.getEffectiveChildren().every(function (column, index) {
if (column.name === addedColumn.name) {
return false;
}
previousNode = column;
return true;
});
//if column found
if (!notFound) {
var idx = 0;
//make sure we insert in the right place
if (previousNode) {
this.meta.forEach(function (column, index) {
if (column.name === previousNode.name) {
idx = index + 1;
}
});
this.splice('meta', idx, 0, addedColumn);
}
else {
if(this.selectable) idx += 1;
this.splice('meta', idx, 1, addedColumn);
}
}
else {
this.push('meta', addedColumn);
}
},
_selectedColumnExists: function(){
return this.meta && this.meta[0] && this.meta[0].name === '_selected';
},
_highlightLoaded: function (evt) {
evt = Polymer.dom(evt);
var column = this._findFirstMatchingElementNameFromEventPath(evt, "PX-DATA-TABLE-COLUMN");
column._highLightElLoadedCount += 1;
if (column._highLightElLoadedCount === Polymer.dom(column).querySelectorAll('px-data-table-highlight').length) {
var columnIndex = this._findMetaIndexFromColumnElement(column);
if (columnIndex > 0) {
this.set('meta.' + columnIndex + '.highlightdefined', true);
}
}
},
_findMetaIndexFromColumnElement: function (columnElement) {
var columnIndex = -1;
this.meta.some(
function (item, idx) {
if (item === columnElement) {
columnIndex = idx;
return true;
}
}
);
return columnIndex;
},
_findFirstMatchingElementNameFromEventPath: function (evt, nodeName) {
var el;
evt.path.some(function (node) {
if (node.nodeName === nodeName) {
el = node;
return true;
}
});
return el;
},
_dataChanged: function (changeRec) {
this.dataChangeTrigger = false; //reset the dataChangeTrigger Boolean
if (this.data === undefined || this.data === null || (!this._isAttached && changeRec.base.length === 0)) {
this._internalData = [];
return;
}
//wait for us to be attached before processing data changes
//debounce it as well
if (!this._isAttached) {
var _this = this;
this.debounce('attach', function () {
_this._dataChanged(changeRec);
}, 10);
return;
}
// if includeAllColumns is true, or if no px-data-table-columns have been defined,
// need to calculate meta from the actual data passed in to the table
if(this.includeAllColumns || this.meta.length === 0 || (this.meta.length === 1 && this.meta[0].name === "_selected")) {
this._generateMetaFromData();
}
if ( !this._typeofComparison(this._internalData, "undefined") && this._internalData.length === 0) {
this._internalData = this._initializeInternalData();
} else {
//Reach here when a cell data is edited
this.dataChangeTrigger = true;
this._internalData = this._refreshInternalData();
}
this.selectedRows = this._internalData.filter(function (it) {
return it._selected === true;
});
this._filterSortAndUpdateDisplayedTable();
var pathNumber = new RegExp('([#])([0-9])+');
if (pathNumber.test(changeRec.path)) {
var index = pathNumber.exec(changeRec.path)[0].slice(1);
var pathPieces = changeRec.path.split('.'),
columnName = pathPieces[pathPieces.length - 1],
column;
this.meta.some(function (columnEl) {
if (columnEl.name === columnName) {
column = columnEl;
return true;
}
});
if (this._cellChanged(this._readContent(this._internalData[index], column), changeRec.value)) {
this._handleValidateEvent(evt);
}
}
},
_getNumberOfItems: function (numberOfItems,totalEntries,dataRemote) {
return dataRemote ? totalEntries : numberOfItems;
},
_includeAllColumnsChanged: function(newValue) {
if(newValue === true) {
this._generateMetaFromData();
}
else if (newValue === false && this._isAttached && this.getContentChildren('#columndefs').length > 0) {
this.meta = this.getContentChildren('#columndefs').filter(function(node) {
return (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'PX-DATA-TABLE-COLUMN');
});
this._selectableChanged(this.selectable);
}
},
_selectableChanged: function(newSelectable) {
// if meta is already defined and then selectable is set, we need to backfill the meta with the _selected column
if (newSelectable === true && this.meta !== null && this.meta !== undefined && this.meta.length > 0) {
this.splice('meta', 0, 0, this._generateMetaForColumn("_selected", "selected", true, this.localize("Selected") + " (0)"));
} else if (newSelectable === false && this.meta !== null && this.meta !== undefined && this.meta.length > 0 && this.meta[0].name === "_selected") {
this.shift('meta');
}
},
_singleSelectChanged: function() {
if(this._internalData && this.selectedRows.length > 1) this._setAllRows(false);
},
/********** Generating column metadata *************/
_generateMetaFromData: function() {
for(var prop in this.data[0]) {
var previousNode,
notFound = this.meta.every(function(column, index) {
if(column.name === prop) {
return false;
}
return true;
});
// if column not found
if(notFound) {
var colInfo = this._generateMetaForColumn(prop, "string", false, prop.charAt(0).toUpperCase() + prop.slice(1));
this.push('meta', colInfo);
}
}
},
_generateMetaForColumn: function (prop, type, isSelectAll, label) {
return Polymer.Base.create('px-data-table-column', {
name: prop,
label: label,
type: type,
sortable: this.sortable,
filterable: this.filterable,
disableSelect: !this.selectable,
editable: false,
required: false,
hide: false,
selectAll: isSelectAll,
validate: function () { return { 'passedValidation': true }; }
});
},
/********** Filter/Sort main function *************/
_filterSortAndUpdateDisplayedTable: function () {
var i,
index,
count = 0,
self = this,
len;
// start at original data source (shadow fields, _selected and _filtered are still set)
this.filteredSortedData = this._internalData;
// reset back to unfiltered
// leave _selected as is since selected rows should stay selected
for (i = 0, len = this._internalData.length; i < len; i++) {
this._setInternalDataAt(this._internalData[i], '_filtered', false);
}
if (!this.dataRemote) {
// If remote, all sorting/filtering is done on server
// sort
if (this.sortedColumn) {
this.filteredSortedData = this._sortByColumn(this.filteredSortedData);
}
// filter
for (index in this.filteredColumns) {
this.filteredSortedData = this._filterByColumn(this.filteredColumns[index].name,
this.filteredColumns[index].userEntry, this.filteredSortedData);
}
// count total number of rows
self = this;
this._internalData.forEach(function (row) {
if (!self._getInternalCellStateAt(row, '_filtered')) {
count++;
}
});
if(this.dataChangeTrigger == false){
this.set('numberOfItems', count);
this.$.pagination.goToPageNumber(1);
}
// with filtering/sorting, it's best just to go back to the first page
// filtering/sorting -> datachangetrigger will be false
} else {
this.$.pagination.updateDisplay();
this.set('numberOfItems', this.totalEntries);
}
this._updateDisplayedRows();
//update selected rows when changing the filter if the select all is enabled
var selectAllCheckbox = Polymer.dom(this.root).querySelector("#selectAllCheckbox");
if(selectAllCheckbox !== null && selectAllCheckbox !== undefined && selectAllCheckbox.checked){
selectAllCheckbox.checked=false;
}
},
/********** Internal data structure ***********/
_refreshInternalData: function (resetDataState) {
var _internalData = [],
i,
len;
for (i = 0, len = this.data.length; i < len; i++) {
var thisObj = this.data[i],
cellDataObj = { dataIndex: i },
resetDataFlag = resetDataState || i >= this._internalData.length;
for (var key in thisObj) {
if (Object.prototype.hasOwnProperty.call(thisObj, key)) {
cellDataObj[key] = {};
cellDataObj[key].value = thisObj[key];
if (resetDataFlag) {
cellDataObj[key]._validation = { passedValidation: true };
} else if(this._internalData[i].row[key] && this._internalData[i].row[key]._validation) {
cellDataObj[key]._validation = this._internalData[i].row[key]._validation;
}
}
}
_internalData.push({
row: cellDataObj,
_filtered: (resetDataFlag ? false : this._internalData[i]._filtered),
_selected: (resetDataFlag ? false : this._internalData[i]._selected),
_highlight: (resetDataFlag ? { value: false, highlightColor: '' } : this._internalData[i]._highlight)
});
}
return _internalData;
},
_initializeInternalData: function () {
// make internal data structure with shadow fields
return this._refreshInternalData(true);
},
// set helper method so we don't have to sprinkle logic of this internal data structure throughout
_setInternalDataAt: function (row, columnName, value) {
if (columnName === '_selected' || columnName === '_filtered' || columnName === '_highlight') {
// shadow fields are in root of row in internal data
this.set('displayedRows.' + this.displayedRows.indexOf(row) + '.' + columnName, value);
row[columnName] = value;
}
else {
// the user's data is in the row column of internal data
row.row[columnName].value = value;
}
},
// get helper method so we don't have to sprinkle logic of this internal data structure throughout
_getInternalDataAt: function (row, columnName) {
return this._getInternalCellStateAt(row, columnName).value;
},
_getInternalCellValidationStateAt: function (row, columnName) {
return this._getInternalCellStateAt(row, columnName)._validation;
},
_setInternalCellValidationStateAt: function (row, columnName, value) {
row.row[columnName]._validation = value;
},
_getInternalCellStateAt: function (row, columnName) {
if (columnName === '_selected' || columnName === '_filtered') {
// shadow fields are in root of row in internal data
return row[columnName];
}
else {
// the user's data is in the row column of internal data
return (row.row[columnName] ? row.row[columnName] : {});
}
},
/******* Update Displayed rows when major changes ****/
_setPageSize: function () {
this.$.pagination.setPageSize(this.pageSize);
},
_getInternalRowStateAt: function (row, columnName) {
if(columnName === '_selected' || columnName === '_filtered') {
return row;
}
else {
return row.row;
}
},
_updateDisplayedRows: function () {
var fromPage,
to;
if (this.firstItemIndex !== null && this.firstItemIndex !== undefined &&
this.pageSize !== null && this.pageSize !== undefined &&
this.filteredSortedData !== undefined && this.filteredSortedData !== null && !this.hidePaginationControl) {
fromPage = this.firstItemIndex - 1; // pagination is 1-based
to = fromPage + parseInt(this.pageSize, 10);
this.filteredSortedData = this.filteredSortedData.map( function(row) {
row.isNew = true;
return row;
});
if (this.dataRemote) {
this.set('displayedRows', this.filteredSortedData);
} else {
this.set('displayedRows', this.filteredSortedData.slice(fromPage, to));
}
} else if (this.filteredSortedData !== undefined && this.filteredSortedData !== null && this.hidePaginationControl) {
this.filteredSortedData = this.filteredSortedData.map( function(row) {
row.isNew = true;
return row;
});
this.set('displayedRows', this.filteredSortedData);
}
},
/********** Sorting ************/
/*
* Fires a sort change request event
*
* Only called if remoteData==true
*
* Information is stored in `evt.detail`:
* ```
* document.getElementById("mytable").addEventListener("px-sort-change-intent", function(e) {
* var data = e.detail;
* console.log("Intended sort: ", JSON.parse(data));
* });
* // ==> [{name:'columnA',direction:'ascending'}] or [{name:'columnB',direction:'descending'}]
* ```
* @event px-sort-change-intent
*/
_triggerSortChangeRequest: function () {
// debouncing so this can be called anytime params are updated
this.debounce('_debounceTriggerSortChangeRequest', function() {
// currently only supports single column sort
// event interface is set up to handle multi-column sort
this.fire('px-sort-change-intent', !this.sortedColumn ? '[]' : JSON.stringify([{
name: this.sortedColumn,
direction: this.descending ? 'descending' : 'ascending'
}]));
}, 300);
},
// sort by header click handler
_sort: function(e, p) {
if(!this.sortable) return;
var column = e.model.column,
sortingColumn;
if (column && column.sortable) {
sortingColumn = column.name;
if(sortingColumn === this.sortedColumn && !this.descending) {
this.set('descending', !this.descending);
}
else if(sortingColumn === this.sortedColumn && this.descending) {
this.set('sortedColumn', '');
} else {
this.set('sortedColumn', sortingColumn);
this.set('descending', false); // always start ascending when click new column
}
}
if (!this.dataRemote) {
this._filterSortAndUpdateDisplayedTable();
} else {
this._triggerSortChangeRequest();
}
},
_sortByColumn: function (rowsToSort) {
var sortFunction = this._getSortFunction(),
sortedRows;
// sorting map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Sorting_maps
sortedRows =
rowsToSort
.map(function (e, i) {
var v;
if (this.sortedColumn === '_selected') {
v = this._getInternalCellStateAt(e, this.sortedColumn);
} else {
v = this._getInternalDataAt(e, this.sortedColumn);
}
// call internal state function...
if (undefined === v || null === v) {
v = '';
}
return {
index: i,
value: this._typeofComparison(v, "string") ? v.toLowerCase() : v
};
}, this)
.sort(sortFunction.bind(this))
.map(function (e) {
return rowsToSort[e.index];
});
return sortedRows;
},
_getSortFunction: function () {
var sortFunction;
if (this.sortedColumn !== '_selected') {
// use custom sort function if there is one
this.meta.forEach(function (obj) {
if (this.sortedColumn === obj.name) {
sortFunction = this._resolveFunctionOnWindow("sort-function-name", obj);
}
}, this);
}
if (!sortFunction) {
if (this.sortedColumn === "_selected") {
sortFunction = this._defaultSortSelected;
}
else {
sortFunction = this._defaultSortAlphabetically;
}
}
return sortFunction;
},
_resolveFunctionOnWindow: function (elAttributeName, elObj) {