forked from olifolkerd/tabulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tabulator.js
4690 lines (3530 loc) · 121 KB
/
tabulator.js
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
/*
* This file is part of the Tabulator package.
*
* (c) Oliver Folkerd <oliver.folkerd@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Full Documentation & Demos can be found at: http://olifolkerd.github.io/tabulator/
*
*/
(function(){
'use strict';
//polyfill for Array.find method
if (!Array.prototype.find) {
Array.prototype.find = function (predicate, thisValue) {
var arr = Object(this);
if (typeof predicate !== 'function') {
throw new TypeError();
}
for(var i=0; i < arr.length; i++) {
if (i in arr) {
var elem = arr[i];
if (predicate.call(thisValue, elem, i, arr)) {
return elem;
}
}
}
return undefined;
}
}
$.widget("ui.tabulator", {
data:[],//array to hold data for table
activeData:[],//array to hold data that is active in the DOM
selectedRows:[], //array to hold currently selected rows
selecting:false, //is selection currently happening
selectPrev:[], //hold jQuery element for previously selected row to handle changing direction when selecting
firstRender:true, //layout table widths correctly on first render
mouseDrag:false, //mouse drag tracker;
mouseDragWidth:false, //starting width of colum on mouse drag
mouseDragElement:false, //column being dragged
mouseDragOut:false, //catch to prevent mouseup on col drag triggering click on sort
sortCurCol:null,//column name of currently sorted column
sortCurDir:null,//column name of currently sorted column
filterField:null, //field to be filtered on data render
filterValue:null, //value to match on filter
filterType:null, //filter type
paginationCurrentPage:1, // pagination page
paginationMaxPage:1, // pagination maxpage
progressiveRenderTimer:null, //timer for progressiver rendering
progressiveRenderFill:false, //initial fill of a progressive rendering table
progressiveRenderLoading:false, //flag to prevent concurrent progresive render loading
progressiveRenderLoadingNext:false, //flag to trigger loading of next items if list was loading when next request was triggered
columnList:[], //an array of all acutal columns ignoring column groupings
responsiveColumnList:[], //array of responsive columns
responsiveColumnIndex:0, //current possition in responsive array
columnFrozenLeft:[], //list of frozen columns left
columnFrozenRight:[], //list of frozen columns right
loaderDiv: $("<div class='tablulator-loader'><div class='tabulator-loader-msg'></div></div>"), //loader blockout div
lang:{}, // hold current locale text
defaultLang:{ //hold default locale text
"columns":{
},
"pagination":{
"first":"First",
"first_title":"First Page",
"last":"Last",
"last_title":"Last Page",
"prev":"Prev",
"prev_title":"Prev Page",
"next":"Next",
"next_title":"Next Page",
},
"headerFilters":{
"default":"filter column...",
"columns":{
}
}
},
//setup options
options: {
colMinWidth:"40px", //minimum global width for a column
colResizable:true, //resizable columns
colVertAlign:"top", //vertical alignment of column headers
height:false, //height of tabulator
fitColumns:false, //fit colums to width of screen;
movableCols:false, //enable movable columns
movableRows:false, //enable movable rows
movableRowHandle:"<div></div><div></div><div></div>", //handle for movable rows
locale:"en-gb", //durrent system language
langs:{},
persistentLayout:false, //store cookie with column _styles
persistentLayoutID:"", //id for stored cookie
pagination:false, //enable pagination
paginationSize:false, //size of pages
paginationElement:false, //element to hold pagination numbers
paginationDataReceived:{ //pagination data received from the server
"current_page":"current_page",
"last_page":"last_page",
"data":"data",
},
paginationDataSent:{ //pagination data sent to the server
"page":"page",
"size":"size",
"sort":"sort",
"sort_dir":"sort_dir",
"filter":"filter",
"filter_value":"filter_value",
"filter_type":"fitler_type",
},
paginator:false, //pagination url string builder
progressiveRender:false, //enable progressive rendering
progressiveRenderSize:20, //block size for progressive rendering
progressiveRenderMargin:200, //disance in px before end of scroll before progressive render is triggered
headerFilterPlaceholder: "", //placeholder text to display in header filters
headerFilterColumnPlaceholders:{}, //placeholders by column
tooltips: false, //Tool tip value
tooltipsHeader: false, //Tool tip for headers
columns:false,//store for colum header info
data:false, //store for initial table data if set at construction
index:"id",
sortable:true, //global default for sorting
dateFormat: "dd/mm/yyyy", //date format to be used for sorting
sortBy:"id", //defualt column to sort by
sortDir:"desc", //default sort direction
groupBy:false, //enable table grouping and set field to group by
groupStartOpen:true, //starting state of group
groupHeader:function(value, count, data){ //header layout function
return value + "<span>(" + count + " " + ((count === 1) ? "item" : "items") + ")</span>";
},
rowFormatter:false, //row formatter callback
addRowPos:"bottom", //position to insert blank rows, top|bottom
selectable:"highlight", //highlight rows on hover
selectableRollingSelection:true, //roll selection once maximum number of selectable rows is reached
selectablePersistence:true, // maintain selection when table view is updated
selectableCheck:function(data, row){return true;}, //check wheather row is selectable
responsiveLayout:false, //enable responsive column layout
ajaxURL:false, //url for ajax loading
ajaxParams:{}, //params for ajax loading
ajaxConfig:"get", //ajax request type
showLoader:true, //show loader while data loading
loader:"<div class='tabulator-loading'>Loading Data</div>", //loader element
loaderError:"<div class='tabulator-error'>Loading Error</div>", //loader element
//Callbacks from events
rowClick:function(){},
rowDblClick:function(){},
rowMouseEnter:function(){},
rowMouseLeave:function(){},
rowAdded:function(){},
rowDeleted:function(){},
rowContext:function(){},
rowMoved:function(){},
rowUpdated:function(){},
rowSelectionChanged:function(){},
cellEdited:function(){},
colMoved:function(){},
colTitleChanged:function(){},
dataLoading:function(){},
dataLoaded:function(){},
dataLoadError:function(){},
dataEdited:function(){},
ajaxResponse:false,
dataFiltering:function(){},
dataFiltered:function(){},
dataSorting:function(){},
dataSorted:function(){},
renderStarted:function(){},
renderComplete:function(){},
pageLoaded:function(){},
localized:function(){},
tableBuilding:function(){},
tableBuilt:function(){},
},
////////////////// Element Construction //////////////////
//constructor
_create: function(){
var self = this;
var element = self.element;
//initialize arrays
self.selectedRows = [];
self.selectPrev = [];
self.columnList = [];
//prevent column array being copied over when not explicitly set
if(!self.options.columns){
self.options.columns = [];
}
if(element.is("table")){
self._parseTable();
}else{
self._buildElement();
}
},
//parse table element to create data set
_parseTable:function(){
var self = this;
var element = self.element;
var options = self.options;
var rows = $("tbody tr", element);
var headers = $("th", element);
var hasIndex = false;
var columns = options.columns;
//find column if it has already been defined
function search(title){
var match = false;
$.each(columns, function(index, column) {
if(column.title === title){
match = column;
return false;
}
});
return match;
}
//get attributes of cell
var attributes = element[0].attributes;
function attribValue(value){
if(value === "true"){
return true;
}
if(value === "false"){
return false;
}
return value;
}
//check for tablator inline options
for(var index in attributes){
var attrib = attributes[index];
var name;
if(attrib && attrib.name && attrib.name.indexOf("tabulator-") === 0){
name = attrib.name.replace("tabulator-", "");
for(var key in options){
if(key.toLowerCase() == name){
options[key] = attribValue(attrib.value);
}
}
}
}
//build columns from table header if they havnt been set;
if(headers.length){
//list of possible attributes
var attribList = ["title", "field", "align", "width", "minWidth", "frozen", "sortable", "sorter", "formatter", "onClick", "onDblClick", "onContext", "editable", "editor", "visible", "cssClass", "tooltip", "tooltipHeader", "editableTitle", "headerFilter", "mutator", "mutateType", "accessor"];
//create column array from headers
headers.each(function(index){
var header = $(this);
var exists = false;
var attributes = header[0].attributes;
var col = search(header.text());
if(col){
exists = true;
}else{
col = {title:header.text()};
}
if(!col.field) {
col.field = header.text().toLowerCase().replace(" ", "_");
}
$("td:eq(" + index + ")", rows).data("field", col.field)
var width = header.attr("width");
if(width && !col.width) {
col.width = width;
}
if(col.field == options.index){
hasIndex = true;
}
//check for tablator inline options
for(var index in attributes){
var attrib = attributes[index];
var name;
if(attrib && attrib.name && attrib.name.indexOf("tabulator-") === 0){
name = attrib.name.replace("tabulator-", "");
attribList.forEach(function(key){
if(key.toLowerCase() == name){
col[key] = attribValue(attrib.value);
}
});
}
}
if(!exists){
columns.push(col)
}
});
}else{
//create blank table headers
headers = $("tr:first td", element);
headers.each(function(index){
var col = {title:"", field:"col" + index};
$("td:eq(" + index + ")", rows).data("field", col.field)
var width = $(this).attr("width");
if(width){
col.width = width;
}
columns.push(col);
});
}
self.data = [];
//iterate through table rows and build data set
rows.each(function(rowIndex){
var item = {};
//create index if the dont exist in table
if(!hasIndex){
item[options.index] = rowIndex;
}
//add row data to item
$("td", $(this)).each(function(colIndex){
item[$(this).data("field")] = $(this).html();
});
self.data.push(item);
});
//create new element
var newElement = $("<div></div>");
//transfer attributes to new element
var attributes = element.prop("attributes");
// loop through attributes and apply them on div
$.each(attributes, function(){
newElement.attr(this.name, this.value);
});
// replace table with div element
element.replaceWith(newElement);
options.data = self.data;
newElement.tabulator(options);
},
//build tabulator element
_buildElement: function(){
var self = this;
var options = self.options;
var element = self.element;
options.tableBuilding();
//set current locale
self.setLocale(self.options.locale);
//// backwards compatability options adjustments ////
//old persistan column layout adjustment
if( typeof options.columnLayoutCookie != 'undefined'){
options.persistentLayout = options.columnLayoutCookie;
options.persistentLayoutID = options.columnLayoutCookieID;
}
//ajax type backwards compatability
if(options.ajaxType){
options.ajaxConfig = options.ajaxType;
}
/////////////////////////////////////////////////////
//setup persistent layout storage if needed
if(self.options.persistentLayout){
//determine persistent layout storage type
self.options.persistentLayout = self.options.persistentLayout !== true ? self.options.persistentLayout : (typeof window.localStorage !== 'undefined' ? "local" : "cookie");
//set storage tag
self.options.persistentLayoutID = "tabulator-" + (self.options.persistentLayoutID ? self.options.persistentLayoutID : self.element.attr("id") ? self.element.attr("id") : "");
}
options.colMinWidth = isNaN(options.colMinWidth) ? options.colMinWidth : options.colMinWidth + "px";
if(options.height){
options.height = isNaN(options.height) ? options.height : options.height + "px";
element.css({"height": options.height});
}
element.addClass("tabulator").attr("role", "grid");
element.empty();
self.header = $("<div class='tabulator-header'></div>")
self.tableHolder = $("<div class='tabulator-tableHolder'></div>");
var scrollTop = 0;
var scrollLeft = 0;
self.tableHolder.scroll(function(){
//scroll header along with table body
var holder = $(this);
var left = holder.scrollLeft();
self.header.scrollLeft(left);
var hozAdjust = 0;
//adjust for vertical scrollbar moving table when present
var scrollWidth = self.header[0].scrollWidth - self.element.innerWidth();
if(left > scrollWidth){
hozAdjust = left - scrollWidth
self.header.css("margin-left", -(hozAdjust));
}else{
self.header.css("margin-left", 0);
}
//keep frozen columns fixed in position
self._calcFrozenColumnsPos(hozAdjust + 3);
//trigger progressive rendering on scroll
if(self.options.progressiveRender && scrollTop != holder.scrollTop() && scrollTop < holder.scrollTop()){
if(!self.progressiveRenderLoading){
if(holder[0].scrollHeight - holder.innerHeight() - holder.scrollTop() < self.options.progressiveRenderMargin){
if(self.options.progressiveRender == "remote"){
if(self.paginationCurrentPage <= self.paginationMaxPage){
self.progressiveRenderLoading = true;
self._renderTable(true);
}
}else{
if(self.paginationCurrentPage < self.paginationMaxPage){
self.paginationCurrentPage++;
self._renderTable(true);
}
}
}
}else{
self.progressiveRenderLoadingNext = true;
}
}
scrollTop = holder.scrollTop();
});
//create scrollable table holder
self.table = $("<div class='tabulator-table'></div>");
//build pagination footer if needed
if(options.pagination){
if(options.pagination === true){
options.pagination = "local"; //convert old pagination style to new
}
if(!options.paginationElement){
options.paginationElement = $("<div class='tabulator-footer'></div>");
self.footer = options.paginationElement;
}
self.paginator = $("<span class='tabulator-paginator'><span class='tabulator-page' data-page='first' role='button' aria-label='" + self.lang.pagination.first_title + "' title='" + self.lang.pagination.first_title + "'>" + self.lang.pagination.first + "</span><span class='tabulator-page' data-page='prev' role='button' aria-label='" + self.lang.pagination.prev_title + "' title='" + self.lang.pagination.prev_title + "'>" + self.lang.pagination.prev + "</span><span class='tabulator-pages'></span><span class='tabulator-page' data-page='next' role='button' aria-label='" + self.lang.pagination.next_title + "' title='" + self.lang.pagination.next_title + "'>" + self.lang.pagination.next + "</span><span class='tabulator-page' data-page='last' role='button' aria-label='" + self.lang.pagination.last_title + "' title='" + self.lang.pagination.last_title + "'>" + self.lang.pagination.last + "</span></span>");
self.paginator.on("click", ".tabulator-page", function(){
if(!$(this).hasClass("disabled")){
self.setPage($(this).data("page"));
}
});
options.paginationElement.append(self.paginator);
}
//layout columns
if(options.persistentLayout){
self._getPersistentCol();
}else{
self._colLayout();
}
},
//set options
_setOption: function(option, value){
var self = this;
//block update if option cannot be updated this way
if(["columns"].indexOf(option) > -1){
return false;
}
//set option to value
$.Widget.prototype._setOption.apply(this, arguments);
//trigger appropriate table response
if(["colMinWidth", "colResizable", "fitColumns", "movableCols", "movableRows", "movableRowHandle", "sortable", "groupBy", "groupHeader", "rowFormatter", "selectable"].indexOf(option) > -1){
//triger rerender
self._renderTable();
}else if(["height", "pagination", "paginationSize", "tooltips"].indexOf(option) > -1){
//triger render/reset page
if(self.options.pagination){
self.setPage(1);
}else{
self._renderTable();
}
}else if(["dateFormat", "sortBy", "sortDir"].indexOf(option) > -1){
//trigger sort
if(self.sortCurCol){
self.sort(self.sortCurCol, self.sortCurDir);
}
}else if(["index"].indexOf(option) > -1){
//trigger reparse data
self._parseData(self.data);
}else if(["paginationElement"].indexOf(option) > -1){
//trigger complete redraw
}
},
////////////////// Localization Functions //////////////////
//set current locale
setLocale:function(desiredLocale){
var self = this;
var locale = false; //hold the matching locale
//fill in any matching languge values
function traverseLang(trans, path){
for(var prop in trans){
if(typeof trans[prop] == "object"){
if(!path[prop]){
path[prop] = {};
}
traverseLang(trans[prop], path[prop]);
}else{
path[prop] = trans[prop];
}
}
}
//determing correct locale to load
if(desiredLocale === true && navigator.language){
//get local from system
desiredLocale = navigator.language.toLowerCase();
}
if(desiredLocale){
if(self.options.langs[desiredLocale]){
locale = desiredLocale;
}else{
//see if matching top level local is present
var prefix = desiredLocale.split("-")[0];
if(self.options.langs[prefix]){
locale = prefix;
}
}
}
if(self.options.headerFilterPlaceholder){
self.defaultLang.headerFilters.default = self.options.headerFilterPlaceholder;
}
if(self.options.headerFilterColumnPlaceholders){
self.defaultLang.headerFilters.columns = self.options.headerFilterColumnPlaceholders;
}
//load default lang template
self.lang = $.extend(true, [], self.defaultLang);
if(locale){
traverseLang(self.options.langs[locale], self.lang);
}
self.options.locale = locale;
//update ui elements that need translating
if(!self.firstRender){
self._updateLocaleText();
}
//triger localized callback
self.options.localized(locale, self.lang);
return locale;
},
//quick update of elements with local based text
_updateLocaleText:function(){
var self = this;
//update column titles
self.columnList.forEach(function(column){
if(column.field){
$(".tabulator-col[data-field=" + column.field + "] .tabulator-col-title", self.header).text(self.lang.columns[column.field] || column.title);
}
});
//update pagination if enabled
if(self.options.pagination){
for(var prop in self.lang.pagination){
var propParts = prop.split("_");
var element = $(".tabulator-paginator .tabulator-page[data-page=" + propParts[0] + "]", self.element);
if (propParts.length > 1){
element.attr("title",self.lang.pagination[prop])
.attr("aria-label",self.lang.pagination[prop]);
}else{
element.text(self.lang.pagination[prop]);
}
}
}
//redraw incase column headers change width
self.redraw(true);
},
//return the current locale
getLocale:function(){
var self = this;
return self.options.locale;
},
//return the language definitions for the curent locale
getLang:function(){
var self = this;
var lang = self.options.langs[self.options.locale]
return lang ? lang : false;
},
////////////////// General Public Functions //////////////////
//get number of elements in dataset
dataCount:function(){
return this.data.length;
},
//redraw list without updating data
redraw:function(fullRedraw){
var self = this;
//redraw columns
if(self.options.fitColumns || self.options.responsiveLayout || fullRedraw){
self._colRender();
}
//reposition loader if present
if(self.element.innerHeight() > 0){
var msg = $(".tabulator-loader-msg", self.loaderDiv);
msg.css({"margin-top":(self.element.innerHeight() / 2) - (msg.outerHeight()/2)})
}
self._calcFrozenColumnsPos();
//trigger row restyle
self._styleRows(true);
if(fullRedraw){
self._renderTable();
}
},
//trigger file download
download:function(type, filename, options){
var self = this;
//create temporary link element to trigger download
var element = document.createElement('a');
if(typeof type === "function"){
//create the download link
element.setAttribute('href', type(self.columnList, self.activeData, options));
}else{
switch(type){
case "csv":
var delimiter = options && options.delimiter ? options.delimiter : ",";
//get field lists
var titles = [];
var fields = [];
self.columnList.forEach(function(column){
if(column.field){
titles.push('"' + String(column.title).split('"').join('""') + '"');
fields.push(column.field);
}
})
//generate header row
var fileContents = [titles.join(delimiter)];
//generate each row of the table
self.activeData.forEach(function(row){
var rowData = [];
fields.forEach(function(field){
var value = typeof row[field] == "object" ? JSON.stringify(row[field]) : row[field];
//escape uotation marks
rowData.push('"' + String(value).split('"').join('""') + '"');
})
fileContents.push(rowData.join(delimiter));
});
//create the download link
element.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(fileContents.join("\n")));
break;
case "json":
var fileContents = JSON.stringify(self.activeData, null, '\t');
//create the download link
element.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(fileContents));
break;
default:
return false;
break;
}
}
//set file title
element.setAttribute('download', filename || "Tabulator." + (typeof type === "function" ? "txt" : type));
//trigger download
element.style.display = 'none';
document.body.appendChild(element);
element.click();
//remove temporary link element
document.body.removeChild(element);
return true;
},
////////////////// Column Manipulation //////////////////
//set column style cookie
_setPersistentCol:function(){
var self = this;
//parse styles from columns
function parseCols(columns){
var cols = [];
columns.forEach(function(column){
var style = {
field: column.field,
width: column.width,
visible: column.visible,
};
if(column.columns){
style.title = column.title;
style.columns = parseCols(column.columns);
}
cols.push(style);
})
return cols;
}
//create array of column styles only
var columnStyles = parseCols(self.options.columns);
//JSON format column data
var data = JSON.stringify(columnStyles);
if(self.options.persistentLayout == "cookie"){
//set cookie expiration far in the future
var expDate = new Date();
expDate.setDate(expDate.getDate() + 10000);
//save cookie
document.cookie = self.options.persistentLayoutID + "=" + data + "; expires=" + expDate.toUTCString();
}else{
//save data to local storage
localStorage.setItem(self.options.persistentLayoutID, data);
}
},
//set Column style cookie
_getPersistentCol:function(){
var self = this;
var colString = "";
if(self.options.persistentLayout == "cookie"){
//find cookie
var cookie = document.cookie;
var cookiePos = cookie.indexOf(self.options.persistentLayoutID + "=");
//if cookie exists, decode and load column data into tabulator
if(cookiePos > -1){
cookie = cookie.substr(cookiePos);
var end = cookie.indexOf(";");
if(end > -1){
cookie = cookie.substr(0, end);
}
colString = cookie.replace(self.options.persistentLayoutID + "=", "");
}
}else{
//find loocal storage value
var colString = localStorage.getItem(self.options.persistentLayoutID);
}
if(colString){
self.setColumns(JSON.parse(colString), true);
}else{
self._colLayout();
}
},
//set tabulator columns
setColumns: function(columns, update){
var self = this;
//update column properties
function updateCols(oldCols, newCols){
newCols.forEach(function(item, to){
var type = item.columns ? "group" : (item.field ? "field" : "object");
var from = search(oldCols, item, type);
if(from !== false){
var column = oldCols.splice(from, 1)[0];
column.width = item.width;
column.visible = item.visible;
oldCols.splice(to , 0, column);
if(type == "group"){
updateCols(column.columns, item.columns);
}
}
});
}
//find matching column
function search(columns, col, type){
var match = false;
$.each(columns, function(i, column){;
switch(type){
case "group":
if(col.title === column.title && col.columns.length === column.columns.length){
match = i;
}
break;
case "field":
if(col.field === column.field){
match = i;
}
break;
case "object":
if(col === column){
match = i;
}
break;
}
if(match !== false){
return false;
}
});
return match;
}
if(Array.isArray(columns)){
//if updating columns work through exisiting column data
if(update){
updateCols(self.options.columns, columns);
}else{
// if replaceing columns, replace columns array with new
self.options.columns = columns;
}
//Trigger Redraw