forked from wootapa/watable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.watable.js
1410 lines (1243 loc) · 79.3 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.08
Copyright (c) 2012 Andreas Petersson([email protected])
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
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
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; //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 _uniqueCols = {}; //array with checked rows
var _checkToggleChecked = false; //check-all toggle state
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();
//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) {
$('<i class="icon-info-sign"></i>').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) $('<i class="icon-chevron-down pull-right"></i>').appendTo(headCell);
else $('<i class="icon-chevron-up pull-right"></i>').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) elem.prop('checked', true).removeClass('indeterminate');
else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
else if (colProps.filter == '') elem.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"><i class="icon-chevron-right"></i></span>').on('click', {op: "l"}, priv.dpOpChanged).appendTo(dp);
$('<span class="add-on"><i class="icon-chevron-left"></i></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) {
$.map(_filterCols, function (colProps, col) {
if (col == column) {
if (colProps.col.type == 'bool') {
if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
else if (colProps.filter == '') elem.addClass('indeterminate');
}
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', priv.rowClicked);
//find out what rows to show next...
var rowsAdded = 0;
_data.toRow = _data.fromRow + priv.options.pageSize;
if (_data.toRow > _data.rows.length)
_data.toRow = _data.rows.length;
//slice out the chunk of data we need and create rows
$.each(_data.rows.slice(_data.fromRow, _data.toRow), function (index, props) {
var row = $('<tr></tr>').appendTo(_body);
//create checkbox
if (_uniqueCol && priv.options.checkboxes) {
var check = _uniqueCols[props[_uniqueCol]] != undefined ? 'checked' : '';
var checkable = props['checkable'] === false ? 'disabled' : '';
var cell = $('<td></td>').appendTo(row);
$('<input class="unique" {0} {1} type="checkbox" />'.f(check, checkable)).appendTo(cell);
}
//create cells
for (var i = 0; i < colsSorted.length; i++) {
var key = colsSorted[i];
var val = props[key];
if (!_data.cols[key]) return;
if (_data.cols[key].unique) row.data('unique', val);
if (!_data.cols[key].hidden) {
var cell = $('<td></td>').appendTo(row);
cell.data('column', key);
if (val === undefined) continue;
var format = props[key + 'Format'] || _data.cols[key].format || '{0}';
switch (_data.cols[key].type) {
case "string":
cell.html(format.f(val));
break;
case "number":
val = (+val);
var forceDecimals = !isNaN(_data.cols[key].decimals);
if (forceDecimals) cell.html(format.f(val.toFixed(_data.cols[key].decimals)));
else {
(val || 0) % 1 === 0
? cell.html(format.f(val))
: cell.html(format.f(val.toFixed(priv.options.types.number.decimals || 2)));
}
break;
case "date":
val = new priv.ext.XDate(val, priv.options.types.date.utc === true).toString(priv.options.types.date.format || 'yyyy-MM-dd HH:mm:ss');
cell.html(format.f(val));
break;
case "bool":
$('<input type="checkbox" {0} disabled />'.f(val ? "checked" : "")).appendTo(cell);
break;
}
}
}
rowsAdded++;
//enough rows created?
if (rowsAdded >= priv.options.pageSize) {
_data.toRow = _data.fromRow + rowsAdded;
return false;
}
});
if (_currPage == 1) {
_pageSize = rowsAdded;
_totalPages = Math.round(Math.ceil(_data.rows.length / _pageSize));
}
//pad with empty rows if we're at last page.
if (_currPage == _totalPages) {
while (rowsAdded < _pageSize) {
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);
});
rowsAdded++;
}
}
//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);
}
//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.fromRow + 1, Math.min(_data.toRow, _data.rows.length), _data.rows.length)).appendTo(footCell);
else {
$('<p>No results</p>').appendTo(footCell);
_totalPages = 0;
}
//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 footPagerDiv = $('<div class="pagination"></div>').appendTo(footDiv);
var footPagerUl = $('<ul></ul>').appendTo(footPagerDiv);
$('<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));
}
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 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 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);
$.each(_data.cols, function (col, props) {
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 dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-list"></i> </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)});
};
/*
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.fromRow = _data && _data.fromRow || 0;
data.toRow = _data && _data.toRow || 0;
//use previous column definitions?
skipCols = skipCols || false;
if (skipCols) data.cols = _data.cols;
else _filterCols = {};
_data = data;
_data.rowsOrg = _data.rows;
//we might have more/less data now. Recalculate stuff.
if (_currPage > 1) {
_data.toRow = Math.min(_data.rows.length, _data.toRow);
_data.fromRow = _data.toRow - _pageSize;
_data.fromRow = Math.max(_data.fromRow, 0);
_currPage = Math.ceil(_data.fromRow / _pageSize) + 1;
_totalPages = Math.ceil(_data.rows.length / _pageSize);
} else {
_data.fromRow = 0;
if (priv.options.pageSize != -1)
_data.toRow = _data.fromRow + priv.options.pageSize;
_data.toRow = Math.max(_data.toRow, _data.rows.length);
}
//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) {
if (props.filter == undefined) props.filter = true;
if (props.filter && typeof props.type != "bool" && typeof props.filter != "boolean") {
_filterCols[col] = _filterCols[col] || {
filter: String(props.filter),
col: props
};
}
}
});
//keep any previously checked rows around?
if (resetChecked === true || resetChecked === undefined)
_uniqueCols = {};
else {
for (var key in _uniqueCols)
_uniqueCols[key] = priv.getRow(key);
}
if (_uniqueCol) {
//create a unique column definition
_data.cols["unique"] = {
column: "unique",
type: "unique",
index: -1,
hidden: true
};
//add rows that needs to be pre-checked
$.each(_data.rows, function (index, row) {
if (row["checked"] === true)
_uniqueCols[row[_uniqueCol]] = row;
});
}
_head = undefined;
_body = undefined;
_foot = undefined;
priv.filter();
priv.sort();
priv.createTable();
};
/*
filters the data.
*/
priv.filter = function () {
if (!priv.options.filter) return;
if (Object.keys(_filterCols).length == 0) return;
//get a fresh copy of the data
_data.rows = $.extend(true, {}, _data.rowsOrg);
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]);
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;
});
if (!row[col + 'Format'] && !colProps.col.format) {
row[col + 'Format'] = 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) {
if (!row[col + 'Format'] && !colProps.col.format) {
var pre = val.substring(0, pos);
var match = val.substring(pos, pos + filter.length);
var post = val.substring(pos + filter.length, row[col].length);
row[col + 'Format'] = '{0}<span class="filter">{1}</span>{2}'.f(pre, match, post);
}
return row;
}
}
});
break;
case "number":
case "date":
var expr = colProps.filter.replace(/\s+/gi, ' ');
var pos = -1, lval, rval, op;
var ne = expr.charAt(0) == '!';
if (ne) expr = expr.substring(1);
//find operator,l/r value
$.each(["..", "="], function(index, operator) {
pos = expr.indexOf(operator);
if (pos >= 0) {
op = operator;
lval = expr.substring(0, pos);
rval = expr.substring(pos + op.length);
lval = parseFloat(lval);
rval = parseFloat(rval);
if (isNaN(lval)) lval = Number.NEGATIVE_INFINITY;
if (isNaN(rval)) rval = Number.MAX_VALUE;
if (colProps.col.type == "date") {
var today = new priv.ext.XDate(priv.options.types.date.utc === true).setHours(0, 0, 0, 0);
lval = today - (lval * -1) * (60 * 60 * 24 * 1000);
rval = today - (rval * -1) * (60 * 60 * 24 * 1000);
}
return false;
}
});
_data.rows = $.map(_data.rows, function (row) {
var match = false;
switch (op) {
case "=":
if (row[col] == rval) match = true;
break;
case "..":
if (colProps.col.type == "date") {
if (row[col] >= lval && row[col] < rval) match = true;
}
else {
if (row[col] >= lval && row[col] <= rval) match = true;
}
break;
default:
break;
}
if (match && !ne ||
!match && ne ||
expr.length == 0 ||
pos < 0)
return row;
});
break;
case "bool":
_data.rows = $.map(_data.rows, function (row) {
if (colProps.filter === '') return row;
if (row[col] != undefined && ((Boolean(row[col]) && colProps.filter) || (!Boolean(row[col]) && !colProps.filter))) return row;
});
break;
case "unique":
_data.rows = $.map(_data.rows, function (row) {
if (colProps.filter === '') return row;
var a = row[_uniqueCol];
var b = _uniqueCols[a] ? _uniqueCols[a][_uniqueCol] : '';
if ((colProps.filter && a === b) || (!colProps.filter && b === '')) return row;
});
break;
}
if (colProps.filter === '') delete _filterCols[colProps.col.column];
});
priv.log('filtering finished in {0} ms.'.f(new priv.ext.XDate() - start));
_currPage = 1;
_data.fromRow = 0;
_body = undefined;
_foot = undefined;
};
/*
sorts the data on the current sorting column
*/
priv.sort = function () {
if (!_data.cols[_currSortCol]) _currSortCol = "";
if (!_currSortCol) return;
var start = new priv.ext.XDate();
priv.log('sorting on col:{0} order:{1}'.f(_currSortCol, _currSortFlip ? "desc" : "asc"));
var isString = (_data.cols[_currSortCol].type == "string");
_data.rows = _data.rows.sort(function (a, b) {
var valA = a[_currSortCol];
var valB = b[_currSortCol];
if (isString) {
if (valA == undefined) valA = '';
if (valB == undefined) valB = '';
if (String(valA).toLowerCase() == String(valB).toLowerCase()) return 0;
if (String(valA).toLowerCase() > String(valB).toLowerCase()) return _currSortFlip ? -1 : 1;
else return _currSortFlip ? 1 : -1;
} else {
valA = (+valA);
valB = (+valB);
if (valA == undefined || isNaN(valA)) {
valA = priv.options.sortEmptyLast ? _currSortFlip ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
}
if (valB == undefined || isNaN(valB)) {
valB = priv.options.sortEmptyLast ? _currSortFlip ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
}
if (valA == valB) return 0;
if (valA > valB) return _currSortFlip ? -1 : 1;
else return _currSortFlip ? 1 : -1;
}
});
priv.log('sorting finished in {0} ms.'.f(new priv.ext.XDate() - start));
};
/*
helper that returns the underlying data by the unique value
*/
priv.getRow = function (unique) {
var start = new priv.ext.XDate();
var row;
$.each(_data.rowsOrg, function (i, r) {
if (r[_uniqueCol] == unique) {
row = r;
return false;
}