forked from wootapa/watable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.watable.js
executable file
·1700 lines (1504 loc) · 109 KB
/
jquery.watable.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
/*
WATable 1.10.3
Copyright (c) 2012 Andreas Petersson(apesv03@gmail.com)
http://wootapa-watable.appspot.com/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function ($, undefined) {
var WATable = function () {
var priv = {}; //private api
var publ = {}; //public api
priv.options = {};
var defaults = {
url: '', //webservice url
urlData: '', //webservice params
urlPost: false, //use POST instead of GET
debug: false, //prints debug info to console
filter: false, //show filter row
columnPicker: false, //show columnpicker
checkboxes: false, //show body checkboxes
checkAllToggle: true, //show check all toggle
actions: '', //holds action links
pageSize: 10, //current pagesize
pageSizePadding: false, //pad with empty rows
pageSizes: [10, 20, 30, 40, 50, 'All'], //available pagesizes
hidePagerOnEmpty: false, //removes pager if no rows
preFill: false, //prefill table with empty rows
sorting: true, // enable column sorting
sortEmptyLast: true, //empty values will be shown last
dataBind: false, //updates table when detecting row data changes
types: { //type specific options
string: {},
number: {},
bool: {},
date: {}
},
transition: undefined, //transition type when paging
transitionDuration: 0.3 //duration of transition in seconds
};
/* bundled scripts */
priv.ext = {};
priv.ext.XDate = /* xdate 0.7 */ function(a,b,c,d){function e(){var b=this instanceof e?this:new e,c=arguments,d=c.length,h;typeof c[d-1]=="boolean"&&(h=c[--d],c=y(c,0,d));if(d)if(d==1)if(d=c[0],d instanceof a||typeof d=="number")b[0]=new a(+d);else if(d instanceof e){var c=b,i=new a(+d[0]);if(f(d))i.toString=G;c[0]=i}else{if(typeof d=="string"){b[0]=new a(0);a:{for(var c=d,d=h||!1,i=e.parsers,j=0,k;j<i.length;j++)if(k=i[j](c,d,b)){b=k;break a}b[0]=new a(c)}}}else b[0]=new a(F.apply(a,c)),h||(b[0]=u(b[0]));else b[0]=new a;typeof h=="boolean"&&g(b,h);return b}function f(a){return a[0].toString===G}function g(b,c,d){if(c){if(!f(b))d&&(b[0]=new a(F(b[0].getFullYear(),b[0].getMonth(),b[0].getDate(),b[0].getHours(),b[0].getMinutes(),b[0].getSeconds(),b[0].getMilliseconds()))),b[0].toString=G}else f(b)&&(b[0]=d?u(b[0]):new a(+b[0]));return b}function h(a,b,c,d,e){var f=x(s,a[0],e),a=x(t,a[0],e),e=b==1?c%12:f(1),g=!1;d.length==2&&typeof d[1]=="boolean"&&(g=d[1],d=[c]);a(b,d);g&&f(1)!=e&&(a(1,[f(1)-1]),a(2,[v(f(0),f(1))]))}function i(a,c,d,e){var d=Number(d),f=b.floor(d);a["set"+B[c]](a["get"+B[c]]()+f,e||!1);f!=d&&c<6&&i(a,c+1,(d-f)*D[c],e)}function j(a,c,d){var a=a.clone().setUTCMode(!0,!0),c=e(c).setUTCMode(!0,!0),f=0;if(d==0||d==1){for(var g=6;g>=d;g--)f/=D[g],f+=s(c,!1,g)-s(a,!1,g);d==1&&(f+=(c.getFullYear()-a.getFullYear())*12)}else d==2?(d=a.toDate().setUTCHours(0,0,0,0),f=c.toDate().setUTCHours(0,0,0,0),f=b.round((f-d)/864e5)+(c-f-(a-d))/864e5):f=(c-a)/[36e5,6e4,1e3,1][d-3];return f}function k(c){var d=c(0),e=c(1),c=c(2),e=new a(F(d,e,c)),f=l(d),c=f;e<f?c=l(d-1):(d=l(d+1),e>=d&&(c=d));return b.floor(b.round((e-c)/864e5)/7)+1}function l(b){b=new a(F(b,0,4));b.setUTCDate(b.getUTCDate()-(b.getUTCDay()+6)%7);return b}function m(a,b,c,e){var f=x(s,a,e),g=x(t,a,e),c=l(c===d?f(0):c);e||(c=u(c));a.setTime(+c);g(2,[f(2)+(b-1)*7])}function n(a,b,c,d,f){var g=e.locales,h=g[e.defaultLocale]||{},i=x(s,a,f),c=(typeof c=="string"?g[c]:c)||{};return o(a,b,function(a){if(d)for(var b=(a==7?2:a)-1;b>=0;b--)d.push(i(b));return i(a)},function(a){return c[a]||h[a]},f)}function o(a,b,c,e,f){for(var g,h,i="";g=b.match(E);){i+=b.substr(0,g.index);if(g[1]){h=i;for(var i=a,j=g[1],k=c,l=e,m=f,n=j.length,q=void 0,r="";n>0;)q=p(i,j.substr(0,n),k,l,m),q!==d?(r+=q,j=j.substr(n),n=j.length):n--;i=h+(r+j)}else g[3]?(h=o(a,g[4],c,e,f),parseInt(h.replace(/\D/g,""),10)&&(i+=h)):i+=g[7]||"'";b=b.substr(g.index+g[0].length)}return i+b}function p(a,c,d,f,g){var h=e.formatters[c];if(typeof h=="string")return o(a,h,d,f,g);else if(typeof h=="function")return h(a,g||!1,f);switch(c){case"fff":return A(d(6),3);case"s":return d(5);case"ss":return A(d(5));case"m":return d(4);case"mm":return A(d(4));case"h":return d(3)%12||12;case"hh":return A(d(3)%12||12);case"H":return d(3);case"HH":return A(d(3));case"d":return d(2);case"dd":return A(d(2));case"ddd":return f("dayNamesShort")[d(7)]||"";case"dddd":return f("dayNames")[d(7)]||"";case"M":return d(1)+1;case"MM":return A(d(1)+1);case"MMM":return f("monthNamesShort")[d(1)]||"";case"MMMM":return f("monthNames")[d(1)]||"";case"yy":return(d(0)+"").substring(2);case"yyyy":return d(0);case"t":return q(d,f).substr(0,1).toLowerCase();case"tt":return q(d,f).toLowerCase();case"T":return q(d,f).substr(0,1);case"TT":return q(d,f);case"z":case"zz":case"zzz":return g?c="Z":(f=a.getTimezoneOffset(),a=f<0?"+":"-",d=b.floor(b.abs(f)/60),f=b.abs(f)%60,g=d,c=="zz"?g=A(d):c=="zzz"&&(g=A(d)+":"+A(f)),c=a+g),c;case"w":return k(d);case"ww":return A(k(d));case"S":return c=d(2),c>10&&c<20?"th":["st","nd","rd"][c%10-1]||"th"}}function q(a,b){return a(3)<12?b("amDesignator"):b("pmDesignator")}function r(a){return!isNaN(+a[0])}function s(a,b,c){return a["get"+(b?"UTC":"")+B[c]]()}function t(a,b,c,d){a["set"+(b?"UTC":"")+B[c]].apply(a,d)}function u(b){return new a(b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate(),b.getUTCHours(),b.getUTCMinutes(),b.getUTCSeconds(),b.getUTCMilliseconds())}function v(b,c){return 32-(new a(F(b,c,32))).getUTCDate()}function w(a){return function(){return a.apply(d,[this].concat(y(arguments)))}}function x(a){var b=y(arguments,1);return function(){return a.apply(d,b.concat(y(arguments)))}}function y(a,b,e){return c.prototype.slice.call(a,b||0,e===d?a.length:e)}function z(a,b){for(var c=0;c<a.length;c++)b(a[c],c)}function A(a,b){b=b||2;for(a+="";a.length<b;)a="0"+a;return a}var B="FullYear,Month,Date,Hours,Minutes,Seconds,Milliseconds,Day,Year".split(","),C=["Years","Months","Days"],D=[12,31,24,60,60,1e3,1],E=/(([a-zA-Z])\2*)|(\((('.*?'|\(.*?\)|.)*?)\))|('(.*?)')/,F=a.UTC,G=a.prototype.toUTCString,H=e.prototype;H.length=1;H.splice=c.prototype.splice;H.getUTCMode=w(f);H.setUTCMode=w(g);H.getTimezoneOffset=function(){return f(this)?0:this[0].getTimezoneOffset()};z(B,function(a,b){H["get"+a]=function(){return s(this[0],f(this),b)};b!=8&&(H["getUTC"+a]=function(){return s(this[0],!0,b)});b!=7&&(H["set"+a]=function(a){h(this,b,a,arguments,f(this));return this},b!=8&&(H["setUTC"+a]=function(a){h(this,b,a,arguments,!0);return this},H["add"+(C[b]||a)]=function(a,c){i(this,b,a,c);return this},H["diff"+(C[b]||a)]=function(a){return j(this,a,b)}))});H.getWeek=function(){return k(x(s,this,!1))};H.getUTCWeek=function(){return k(x(s,this,!0))};H.setWeek=function(a,b){m(this,a,b,!1);return this};H.setUTCWeek=function(a,b){m(this,a,b,!0);return this};H.addWeeks=function(a){return this.addDays(Number(a)*7)};H.diffWeeks=function(a){return j(this,a,2)/7};e.parsers=[function(b,c,d){if(b=b.match(/^(\d{4})(-(\d{2})(-(\d{2})([T ](\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|(([-+])(\d{2})(:?(\d{2}))?))?)?)?)?$/)){var e=new a(F(b[1],b[3]?b[3]-1:0,b[5]||1,b[7]||0,b[8]||0,b[10]||0,b[12]?Number("0."+b[12])*1e3:0));b[13]?b[14]&&e.setUTCMinutes(e.getUTCMinutes()+(b[15]=="-"?1:-1)*(Number(b[16])*60+(b[18]?Number(b[18]):0))):c||(e=u(e));return d.setTime(+e)}}];e.parse=function(a){return+e(""+a)};H.toString=function(a,b,c){return a===d||!r(this)?this[0].toString():n(this,a,b,c,f(this))};H.toUTCString=H.toGMTString=function(a,b,c){return a===d||!r(this)?this[0].toUTCString():n(this,a,b,c,!0)};H.toISOString=function(){return this.toUTCString("yyyy-MM-dd'T'HH:mm:ss(.fff)zzz")};e.defaultLocale="";e.locales={"":{monthNames:"January,February,March,April,May,June,July,August,September,October,November,December".split(","),monthNamesShort:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),dayNames:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),dayNamesShort:"Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(","),amDesignator:"AM",pmDesignator:"PM"}};e.formatters={i:"yyyy-MM-dd'T'HH:mm:ss(.fff)",u:"yyyy-MM-dd'T'HH:mm:ss(.fff)zzz"};z("getTime,valueOf,toDateString,toTimeString,toLocaleString,toLocaleDateString,toLocaleTimeString,toJSON".split(","),function(a){H[a]=function(){return this[0][a]()}});H.setTime=function(a){this[0].setTime(a);return this};H.valid=w(r);H.clone=function(){return new e(this)};H.clearTime=function(){return this.setHours(0,0,0,0)};H.toDate=function(){return new a(+this[0])};e.now=function(){return+(new a)};e.today=function(){return(new e).clearTime()};e.UTC=F;e.getDaysInMonth=v;if(typeof module!=="undefined"&&module.exports)module.exports=e;return e}(Date,Math,Array);
//these holds the actual dom table objects, and is used to identify what parts of the table that needs to be created.
var _cont; //container holding table
var _table; //the table
var _head; //table header
var _headSort; //table header sorting row
var _headFilter; //table header filter row
var _body; //table body
var _foot; //table footer
var _data = {}; //columns and rows
var _currPage = 1; //current page
var _pageSize; //current pagesize
var _totalPages = 1; //total pages
var _currSortCol; //current sorting column
var _currSortFlip = false; //current sorting direction
var _currDpOp; //clicked datepicker operator
var _filterCols = {}; //array with current filters
var _filterTimeout; //timer for delayed filtering
var _uniqueCol; //reference to column with the unique property
var _checkToggleChecked = false; //check-all toggle state
var _dataBind; //true if dataBind
var _reservedRowProps = ['AutoFormat']; //internally used row properties
var _vendors = ["webkit", "moz", "Moz", "ms", "o", "O"]; //vendors prefixes. used for not yet officially supported features.
var _transition = {
supported: undefined, //true if browser supports transitions
doTransition: false, //true if allowed to transition
direction: undefined, //direction of transition.
available: {
'bounce': {
next: {
tin: 'bounceIn',
tout: 'bounceOut'
},
prev: {
tin: 'bounceIn',
tout: 'bounceOut'
}
},
'fade': {
next: {
tin: 'fadeIn',
tout: 'fadeOut'
},
prev: {
tin: 'fadeIn',
tout: 'fadeOut'
}
},
'flip': {
next: {
tin: 'flipInX',
tout: 'flipOutX'
},
prev: {
tin: 'flipInX',
tout: 'flipOutX'
}
},
'rotate': {
next: {
tin: 'rotateInDownLeft',
tout: 'rotateOutDownLeft'
},
prev: {
tin: 'rotateInUpLeft',
tout: 'rotateOutUpLeft'
}
},
'scroll': {
next: {
tin: 'fadeInUp',
tout: 'fadeOutUp'
},
prev: {
tin: 'fadeInDown',
tout: 'fadeOutDown'
}
},
'slide': {
next: {
tin: 'fadeInRight',
tout: 'fadeOutLeft'
},
prev: {
tin: 'fadeInLeft',
tout: 'fadeOutRight'
}
}
}
}
/*
initialize the plugin.
*/
priv.init = function () {
_cont = priv.options.id;
priv.options.types.string = ((priv.options.types || {}).string || {});
priv.options.types.number = ((priv.options.types || {}).number || {});
priv.options.types.bool = ((priv.options.types || {}).bool || {});
priv.options.types.date = ((priv.options.types || {}).date || {});
priv.options.transition = priv.options.transition === true ? 'scroll' : priv.options.transition;
//check support transitions
_transition.supported = priv.supportsTransition();
//check supports dataBinding
_dataBind = (priv.options.dataBind && !!document.addEventListener);
if (priv.options.data) {
priv.setData(priv.options.data);
}
else {
//fill the table with empty cells
if (priv.options.preFill) {
var data = {
cols: {
dummy: {
index: 1,
friendly: " ",
type: "string"
}
},
rows: []
};
for (var i = 0; i < priv.options.pageSize; i++)
data.rows.push({dummy: " "});
priv.setData(data);
}
}
//try call webservice for data
priv.update();
};
/*
creates the table with all its parts and handlers.
note that only the parts we need is created.
(yeah, the function is huge)
*/
priv.createTable = function () {
var start = new priv.ext.XDate();
//create table itself
if (!_table) {
_head = _body = _foot = undefined;
_table = $('<table class="watable table table-striped table-hover table-bordered table-condensed"></table>').appendTo(_cont);
}
//create the header which will later hold both sorting and filtering
if (!_head) {
_table.find('thead').remove();
_headSort = _headFilter = undefined;
_head = $('<thead></thead>').prependTo(_table);
}
//sort the columns in index order
var colsSorted = Object.keys(_data.cols).sort(function (a, b) {
return _data.cols[a].index - _data.cols[b].index;
});
//create the header sorting row
if (!_headSort) {
_head.find('.sort i').tooltip('hide');
_head.find(".sort").remove();
_headSort = $('<tr class="sort"></tr>').prependTo(_head);
//create the checkall toggle
if (_uniqueCol && priv.options.checkboxes) {
var checked = _checkToggleChecked ? 'checked' : '';
var headCell = $('<th></th>').appendTo(_headSort);
if (priv.options.checkAllToggle) {
var elem = $('<input {0} class="checkToggle" type="checkbox" />'.f(checked)).appendTo(headCell);
elem.on('change', priv.checkToggleChanged);
}
}
//create the sortable headers
for (var i = 0; i < colsSorted.length; i++) {
var column = colsSorted[i];
var props = _data.cols[column];
if (!props.hidden) {
var headCell = $('<th></th>').appendTo(_headSort);
var link;
if(priv.options.sorting && props.sorting !== false) {
link = $('<a class="pull-left" href="#">{0}</a>'.f(props.friendly || column));
link.on('click', {column: column}, priv.columnClicked);
}
else {
link = $('<span class="pull-left">{0}</span>'.f(props.friendly || column));
}
link.appendTo(headCell);
if (props.tooltip) {
$('<span class="glyphicon glyphicon-info-sign"></span>').tooltip({
title: props.tooltip.trim(),
html: true,
container: 'body',
placement: 'top',
delay: {
show: 500,
hide: 100
}
}).appendTo(link);
}
//Add sort arrow
if (column == _currSortCol) {
if (_currSortFlip) $('<span class="glyphicon glyphicon-chevron-down pull-right"></span>').appendTo(headCell);
else $('<span class="glyphicon glyphicon-chevron-up pull-right"></span>').appendTo(headCell);
}
}
}
}
//create the header filtering row
if (!_headFilter && priv.options.filter) {
_head.find(".filter").remove();
_headFilter = $('<tr class="filter"></tr>').appendTo(_head);
var headCell;
var elem;
var placeHolder = '';
var tooltip = '';
//create the filter checkbox
if (_uniqueCol && priv.options.checkboxes) {
tooltip = priv.options.types.bool.filterTooltip || 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked';
headCell = $('<th></th>').appendTo(_headFilter);
elem = $('<input class="filter indeterminate" checked type="checkbox" />').appendTo(headCell);
$.map(_filterCols, function (colProps, col) {
if (col == "unique") {
if (colProps.filter == 1)
elem.prop('checked', true).removeClass('indeterminate');
else if (colProps.filter == 0)
elem.prop('checked', false).removeClass('indeterminate');
else
elem.prop('checked', true).addClass('indeterminate');
}
});
if (tooltip) {
elem.tooltip({
title: tooltip.trim(),
html: true,
container: 'body',
trigger: 'hover',
placement: 'top',
delay: {
show: 500,
hide: 100
}
});
}
elem.on('click', {column: "unique"}, priv.filterChanged);
}
//create the column filters
for (var i = 0; i < colsSorted.length; i++) {
var column = colsSorted[i];
var props = _data.cols[column];
tooltip = props.filterTooltip === true ? undefined : props.filterTooltip === false ? '' : props.filterTooltip;
placeHolder = props.placeHolder === true ? undefined : props.placeHolder === false ? '' : props.placeHolder;
if (!props.hidden) {
headCell = $('<th></th>').appendTo(_headFilter);
switch (props.type || 'string') {
case "number":
if (placeHolder == undefined) placeHolder = priv.options.types.number.placeHolder;
placeHolder = (placeHolder === true || placeHolder == undefined) ? '10..20 =50' : placeHolder === false ? '' : placeHolder;
if (tooltip == undefined) tooltip = priv.options.types.number.filterTooltip;
tooltip = (tooltip === true || tooltip == undefined) ? 'Values 10 to 20:<br/>10..20<br/>Values except 10 to 20:<br/>!10..20<br/>Values exactly 50:<br/>=50' : tooltip === false ? '' : tooltip;
elem = $('<input placeholder="{0}" class="filter" type="text" />'.f(placeHolder));
elem.on('keyup', {column: column}, priv.filterChanged);
break;
case "date":
if (placeHolder == undefined) placeHolder = priv.options.types.date.placeHolder;
placeHolder = (placeHolder === true || placeHolder == undefined) ? '-7..0' : placeHolder === false ? '' : placeHolder;
if (tooltip == undefined) tooltip = priv.options.types.date.filterTooltip;
tooltip = (tooltip === true || tooltip == undefined) ? 'Today:<br/>0..1<br/>All except today:<br/>!0..1<br/>A week today excluded:<br/>-7..0' : tooltip === false ? '' : tooltip;
elem = $('<div><input placeholder="{0}" class="filter" type="text" /></div>'.f(placeHolder));
if (priv.options.types.date.datePicker === true || priv.options.types.date.datePicker == undefined)
{
if ($().datepicker)
{
elem.addClass('date-wrap');
var today = new priv.ext.XDate(false).setHours(0, 0, 0, 0).toString('yyyy-MM-dd');
var dp = $('<div style="float:right" class="date" data-date="{0}" data-date-format="{1}" />'.f(today, 'yyyy-mm-dd')).appendTo(elem);
$('<input style="display:none" type="text" />').appendTo(dp);
$('<span class="add-on glyphicon glyphicon-chevron-right"></span>').on('click', {op: "l"}, priv.dpOpChanged).appendTo(dp);
$('<span class="add-on glyphicon glyphicon-chevron-left"></span>').on('click', {op: "r"}, priv.dpOpChanged).appendTo(dp);
dp.datepicker({weekStart:1});
dp.on('changeDate', {column: column, input: $('input.filter', elem)}, priv.dpClicked);
}
else
priv.log('datepicker plugin not found');
}
elem.on('keyup', 'input.filter', {column: column}, priv.filterChanged);
break;
case "bool":
if (tooltip == undefined) tooltip = priv.options.types.bool.filterTooltip;
tooltip = (tooltip === true || tooltip == undefined) ? 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked' : tooltip === false ? '' : tooltip;
elem = $('<input class="filter indeterminate" checked type="checkbox" />');
elem.on('click', {column: column}, priv.filterChanged);
break;
case "string":
if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
placeHolder = (placeHolder === true || placeHolder == undefined) ? 'John Doe' : placeHolder === false ? '' : placeHolder;
if (tooltip == undefined) tooltip = priv.options.types.string.filterTooltip;
tooltip = (tooltip === true || tooltip == undefined) ? 'Find John Doe:<br/>John Doe<br/>Find John and Jane Doe(Regex):<br/>?John Doe|Jane Doe<br/>Find all except John Doe:<br/>!John Doe' : tooltip === false ? '' : tooltip;
elem = $('<input placeholder="{0}" class="filter" type="text" />'.f(placeHolder));
elem.on('keyup', {column: column}, priv.filterChanged);
break;
case "none":
elem = $('<div> </div>');
break;
}
if (tooltip) {
elem.tooltip({
title: tooltip.trim(),
html: true,
container: 'body',
trigger: 'hover',
placement: 'top',
delay: {
show: 500,
hide: 100
}
});
}
if (elem && props.filter !== false) {
$.map(_filterCols, function (colProps, col) {
if (col == column) {
if (colProps.col.type == 'bool') {
if (colProps.filter == 1)
elem.prop('checked', true).removeClass('indeterminate');
else if (colProps.filter == 0)
elem.prop('checked', false).removeClass('indeterminate');
else
elem.prop('checked', true).addClass('indeterminate');
}
else if (colProps.col.type == 'date') {
//dates have the input nested
$('input:first', elem).val(colProps.filter);
}
else{
elem.val(colProps.filter);
}
}
});
elem.appendTo(headCell);
}
}
}
}
//create the body
if (!_body) {
var prevBody = _table.find('tbody');
if (!_transition.doTransition && prevBody.length)
prevBody.remove();
_body = $('<tbody style="display:none"></tbody>').insertAfter(_head);
_body.on('change', '.unique', priv.rowChecked);
_body.on('click', 'td:not(.watable-col-cbunique)', priv.rowClicked);
//find out what rows to show next...
_pageSize = priv.options.pageSize == -1 ? _data.rows.length : Math.min(priv.options.pageSize, _data.rows.length);
_totalPages = Math.ceil(_data.rows.length / _pageSize) || 1;
_currPage = Math.min(_totalPages, _currPage);
_data.meta.rowsRendered = {};
if (_currPage > 1) {
_data.meta.fromRow = Math.max((_pageSize * _currPage) - _pageSize, 0);
_data.meta.toRow = Math.min(_data.meta.fromRow + _pageSize, _data.rows.length);
}
else {
_data.meta.fromRow = 0;
_data.meta.toRow = _pageSize;
}
//slice out the chunk of data we need and create rows
$.each(_data.rows.slice(_data.meta.fromRow, _data.meta.toRow), function (index, row) {
var rowRendered = $('<tr class="{0}"></tr>'.f(index%2 == 0 ? 'odd' : 'even')).appendTo(_body);
if (_uniqueCol) {
_data.meta.rowsRendered[row[_uniqueCol]] = rowRendered;
//create checkbox
if (priv.options.checkboxes) {
var check = _data.meta.rowsChecked[row[_uniqueCol]] != undefined ? 'checked' : '';
var checkable = row['row-checkable'] === false ? 'disabled' : '';
var cell = $('<td class="watable-col-cbunique"></td>').appendTo(rowRendered);
$('<input class="unique" {0} {1} type="checkbox" />'.f(check, checkable)).appendTo(cell);
}
}
//create cells
for (var i = 0; i < colsSorted.length; i++) {
var col = colsSorted[i];
if (!_data.cols[col]) {
return;
}
if (_data.cols[col].unique) {
rowRendered.data('unique', row[col]);
}
if (!_data.cols[col].hidden) {
var cell = $('<td></td>');
priv.renderCell(cell, col, row, rowRendered);
cell.appendTo(rowRendered);
}
}
});
//pad with empty rows?
if (priv.options.pageSize != -1 && (_currPage == _totalPages && _currPage > 1) || priv.options.pageSizePadding) {
var loops = priv.options.pageSize - (_data.meta.toRow - _data.meta.fromRow);
while (loops-- >0) {
var row = $('<tr></tr>').appendTo(_body);
if (_uniqueCol && priv.options.checkboxes) {
var cell = $('<td></td>').appendTo(row);
$('<input disabled type="checkbox" />').appendTo(cell);
}
$.each(_data.cols, function (column, props) {
if (!props.hidden) $('<td> </td>').appendTo(row);
});
}
}
//transition between bodys?
if (prevBody.length && _transition.doTransition) {
var transition = _transition.direction == 1 ? _transition.available[priv.options.transition].next : _transition.available[priv.options.transition].prev;
//animation duration
var vendorCSSProps = {};
$.each(_vendors, function (index, vendor) {
var key = '-{0}-animation-duration'.f(vendor);
vendorCSSProps[key] = '{0}s'.f(priv.options.transitionDuration);
});
prevBody.css(vendorCSSProps);
var fallbackTimer;
var vendorAnimationEnd = $.map(_vendors, function (vendor) { return '{0}AnimationEnd {0}animationend'.f(vendor); }).join(" ");
prevBody.one('{0} animationend'.f(vendorAnimationEnd), function (e) {
clearTimeout(fallbackTimer);
prevBody.remove();
_body.css(vendorCSSProps);
//animate in the current body
_body.one('{0} animationend'.f(vendorAnimationEnd), function (e) {
_body.removeClass('animated {0}'.f(transition.tin));
});
_body.show(0).addClass('animated {0}'.f(transition.tin));
});
//fallback timer to prevent paging from breaking when animationend wont fire
fallbackTimer = setTimeout(function(e) {
priv.log('animate.css seems to be missing!', true);
prevBody.remove();
_body.show(0);
_transition.supported = false;
}, (priv.options.transitionDuration * 1000) /* wait a little longer */ + 500);
//animate out the previous body
prevBody.addClass('animated {0}'.f(transition.tout));
_transition.doTransition = false;
}
else {
_body.show(0);
}
//recreate footer?
_data.meta.rowsFilteredCount = _data.meta.rowsFilteredCount || 0;
if (_data.meta.rowsFilteredCount != _data.rows.length) {
_foot = undefined;
_data.meta.rowsFilteredCount = _data.rows.length;
}
}
//create the footer
if (!_foot) {
_table.find('tfoot').remove();
_foot = $('<tfoot></tfoot>').insertAfter(_body);
var footRow = $('<tr></tr>').appendTo(_foot);
var footCell = $('<td colspan="999"></td>').appendTo(footRow);
//create summary
if (_data.rows.length > 0)
$('<p>Rows {0}-{1} of {2}</p>'.f(_data.meta.fromRow + 1, Math.min(_data.meta.toRow, _data.rows.length), _data.rows.length)).appendTo(footCell);
else {
$('<p>No results</p>').appendTo(footCell);
}
//create the pager.
var lowerPage = _currPage - 2;
var upperPage = _currPage + 2;
if (upperPage > _totalPages) {
var diff = upperPage - _totalPages;
upperPage = _totalPages;
lowerPage -= diff;
}
if (lowerPage < 1) lowerPage = 1;
if (upperPage < 5) upperPage = 5;
var footToolbar = $('<div class="btn-toolbar"></div>').appendTo(footCell);
var footDiv = $('<div class="btn-group"></div>').appendTo(footToolbar);
var footPagerUl = $('<ul class="pagination"></ul>').appendTo(footDiv);
$('<li class="{0}"><a href="#">«</a></li>'.f(_currPage == 1 ? 'disabled' : ''))
.on('click', {pageIndex: _currPage - 1}, priv.pageChanged).appendTo(footPagerUl);
for (var i = lowerPage; i <= upperPage; i++) {
var link;
if (i == _currPage) {
link = $('<li class="active"><a href="#">{0}</a></li>'.f(i));
link.on('click', function(e) { e.preventDefault();} )
}
else {
link = $('<li class="{1}"><a href="#">{0}</a></li>'.f(i, i > _totalPages ? 'disabled' : ''));
link.on('click', {pageIndex: i}, priv.pageChanged);
}
link.appendTo(footPagerUl);
}
$('<li class="{0}"><a href="#">»</a></li>'.f(_currPage == _totalPages ? 'disabled' : ''))
.on('click', {pageIndex: _currPage + 1}, priv.pageChanged).appendTo(footPagerUl);
//create pagesize dropdown
if (priv.options.pageSizes.length) {
var div = $('<div class="btn-group dropup pagesize"></div>').appendTo(footToolbar);
var btn = $('<button class="btn btn-default dropdown-toggle" data-toggle="dropdown" href="#">Rows </button>').appendTo(div);
var span = $('<span class="caret"></span>').appendTo(btn);
var ul = $('<ul class="dropdown-menu">').appendTo(div);
$.each(priv.options.pageSizes, function (index, val) {
var li = $('<li></li>').appendTo(ul);
$('<a href="#">{0}</a>'.f(val)).appendTo(li);
});
div.on('click', 'a', priv.pageSizeChanged);
}
//create columnpicker dropdown
if (priv.options.columnPicker) {
var div = $('<div class="btn-group dropup columnpicker"></div>').appendTo(footToolbar);
var btn = $('<button class="btn btn-default dropdown-toggle" data-toggle="dropdown" href="#">Columns </button>').appendTo(div);
var span = $('<span class="caret"></span>').appendTo(btn);
var ul = $('<ul class="dropdown-menu">').appendTo(div);
for (var i = 0; i < colsSorted.length; i++) {
var col = colsSorted[i];
var props = _data.cols[col];
if (props.type != "unique") {
var li = $('<li></li>').appendTo(ul);
$('<input {0} type="checkbox" title="{1}" value="{1}" > {2}</input>'.f(props.hidden ? '' : 'checked', col, props.friendly || col)).appendTo(li);
}
}
div.on('click', 'input', priv.columnPickerClicked);
}
//create actions dropdown
if (priv.options.actions) {
var div = $('<div class="btn-group dropup actions"></div>').appendTo(footToolbar);
var btn = $('<button class="btn btn-default dropdown-toggle" data-toggle="dropdown" href="#"><span class="glyphicon glyphicon-list"></span> </button>').appendTo(div);
var span = $('<span class="caret"></span>').appendTo(btn);
var ul = $('<ul class="dropdown-menu">').appendTo(div);
if (priv.options.actions.filter) {
var li = $('<li></li>').appendTo(ul);
$('<input {0} type="checkbox" > Filter</input>'.f(priv.options.filter ? 'checked' : '')).appendTo(li);
li.on('click', 'input', function (e) {
priv.options.filter = !priv.options.filter;
_head = undefined;
priv.createTable();
});
}
if (priv.options.actions.columnPicker) {
var li = $('<li></li>').appendTo(ul);
$('<input {0} type="checkbox" > ColumnPicker</input>'.f(priv.options.columnPicker ? 'checked' : '')).appendTo(li);
li.on('click', 'input', function (e) {
priv.options.columnPicker = !priv.options.columnPicker;
_foot = undefined;
priv.createTable();
});
}
if (priv.options.actions.custom) {
$.each(priv.options.actions.custom, function (index, val) {
var li = $('<li></li>').appendTo(ul);
$(val).appendTo(li);
});
}
}
}
if (_data.rows.length == 0 && priv.options.hidePagerOnEmpty)
$('.btn-toolbar', _foot).remove();
priv.log('table created in {0}ms.'.f(new priv.ext.XDate() - start));
if (typeof priv.options.tableCreated == 'function')
priv.options.tableCreated.call(_table.get(0), {table: _table.get(0)});
};
/*
renders a cell
*/
priv.renderCell= function(cell, col, row, renderedRow) {
cell.data('column', col);
//add any cell/column level classes
cell.removeClass();
var cellClasses = $.grep([].concat((row[col + 'Cls'] || '').split(','), (_data.cols[col].cls || '').split(',')),function(n){ return(n)});
$.each(cellClasses, function(i, cellClass) {
cellClass = cellClass.trim();
if (!cell.hasClass(cellClass))
cell.addClass(cellClass);
});
//add any row level classes here as well
var rowClasses = row['row-cls'] || "";
var newClasses = $.grep(rowClasses.split(','),function(n){ return(n)});
var oldClasses = renderedRow.attr('class').split(' ');
var addClasses = $.unique($(newClasses)).not($(oldClasses)).get();
$.each(addClasses, function(i, cls) {
renderedRow.addClass(cls);
});
var removeClasses = $.unique($(oldClasses)).not($(newClasses.concat(['odd','even']))).get();
$.each(removeClasses, function(i, cls) {
renderedRow.removeClass(cls);
});
if (_uniqueCol) {
var cellClass = 'watable-col-{0}'.f(col);
if (!cell.hasClass(cellClass))
cell.addClass(cellClass);
}
var val = row[col];
var format = row[col + 'Format'] ||
_data.cols[col].format ||
row[col + 'AutoFormat'] ||
'{0}';
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
switch (_data.cols[col].type) {
case "string":
val = val || '';
cell.html(format.f(val));
break;
case "number":
val = val || '';
if (isNumber(val)) {
val = (+val);
var forceDecimals = !isNaN(_data.cols[col].decimals);
if (forceDecimals) {
val = val.toFixed(_data.cols[col].decimals);
}
else {
val = val % 1 === 0
? val
: val.toFixed(priv.options.types.number.decimals || 2);
}
}
cell.html(format.f(val));
break;
case "date":
val = val || '';
if (isNumber(val)) {
val = (+val);
val = new priv.ext.XDate(val, _data.cols[col].dateUTC === true || priv.options.types.date.utc === true).toString(_data.cols[col].dateFormat || priv.options.types.date.format || 'yyyy-MM-dd HH:mm:ss');
}
cell.html(format.f(val));
break;
case "bool":
var checkbox = cell.children("input:checkbox");
if(checkbox.length) {
checkbox.prop("checked", val == 1);
} else {
$('<input type="checkbox" {0} disabled />'.f(val == 1 ? "checked" : "")).appendTo(cell);
}
break;
}
};
/*
calls the webservice(if defined).
*/
priv.update = function (callback, skipCols, resetChecked) {
if (!priv.options.url) {
priv.log('no url found');
return;
}
priv.log('requesting data from url:{0} data:{1}'.f(priv.options.url, JSON.stringify(priv.options.urlData) || ''));
var start = new priv.ext.XDate();
$.ajax({
url: priv.options.url,
type: priv.options.urlPost ? 'POST' : 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: priv.options.urlData,
async: true,
success: function (data) {
priv.log('request finished in {0}ms.'.f(new priv.ext.XDate() - start));
//assign the new data
if (data.d && data.d.cols)
priv.setData(data.d, skipCols, resetChecked);
else
priv.setData(data, skipCols, resetChecked);
if (typeof callback == "function")
callback.call(this);
},
error: function (err) {
priv.log('request error: '.f(err));
}
});
};
/*
assigns the new data.
*/
priv.setData = function (pData, skipCols, resetChecked) {
var data = $.extend(true, {}, pData);
data.meta = {};
data.meta.rowsRendered = {};
data.meta.fromRow = _data.meta && _data.meta.fromRow || 0;
data.meta.toRow = _data.meta && _data.meta.toRow || 0;
//use previous column definitions?
skipCols = skipCols || false;
if (skipCols) data.cols = _data.cols;
else _filterCols = {};
_data = data;
_data.meta.rowsAll = pData.rows;
//wash the new data a bit
_uniqueCol = "";
$.each(_data.cols, function (col, props) {
//set sorting
if (!_currSortCol && props.sortOrder && priv.options.sorting && props.sorting !== false) {
_currSortCol = col;
_currSortFlip = props.sortOrder != "asc";
}
//default to string type if missing
if (!props.type) _data.cols[col].type = "string";
//if several unique columns is defined, use the first.
if (props.unique) {
if (!_uniqueCol) _uniqueCol = col;
else props.unique = false;
}
//if index property is missing, create one
if (!props.index) _data.cols[col].index = new priv.ext.XDate();
props.column = col;
//set any initial filter
if (!skipCols) {
props.filter = props.filter == undefined ? '' : props.filter;
if (props.filter !== false) {
_filterCols[col] = _filterCols[col] || {
filter: props.filter,
col: props
};
}
}
});
_data.meta.rowsLookup = {};
//keep any previously checked rows around?
if (resetChecked === true || resetChecked === undefined)
_data.meta.rowsChecked = {};
else {
for (var key in _data.meta.rowsChecked)
_data.meta.rowsChecked[key] = _data.meta.rowsLookup[key];
}
if (_uniqueCol) {
//create a unique column definition
_data.cols["unique"] = {
column: "unique",
type: "unique",
index: -1,
hidden: true
};
_data.meta.rowObservers = {};
$.each(_data.meta.rowsAll, function (index, row) {
//add rows that needs to be pre-checked
if (row["row-checked"] === true) {
_data.meta.rowsChecked[row[_uniqueCol]] = row;
}
//add the row to lookup object, so we can find it fast later on.
_data.meta.rowsLookup[row[_uniqueCol]] = {
index: index,
row: row
};
//add row observer
priv.addRowObserver(row);
});
if (_dataBind) {
_data.meta.rowsObserver = new ArrayObserver(_data.meta.rowsAll).open(priv.rowsChanged);
}
}
_head = undefined;
_body = undefined;
priv.filter();
priv.sort();
priv.createTable();
};
/*
returns data with all,checked,filtered or rendered rows
*/
priv.getData = function (checked, filtered, rendered) {
checked = checked || false;
filtered = filtered || false;
rendered = rendered || false;
//copy complete _data object
var data = $.extend(true, {}, _data);
//remove internal stuff
delete data.cols["unique"];
delete data.meta;
//set the current filters
$.each(data.cols, function(col) {
if (_filterCols[col]) {
data.cols[col].filter = _filterCols[col].filter;
}
});
//set rows
data.rows = filtered ? _data.rows : _data.meta.rowsAll;
if (checked) {
data.rows = $.map(data.rows, function (row, index) {
if (_data.meta.rowsChecked[row[_uniqueCol]]) {
return row;
}
});
}
if (rendered) {
data.rows = $.map(data.rows, function (row, index) {
if (_data.meta.rowsRendered[row[_uniqueCol]]) {
return row;
}
});
}
return data;
};
/*
filters all rows.
*/
priv.filter = function () {
//get a fresh copy of the data
_data.rows = _data.meta.rowsAll.slice();
if (!priv.options.filter) return;
if (Object.keys(_filterCols).length == 0) return;
var start = new priv.ext.XDate();
//for every column with a filter, run through the rows and return the matching rows
$.each(_filterCols, function (col, colProps) {
priv.log('filtering on text:{0} col:{1} type:{2} '.f(colProps.filter, colProps.col.column, colProps.col.type));
switch (colProps.col.type) {
case "string":
var filter = colProps.filter;
var ne = false, regex = false, validRegex = true;
//Escaping first character means cannot be negate or regex
if (filter.charAt(0) == '\\')
filter = filter.substr(1);
else {
var ne = filter.charAt(0) == '!';
if (ne) filter = filter.substring(1);
regex = filter.length > 0 && filter.charAt(0) == "?";
}
if (regex) {
filter = filter.substr(1);
try {filter = new RegExp(filter, "gi");}
catch(err) {
priv.log('invalid regex:{0}'.f(filter), true);
validRegex = false;
}
}
else filter = filter.toLowerCase();
_data.rows = $.map(_data.rows, function (row) {
var val = String(row[col]);
row[col + 'AutoFormat'] = '';
if (regex && validRegex) {
var matches = val.match(filter);
if (!matches && ne) return row;
if (matches && !ne) {
var pos = 0;
$.each(matches, function(index, match) {
var matchMask = '<span class="filter">{0}</span>'.f(match);
pos = val.indexOf(match, pos);
var pre = val.substring(0, pos);
var post = val.substring(pos + match.length);
val = '{0}{1}{2}'.f(pre, matchMask, post);
pos += matchMask.length;
});
row[col + 'AutoFormat'] = val;
return row;
}
}
else {
var pos = val.toLowerCase().indexOf(filter);
if ((pos == -1 && ne) || filter === '') return row;
else if (row[col] != undefined && pos >= 0 && !ne) {