-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.dynatable.js
executable file
·1681 lines (1462 loc) · 57.3 KB
/
jquery.dynatable.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
/*
* jQuery Dynatable plugin 0.3.1
*
* Copyright (c) 2014 Steve Schwartz (JangoSteve)
*
* Dual licensed under the AGPL and Proprietary licenses:
* http://www.dynatable.com/license/
*
* Date: Tue Jan 02 2014
*/
//
(function($) {
var defaults,
mergeSettings,
dt,
Model,
modelPrototypes = {
dom: Dom,
domColumns: DomColumns,
records: Records,
recordsCount: RecordsCount,
processingIndicator: ProcessingIndicator,
state: State,
sorts: Sorts,
sortsHeaders: SortsHeaders,
queries: Queries,
inputsSearch: InputsSearch,
paginationPage: PaginationPage,
paginationPerPage: PaginationPerPage,
paginationLinks: PaginationLinks
},
utility,
build,
processAll,
initModel,
defaultRowWriter,
defaultCellWriter,
defaultAttributeWriter,
defaultAttributeReader;
//-----------------------------------------------------------------
// Cached plugin global defaults
//-----------------------------------------------------------------
defaults = {
features: {
paginate: true,
sort: true,
pushState: true,
search: true,
recordCount: true,
perPageSelect: true
},
table: {
defaultColumnIdStyle: 'camelCase',
columns: null,
headRowSelector: 'thead tr', // or e.g. tr:first-child
bodyRowSelector: 'tbody tr',
headRowClass: null
},
inputs: {
queries: null,
sorts: null,
multisort: ['ctrlKey', 'shiftKey', 'metaKey'],
page: null,
queryEvent: 'blur change',
recordCountTarget: null,
recordCountPlacement: 'after',
paginationLinkTarget: null,
paginationLinkPlacement: 'after',
paginationClass: 'dynatable-pagination-links',
paginationLinkClass: 'dynatable-page-link',
paginationPrevClass: 'dynatable-page-prev',
paginationNextClass: 'dynatable-page-next',
paginationActiveClass: 'dynatable-active-page',
paginationDisabledClass: 'dynatable-disabled-page',
paginationPrev: 'Previous',
paginationNext: 'Next',
paginationGap: [1,2,2,1],
searchTarget: null,
searchPlacement: 'before',
perPageTarget: null,
perPagePlacement: 'before',
perPageText: 'Show: ',
recordCountText: 'Showing ',
processingText: 'Processing...'
},
dataset: {
ajax: false,
ajaxUrl: null,
ajaxCache: null,
ajaxOnLoad: false,
ajaxMethod: 'GET',
ajaxDataType: 'json',
totalRecordCount: null,
queries: {},
queryRecordCount: null,
page: null,
perPageDefault: 10,
perPageOptions: [10,20,50,100],
sorts: {},
sortsKeys: null,
sortTypes: {},
records: null
},
writers: {
_rowWriter: defaultRowWriter,
_cellWriter: defaultCellWriter,
_attributeWriter: defaultAttributeWriter
},
readers: {
_rowReader: null,
_attributeReader: defaultAttributeReader
},
params: {
dynatable: 'dynatable',
queries: 'queries',
sorts: 'sorts',
page: 'page',
perPage: 'perPage',
offset: 'offset',
records: 'records',
record: null,
queryRecordCount: 'queryRecordCount',
totalRecordCount: 'totalRecordCount'
}
};
//-----------------------------------------------------------------
// Each dynatable instance inherits from this,
// set properties specific to instance
//-----------------------------------------------------------------
dt = {
init: function(element, options) {
this.settings = mergeSettings(options);
this.element = element;
this.$element = $(element);
// All the setup that doesn't require element or options
build.call(this);
return this;
},
process: function(skipPushState) {
processAll.call(this, skipPushState);
}
};
//-----------------------------------------------------------------
// Cached plugin global functions
//-----------------------------------------------------------------
mergeSettings = function(options) {
var newOptions = $.extend(true, {}, defaults, options);
// TODO: figure out a better way to do this.
// Doing `extend(true)` causes any elements that are arrays
// to merge the default and options arrays instead of overriding the defaults.
if (options) {
if (options.inputs) {
if (options.inputs.multisort) {
newOptions.inputs.multisort = options.inputs.multisort;
}
if (options.inputs.paginationGap) {
newOptions.inputs.paginationGap = options.inputs.paginationGap;
}
}
if (options.dataset && options.dataset.perPageOptions) {
newOptions.dataset.perPageOptions = options.dataset.perPageOptions;
}
}
return newOptions;
};
build = function() {
this.$element.trigger('dynatable:preinit', this);
for (model in modelPrototypes) {
if (modelPrototypes.hasOwnProperty(model)) {
var modelInstance = this[model] = new modelPrototypes[model](this, this.settings);
if (modelInstance.initOnLoad()) {
modelInstance.init();
}
}
}
this.$element.trigger('dynatable:init', this);
if (!this.settings.dataset.ajax || (this.settings.dataset.ajax && this.settings.dataset.ajaxOnLoad) || this.settings.features.paginate) {
this.process();
}
};
processAll = function(skipPushState) {
var data = {};
this.$element.trigger('dynatable:beforeProcess', data);
if (!$.isEmptyObject(this.settings.dataset.queries)) { data[this.settings.params.queries] = this.settings.dataset.queries; }
// TODO: Wrap this in a try/rescue block to hide the processing indicator and indicate something went wrong if error
this.processingIndicator.show();
if (this.settings.features.sort && !$.isEmptyObject(this.settings.dataset.sorts)) { data[this.settings.params.sorts] = this.settings.dataset.sorts; }
if (this.settings.features.paginate && this.settings.dataset.page) {
var page = this.settings.dataset.page,
perPage = this.settings.dataset.perPage;
data[this.settings.params.page] = page;
data[this.settings.params.perPage] = perPage;
data[this.settings.params.offset] = (page - 1) * perPage;
}
if (this.settings.dataset.ajaxData) { $.extend(data, this.settings.dataset.ajaxData); }
// If ajax, sends query to ajaxUrl with queries and sorts serialized and appended in ajax data
// otherwise, executes queries and sorts on in-page data
if (this.settings.dataset.ajax) {
var _this = this;
var options = {
type: _this.settings.dataset.ajaxMethod,
dataType: _this.settings.dataset.ajaxDataType,
data: data,
error: function(xhr, error) {
},
success: function(response) {
_this.$element.trigger('dynatable:ajax:success', response);
// Merge ajax results and meta-data into dynatables cached data
_this.records.updateFromJson(response);
// update table with new records
_this.dom.update();
if (!skipPushState && _this.state.initOnLoad()) {
_this.state.push(data);
}
},
complete: function() {
_this.processingIndicator.hide();
}
};
// Do not pass url to `ajax` options if blank
if (this.settings.dataset.ajaxUrl) {
options.url = this.settings.dataset.ajaxUrl;
// If ajaxUrl is blank, then we're using the current page URL,
// we need to strip out any query, sort, or page data controlled by dynatable
// that may have been in URL when page loaded, so that it doesn't conflict with
// what's passed in with the data ajax parameter
} else {
options.url = utility.refreshQueryString(window.location.href, {}, this.settings);
}
if (this.settings.dataset.ajaxCache !== null) { options.cache = this.settings.dataset.ajaxCache; }
$.ajax(options);
} else {
this.records.resetOriginal();
this.queries.run();
if (this.settings.features.sort) {
this.records.sort();
}
if (this.settings.features.paginate) {
this.records.paginate();
}
this.dom.update();
this.processingIndicator.hide();
if (!skipPushState && this.state.initOnLoad()) {
this.state.push(data);
}
}
this.$element.trigger('dynatable:afterProcess', data);
};
function defaultRowWriter(rowIndex, record, columns, cellWriter) {
var tr = '';
// grab the record's attribute for each column
for (var i = 0, len = columns.length; i < len; i++) {
tr += cellWriter(columns[i], record);
}
return '<tr>' + tr + '</tr>';
};
function defaultCellWriter(column, record) {
var html = column.attributeWriter(record),
td = '<td';
if (column.hidden || column.textAlign) {
td += ' style="';
// keep cells for hidden column headers hidden
if (column.hidden) {
td += 'display: none;';
}
// keep cells aligned as their column headers are aligned
if (column.textAlign) {
td += 'text-align: ' + column.textAlign + ';';
}
td += '"';
}
return td + '>' + html + '</td>';
};
function defaultAttributeWriter(record) {
// `this` is the column object in settings.columns
// TODO: automatically convert common types, such as arrays and objects, to string
return record[this.id];
};
function defaultAttributeReader(cell, record) {
return $(cell).html();
};
//-----------------------------------------------------------------
// Dynatable object model prototype
// (all object models get these default functions)
//-----------------------------------------------------------------
Model = {
initOnLoad: function() {
return true;
},
init: function() {}
};
for (model in modelPrototypes) {
if (modelPrototypes.hasOwnProperty(model)) {
var modelPrototype = modelPrototypes[model];
modelPrototype.prototype = Model;
}
}
//-----------------------------------------------------------------
// Dynatable object models
//-----------------------------------------------------------------
function Dom(obj, settings) {
var _this = this;
// update table contents with new records array
// from query (whether ajax or not)
this.update = function() {
var rows = '',
columns = settings.table.columns,
rowWriter = settings.writers._rowWriter,
cellWriter = settings.writers._cellWriter;
obj.$element.trigger('dynatable:beforeUpdate', rows);
// loop through records
for (var i = 0, len = settings.dataset.records.length; i < len; i++) {
var record = settings.dataset.records[i],
tr = rowWriter(i, record, columns, cellWriter);
rows += tr;
}
// Appended dynatable interactive elements
if (settings.features.recordCount) {
$('#dynatable-record-count-' + obj.element.id).replaceWith(obj.recordsCount.create());
}
if (settings.features.paginate) {
$('#dynatable-pagination-links-' + obj.element.id).replaceWith(obj.paginationLinks.create());
if (settings.features.perPageSelect) {
$('#dynatable-per-page-' + obj.element.id).val(parseInt(settings.dataset.perPage));
}
}
// Sort headers functionality
if (settings.features.sort && columns) {
obj.sortsHeaders.removeAllArrows();
for (var i = 0, len = columns.length; i < len; i++) {
var column = columns[i],
sortedByColumn = utility.allMatch(settings.dataset.sorts, column.sorts, function(sorts, sort) { return sort in sorts; }),
value = settings.dataset.sorts[column.sorts[0]];
if (sortedByColumn) {
obj.$element.find('[data-dynatable-column="' + column.id + '"]').find('.dynatable-sort-header').each(function(){
if (value == 1) {
obj.sortsHeaders.appendArrowUp($(this));
} else {
obj.sortsHeaders.appendArrowDown($(this));
}
});
}
}
}
// Query search functionality
if (settings.inputs.queries || settings.features.search) {
var allQueries = settings.inputs.queries || $();
if (settings.features.search) {
allQueries = allQueries.add('#dynatable-query-search-' + obj.element.id);
}
allQueries.each(function() {
var $this = $(this),
q = settings.dataset.queries[$this.data('dynatable-query')];
$this.val(q || '');
});
}
obj.$element.find(settings.table.bodyRowSelector).remove();
obj.$element.append(rows);
obj.$element.trigger('dynatable:afterUpdate', rows);
};
};
function DomColumns(obj, settings) {
var _this = this;
this.initOnLoad = function() {
return obj.$element.is('table');
};
this.init = function() {
settings.table.columns = [];
this.getFromTable();
};
// initialize table[columns] array
this.getFromTable = function() {
var $columns = obj.$element.find(settings.table.headRowSelector).children('th,td');
if ($columns.length) {
$columns.each(function(index){
_this.add($(this), index, true);
});
} else {
return $.error("Couldn't find any columns headers in '" + settings.table.headRowSelector + " th,td'. If your header row is different, specify the selector in the table: headRowSelector option.");
}
};
this.add = function($column, position, skipAppend, skipUpdate) {
var columns = settings.table.columns,
label = $column.text(),
id = $column.data('dynatable-column') || utility.normalizeText(label, settings.table.defaultColumnIdStyle),
dataSorts = $column.data('dynatable-sorts'),
sorts = dataSorts ? $.map(dataSorts.split(','), function(text) { return $.trim(text); }) : [id];
// If the column id is blank, generate an id for it
if ( !id ) {
this.generate($column);
id = $column.data('dynatable-column');
}
// Add column data to plugin instance
columns.splice(position, 0, {
index: position,
label: label,
id: id,
attributeWriter: settings.writers[id] || settings.writers._attributeWriter,
attributeReader: settings.readers[id] || settings.readers._attributeReader,
sorts: sorts,
hidden: $column.css('display') === 'none',
textAlign: $column.css('text-align')
});
// Modify header cell
$column
.attr('data-dynatable-column', id)
.addClass('dynatable-head');
if (settings.table.headRowClass) { $column.addClass(settings.table.headRowClass); }
// Append column header to table
if (!skipAppend) {
var domPosition = position + 1,
$sibling = obj.$element.find(settings.table.headRowSelector)
.children('th:nth-child(' + domPosition + '),td:nth-child(' + domPosition + ')').first(),
columnsAfter = columns.slice(position + 1, columns.length);
if ($sibling.length) {
$sibling.before($column);
// sibling column doesn't yet exist (maybe this is the last column in the header row)
} else {
obj.$element.find(settings.table.headRowSelector).append($column);
}
obj.sortsHeaders.attachOne($column.get());
// increment the index of all columns after this one that was just inserted
if (columnsAfter.length) {
for (var i = 0, len = columnsAfter.length; i < len; i++) {
columnsAfter[i].index += 1;
}
}
if (!skipUpdate) {
obj.dom.update();
}
}
return dt;
};
this.remove = function(columnIndexOrId) {
var columns = settings.table.columns,
length = columns.length;
if (typeof(columnIndexOrId) === "number") {
var column = columns[columnIndexOrId];
this.removeFromTable(column.id);
this.removeFromArray(columnIndexOrId);
} else {
// Traverse columns array in reverse order so that subsequent indices
// don't get messed up when we delete an item from the array in an iteration
for (var i = columns.length - 1; i >= 0; i--) {
var column = columns[i];
if (column.id === columnIndexOrId) {
this.removeFromTable(columnIndexOrId);
this.removeFromArray(i);
}
}
}
obj.dom.update();
};
this.removeFromTable = function(columnId) {
obj.$element.find(settings.table.headRowSelector).children('[data-dynatable-column="' + columnId + '"]').first()
.remove();
};
this.removeFromArray = function(index) {
var columns = settings.table.columns,
adjustColumns;
columns.splice(index, 1);
adjustColumns = columns.slice(index, columns.length);
for (var i = 0, len = adjustColumns.length; i < len; i++) {
adjustColumns[i].index -= 1;
}
};
this.generate = function($cell) {
var cell = $cell === undefined ? $('<th></th>') : $cell;
return this.attachGeneratedAttributes(cell);
};
this.attachGeneratedAttributes = function($cell) {
// Use increment to create unique column name that is the same each time the page is reloaded,
// in order to avoid errors with mismatched attribute names when loading cached `dataset.records` array
var increment = obj.$element.find(settings.table.headRowSelector).children('th[data-dynatable-generated]').length;
return $cell
.attr('data-dynatable-column', 'dynatable-generated-' + increment) //+ utility.randomHash(),
.attr('data-dynatable-no-sort', 'true')
.attr('data-dynatable-generated', increment);
};
};
function Records(obj, settings) {
var _this = this;
this.initOnLoad = function() {
return !settings.dataset.ajax;
};
this.init = function() {
if (settings.dataset.records === null) {
settings.dataset.records = this.getFromTable();
if (!settings.dataset.queryRecordCount) {
settings.dataset.queryRecordCount = this.count();
}
if (!settings.dataset.totalRecordCount){
settings.dataset.totalRecordCount = settings.dataset.queryRecordCount;
}
}
// Create cache of original full recordset (unpaginated and unqueried)
settings.dataset.originalRecords = $.extend(true, [], settings.dataset.records);
};
// merge ajax response json with cached data including
// meta-data and records
this.updateFromJson = function(data) {
var records;
if (settings.params.records === "_root") {
records = data;
} else if (settings.params.records in data) {
records = data[settings.params.records];
}
if (settings.params.record) {
var len = records.length - 1;
for (var i = 0; i < len; i++) {
records[i] = records[i][settings.params.record];
}
}
if (settings.params.queryRecordCount in data) {
settings.dataset.queryRecordCount = data[settings.params.queryRecordCount];
}
if (settings.params.totalRecordCount in data) {
settings.dataset.totalRecordCount = data[settings.params.totalRecordCount];
}
settings.dataset.records = records;
};
// For really advanced sorting,
// see http://james.padolsey.com/javascript/sorting-elements-with-jquery/
this.sort = function() {
var sort = [].sort,
sorts = settings.dataset.sorts,
sortsKeys = settings.dataset.sortsKeys,
sortTypes = settings.dataset.sortTypes;
var sortFunction = function(a, b) {
var comparison;
if ($.isEmptyObject(sorts)) {
comparison = obj.sorts.functions['originalPlacement'](a, b);
} else {
for (var i = 0, len = sortsKeys.length; i < len; i++) {
var attr = sortsKeys[i],
direction = sorts[attr],
sortType = sortTypes[attr] || obj.sorts.guessType(a, b, attr);
comparison = obj.sorts.functions[sortType](a, b, attr, direction);
// Don't need to sort any further unless this sort is a tie between a and b,
// so break the for loop unless tied
if (comparison !== 0) { break; }
}
}
return comparison;
}
return sort.call(settings.dataset.records, sortFunction);
};
this.paginate = function() {
var bounds = this.pageBounds(),
first = bounds[0], last = bounds[1];
settings.dataset.records = settings.dataset.records.slice(first, last);
};
this.resetOriginal = function() {
settings.dataset.records = settings.dataset.originalRecords || [];
};
this.pageBounds = function() {
var page = settings.dataset.page || 1,
first = (page - 1) * settings.dataset.perPage,
last = Math.min(first + settings.dataset.perPage, settings.dataset.queryRecordCount);
return [first,last];
};
// get initial recordset to populate table
// if ajax, call ajaxUrl
// otherwise, initialize from in-table records
this.getFromTable = function() {
var records = [],
columns = settings.table.columns,
tableRecords = obj.$element.find(settings.table.bodyRowSelector);
tableRecords.each(function(index){
var record = {};
record['dynatable-original-index'] = index;
$(this).find('th,td').each(function(index) {
if (columns[index] === undefined) {
// Header cell didn't exist for this column, so let's generate and append
// a new header cell with a randomly generated name (so we can store and
// retrieve the contents of this column for each record)
obj.domColumns.add(obj.domColumns.generate(), columns.length, false, true); // don't skipAppend, do skipUpdate
}
var value = columns[index].attributeReader(this, record),
attr = columns[index].id;
// If value from table is HTML, let's get and cache the text equivalent for
// the default string sorting, since it rarely makes sense for sort headers
// to sort based on HTML tags.
if (typeof(value) === "string" && value.match(/\s*\<.+\>/)) {
if (! record['dynatable-sortable-text']) {
record['dynatable-sortable-text'] = {};
}
record['dynatable-sortable-text'][attr] = $.trim($('<div></div>').html(value).text());
}
record[attr] = value;
});
// Allow configuration function which alters record based on attributes of
// table row (e.g. from html5 data- attributes)
if (typeof(settings.readers._rowReader) === "function") {
settings.readers._rowReader(index, this, record);
}
records.push(record);
});
return records; // 1st row is header
};
// count records from table
this.count = function() {
return settings.dataset.records.length;
};
};
function RecordsCount(obj, settings) {
this.initOnLoad = function() {
return settings.features.recordCount;
};
this.init = function() {
this.attach();
};
this.create = function() {
var recordsShown = obj.records.count(),
recordsQueryCount = settings.dataset.queryRecordCount,
recordsTotal = settings.dataset.totalRecordCount,
text = settings.inputs.recordCountText,
collection_name = settings.params.records;
if (recordsShown < recordsQueryCount && settings.features.paginate) {
var bounds = obj.records.pageBounds();
text += "<span class='dynatable-record-bounds'>" + (bounds[0] + 1) + " to " + bounds[1] + "</span> of ";
} else if (recordsShown === recordsQueryCount && settings.features.paginate) {
text += recordsShown + " of ";
}
text += recordsQueryCount + " " + collection_name;
if (recordsQueryCount < recordsTotal) {
text += " (filtered from " + recordsTotal + " total records)";
}
return $('<span></span>', {
id: 'dynatable-record-count-' + obj.element.id,
'class': 'dynatable-record-count',
html: text
});
};
this.attach = function() {
var $target = settings.inputs.recordCountTarget ? $(settings.inputs.recordCountTarget) : obj.$element;
$target[settings.inputs.recordCountPlacement](this.create());
};
};
function ProcessingIndicator(obj, settings) {
this.init = function() {
this.attach();
};
this.create = function() {
var $processing = $('<div></div>', {
html: '<span>' + settings.inputs.processingText + '</span>',
id: 'dynatable-processing-' + obj.element.id,
'class': 'dynatable-processing',
style: 'position: absolute; display: none;'
});
return $processing;
};
this.position = function() {
var $processing = $('#dynatable-processing-' + obj.element.id),
$span = $processing.children('span'),
spanHeight = $span.outerHeight(),
spanWidth = $span.outerWidth(),
$covered = obj.$element,
offset = $covered.offset(),
height = $covered.outerHeight(), width = $covered.outerWidth();
$processing
.offset({left: offset.left, top: offset.top})
.width(width)
.height(height)
$span
.offset({left: offset.left + ( (width - spanWidth) / 2 ), top: offset.top + ( (height - spanHeight) / 2 )});
return $processing;
};
this.attach = function() {
obj.$element.before(this.create());
};
this.show = function() {
$('#dynatable-processing-' + obj.element.id).show();
this.position();
};
this.hide = function() {
$('#dynatable-processing-' + obj.element.id).hide();
};
};
function State(obj, settings) {
this.initOnLoad = function() {
// Check if pushState option is true, and if browser supports it
return settings.features.pushState && history.pushState;
};
this.init = function() {
window.onpopstate = function(event) {
if (event.state && event.state.dynatable) {
obj.state.pop(event);
}
}
};
this.push = function(data) {
var urlString = window.location.search,
urlOptions,
path,
params,
hash,
newParams,
cacheStr,
cache,
// replaceState on initial load, then pushState after that
firstPush = !(window.history.state && window.history.state.dynatable),
pushFunction = firstPush ? 'replaceState' : 'pushState';
if (urlString && /^\?/.test(urlString)) { urlString = urlString.substring(1); }
$.extend(urlOptions, data);
params = utility.refreshQueryString(urlString, data, settings);
if (params) { params = '?' + params; }
hash = window.location.hash;
path = window.location.pathname;
obj.$element.trigger('dynatable:push', data);
cache = { dynatable: { dataset: settings.dataset } };
if (!firstPush) { cache.dynatable.scrollTop = $(window).scrollTop(); }
cacheStr = JSON.stringify(cache);
// Mozilla has a 640k char limit on what can be stored in pushState.
// See "limit" in https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history#The_pushState().C2.A0method
// and "dataStr.length" in http://wine.git.sourceforge.net/git/gitweb.cgi?p=wine/wine-gecko;a=patch;h=43a11bdddc5fc1ff102278a120be66a7b90afe28
//
// Likewise, other browsers may have varying (undocumented) limits.
// Also, Firefox's limit can be changed in about:config as browser.history.maxStateObjectSize
// Since we don't know what the actual limit will be in any given situation, we'll just try caching and rescue
// any exceptions by retrying pushState without caching the records.
//
// I have absolutely no idea why perPageOptions suddenly becomes an array-like object instead of an array,
// but just recently, this started throwing an error if I don't convert it:
// 'Uncaught Error: DATA_CLONE_ERR: DOM Exception 25'
cache.dynatable.dataset.perPageOptions = $.makeArray(cache.dynatable.dataset.perPageOptions);
try {
window.history[pushFunction](cache, "Dynatable state", path + params + hash);
} catch(error) {
// Make cached records = null, so that `pop` will rerun process to retrieve records
cache.dynatable.dataset.records = null;
window.history[pushFunction](cache, "Dynatable state", path + params + hash);
}
};
this.pop = function(event) {
var data = event.state.dynatable;
settings.dataset = data.dataset;
if (data.scrollTop) { $(window).scrollTop(data.scrollTop); }
// If dataset.records is cached from pushState
if ( data.dataset.records ) {
obj.dom.update();
} else {
obj.process(true);
}
};
};
function Sorts(obj, settings) {
this.initOnLoad = function() {
return settings.features.sort;
};
this.init = function() {
var sortsUrl = window.location.search.match(new RegExp(settings.params.sorts + '[^&=]*=[^&]*', 'g'));
settings.dataset.sorts = sortsUrl ? utility.deserialize(sortsUrl)[settings.params.sorts] : {};
settings.dataset.sortsKeys = sortsUrl ? utility.keysFromObject(settings.dataset.sorts) : [];
};
this.add = function(attr, direction) {
var sortsKeys = settings.dataset.sortsKeys,
index = $.inArray(attr, sortsKeys);
settings.dataset.sorts[attr] = direction;
if (index === -1) { sortsKeys.push(attr); }
return dt;
};
this.remove = function(attr) {
var sortsKeys = settings.dataset.sortsKeys,
index = $.inArray(attr, sortsKeys);
delete settings.dataset.sorts[attr];
if (index !== -1) { sortsKeys.splice(index, 1); }
return dt;
};
this.clear = function() {
settings.dataset.sorts = {};
settings.dataset.sortsKeys.length = 0;
};
// Try to intelligently guess which sort function to use
// based on the type of attribute values.
// Consider using something more robust than `typeof` (http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/)
this.guessType = function(a, b, attr) {
var types = {
string: 'string',
number: 'number',
'boolean': 'number',
object: 'number' // dates and null values are also objects, this works...
},
attrType = a[attr] ? typeof(a[attr]) : typeof(b[attr]),
type = types[attrType] || 'number';
return type;
};
// Built-in sort functions
// (the most common use-cases I could think of)
this.functions = {
number: function(a, b, attr, direction) {
return a[attr] === b[attr] ? 0 : (direction > 0 ? a[attr] - b[attr] : b[attr] - a[attr]);
},
string: function(a, b, attr, direction) {
var aAttr = (a['dynatable-sortable-text'] && a['dynatable-sortable-text'][attr]) ? a['dynatable-sortable-text'][attr] : a[attr],
bAttr = (b['dynatable-sortable-text'] && b['dynatable-sortable-text'][attr]) ? b['dynatable-sortable-text'][attr] : b[attr],
comparison;
aAttr = aAttr.toLowerCase();
bAttr = bAttr.toLowerCase();
comparison = aAttr === bAttr ? 0 : (direction > 0 ? aAttr > bAttr : bAttr > aAttr);
// force false boolean value to -1, true to 1, and tie to 0
return comparison === false ? -1 : (comparison - 0);
},
originalPlacement: function(a, b) {
return a['dynatable-original-index'] - b['dynatable-original-index'];
}
};
};
// turn table headers into links which add sort to sorts array
function SortsHeaders(obj, settings) {
var _this = this;
this.initOnLoad = function() {
return settings.features.sort;
};
this.init = function() {
this.attach();
};
this.create = function(cell) {
var $cell = $(cell),
$link = $('<a></a>', {
'class': 'dynatable-sort-header',
href: '#',
html: $cell.html()
}),
id = $cell.data('dynatable-column'),
column = utility.findObjectInArray(settings.table.columns, {id: id});
$link.bind('click', function(e) {
_this.toggleSort(e, $link, column);
obj.process();
e.preventDefault();
});
if (this.sortedByColumn($link, column)) {
if (this.sortedByColumnValue(column) == 1) {
this.appendArrowUp($link);
} else {
this.appendArrowDown($link);
}
}
return $link;
};
this.removeAll = function() {
obj.$element.find(settings.table.headRowSelector).children('th,td').each(function(){
_this.removeAllArrows();
_this.removeOne(this);
});
};
this.removeOne = function(cell) {
var $cell = $(cell),
$link = $cell.find('.dynatable-sort-header');
if ($link.length) {
var html = $link.html();
$link.remove();
$cell.html($cell.html() + html);
}
};
this.attach = function() {
obj.$element.find(settings.table.headRowSelector).children('th,td').each(function(){
_this.attachOne(this);
});
};
this.attachOne = function(cell) {
var $cell = $(cell);
if (!$cell.data('dynatable-no-sort')) {