UNPKG

34.8 kBJavaScriptView Raw
1(function (global, factory) {
2 if (typeof define === "function" && define.amd) {
3 define([], factory);
4 } else if (typeof exports !== "undefined") {
5 factory();
6 } else {
7 var mod = {
8 exports: {}
9 };
10 factory();
11 global.bootstrapTableFilterControl = mod.exports;
12 }
13})(this, function () {
14 'use strict';
15
16 function _classCallCheck(instance, Constructor) {
17 if (!(instance instanceof Constructor)) {
18 throw new TypeError("Cannot call a class as a function");
19 }
20 }
21
22 var _createClass = function () {
23 function defineProperties(target, props) {
24 for (var i = 0; i < props.length; i++) {
25 var descriptor = props[i];
26 descriptor.enumerable = descriptor.enumerable || false;
27 descriptor.configurable = true;
28 if ("value" in descriptor) descriptor.writable = true;
29 Object.defineProperty(target, descriptor.key, descriptor);
30 }
31 }
32
33 return function (Constructor, protoProps, staticProps) {
34 if (protoProps) defineProperties(Constructor.prototype, protoProps);
35 if (staticProps) defineProperties(Constructor, staticProps);
36 return Constructor;
37 };
38 }();
39
40 function _possibleConstructorReturn(self, call) {
41 if (!self) {
42 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
43 }
44
45 return call && (typeof call === "object" || typeof call === "function") ? call : self;
46 }
47
48 var _get = function get(object, property, receiver) {
49 if (object === null) object = Function.prototype;
50 var desc = Object.getOwnPropertyDescriptor(object, property);
51
52 if (desc === undefined) {
53 var parent = Object.getPrototypeOf(object);
54
55 if (parent === null) {
56 return undefined;
57 } else {
58 return get(parent, property, receiver);
59 }
60 } else if ("value" in desc) {
61 return desc.value;
62 } else {
63 var getter = desc.get;
64
65 if (getter === undefined) {
66 return undefined;
67 }
68
69 return getter.call(receiver);
70 }
71 };
72
73 function _inherits(subClass, superClass) {
74 if (typeof superClass !== "function" && superClass !== null) {
75 throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
76 }
77
78 subClass.prototype = Object.create(superClass && superClass.prototype, {
79 constructor: {
80 value: subClass,
81 enumerable: false,
82 writable: true,
83 configurable: true
84 }
85 });
86 if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
87 }
88
89 /**
90 * @author: Dennis Hernández
91 * @webSite: http://djhvscf.github.io/Blog
92 * @version: v2.2.0
93 */
94
95 (function ($) {
96 var Utils = $.fn.bootstrapTable.utils;
97 var UtilsFilterControl = {
98 getOptionsFromSelectControl: function getOptionsFromSelectControl(selectControl) {
99 return selectControl.get(selectControl.length - 1).options;
100 },
101 hideUnusedSelectOptions: function hideUnusedSelectOptions(selectControl, uniqueValues) {
102 var options = UtilsFilterControl.getOptionsFromSelectControl(selectControl);
103
104 for (var i = 0; i < options.length; i++) {
105 if (options[i].value !== '') {
106 if (!uniqueValues.hasOwnProperty(options[i].value)) {
107 selectControl.find(Utils.sprintf('option[value=\'%s\']', options[i].value)).hide();
108 } else {
109 selectControl.find(Utils.sprintf('option[value=\'%s\']', options[i].value)).show();
110 }
111 }
112 }
113 },
114 addOptionToSelectControl: function addOptionToSelectControl(selectControl, _value, text) {
115 var value = $.trim(_value);
116 var $selectControl = $(selectControl.get(selectControl.length - 1));
117 if (!UtilsFilterControl.existOptionInSelectControl(selectControl, value)) {
118 $selectControl.append($('<option></option>').attr('value', value).text($('<div />').html(text).text()));
119 }
120 },
121 sortSelectControl: function sortSelectControl(selectControl) {
122 var $selectControl = $(selectControl.get(selectControl.length - 1));
123 var $opts = $selectControl.find('option:gt(0)');
124
125 $opts.sort(function (a, b) {
126 var aa = $(a).text().toLowerCase();
127 var bb = $(b).text().toLowerCase();
128 if ($.isNumeric(a) && $.isNumeric(b)) {
129 // Convert numerical values from string to float.
130 aa = parseFloat(aa);
131 bb = parseFloat(bb);
132 }
133 return aa > bb ? 1 : aa < bb ? -1 : 0;
134 });
135
136 $selectControl.find('option:gt(0)').remove();
137 $selectControl.append($opts);
138 },
139 existOptionInSelectControl: function existOptionInSelectControl(selectControl, value) {
140 var options = UtilsFilterControl.getOptionsFromSelectControl(selectControl);
141 for (var i = 0; i < options.length; i++) {
142 if (options[i].value === value.toString()) {
143 // The value is not valid to add
144 return true;
145 }
146 }
147
148 // If we get here, the value is valid to add
149 return false;
150 },
151 fixHeaderCSS: function fixHeaderCSS(_ref) {
152 var $tableHeader = _ref.$tableHeader;
153
154 $tableHeader.css('height', '77px');
155 },
156 getCurrentHeader: function getCurrentHeader(_ref2) {
157 var $header = _ref2.$header,
158 options = _ref2.options,
159 $tableHeader = _ref2.$tableHeader;
160
161 var header = $header;
162 if (options.height) {
163 header = $tableHeader;
164 }
165
166 return header;
167 },
168 getCurrentSearchControls: function getCurrentSearchControls(_ref3) {
169 var options = _ref3.options;
170
171 var searchControls = 'select, input';
172 if (options.height) {
173 searchControls = 'table select, table input';
174 }
175
176 return searchControls;
177 },
178 getCursorPosition: function getCursorPosition(el) {
179 if (Utils.isIEBrowser()) {
180 if ($(el).is('input[type=text]')) {
181 var pos = 0;
182 if ('selectionStart' in el) {
183 pos = el.selectionStart;
184 } else if ('selection' in document) {
185 el.focus();
186 var Sel = document.selection.createRange();
187 var SelLength = document.selection.createRange().text.length;
188 Sel.moveStart('character', -el.value.length);
189 pos = Sel.text.length - SelLength;
190 }
191 return pos;
192 }
193 return -1;
194 }
195 return -1;
196 },
197 setCursorPosition: function setCursorPosition(el) {
198 $(el).val(el.value);
199 },
200 copyValues: function copyValues(that) {
201 var header = UtilsFilterControl.getCurrentHeader(that);
202 var searchControls = UtilsFilterControl.getCurrentSearchControls(that);
203
204 that.options.valuesFilterControl = [];
205
206 header.find(searchControls).each(function () {
207 that.options.valuesFilterControl.push({
208 field: $(this).closest('[data-field]').data('field'),
209 value: $(this).val(),
210 position: UtilsFilterControl.getCursorPosition($(this).get(0)),
211 hasFocus: $(this).is(':focus')
212 });
213 });
214 },
215 setValues: function setValues(that) {
216 var field = null;
217 var result = [];
218 var header = UtilsFilterControl.getCurrentHeader(that);
219 var searchControls = UtilsFilterControl.getCurrentSearchControls(that);
220
221 if (that.options.valuesFilterControl.length > 0) {
222 // Callback to apply after settings fields values
223 var fieldToFocusCallback = null;
224 header.find(searchControls).each(function (index, ele) {
225 field = $(this).closest('[data-field]').data('field');
226 result = that.options.valuesFilterControl.filter(function (valueObj) {
227 return valueObj.field === field;
228 });
229
230 if (result.length > 0) {
231 $(this).val(result[0].value);
232 if (result[0].hasFocus) {
233 // set callback if the field had the focus.
234 fieldToFocusCallback = function (fieldToFocus, carretPosition) {
235 // Closure here to capture the field and cursor position
236 var closedCallback = function closedCallback() {
237 fieldToFocus.focus();
238 UtilsFilterControl.setCursorPosition(fieldToFocus, carretPosition);
239 };
240 return closedCallback;
241 }($(this).get(0), result[0].position);
242 }
243 }
244 });
245
246 // Callback call.
247 if (fieldToFocusCallback !== null) {
248 fieldToFocusCallback();
249 }
250 }
251 },
252 collectBootstrapCookies: function collectBootstrapCookies() {
253 var cookies = [];
254 var foundCookies = document.cookie.match(/(?:bs.table.)(\w*)/g);
255
256 if (foundCookies) {
257 $.each(foundCookies, function (i, _cookie) {
258 var cookie = _cookie;
259 if (/./.test(cookie)) {
260 cookie = cookie.split('.').pop();
261 }
262
263 if ($.inArray(cookie, cookies) === -1) {
264 cookies.push(cookie);
265 }
266 });
267 return cookies;
268 }
269 },
270 escapeID: function escapeID(id) {
271 return String(id).replace(/(:|\.|\[|\]|,)/g, '\\$1');
272 },
273 isColumnSearchableViaSelect: function isColumnSearchableViaSelect(_ref4) {
274 var filterControl = _ref4.filterControl,
275 searchable = _ref4.searchable;
276
277 return filterControl && filterControl.toLowerCase() === 'select' && searchable;
278 },
279 isFilterDataNotGiven: function isFilterDataNotGiven(_ref5) {
280 var filterData = _ref5.filterData;
281
282 return filterData === undefined || filterData.toLowerCase() === 'column';
283 },
284 hasSelectControlElement: function hasSelectControlElement(selectControl) {
285 return selectControl && selectControl.length > 0;
286 },
287 initFilterSelectControls: function initFilterSelectControls(that) {
288 var data = that.data;
289 var itemsPerPage = that.pageTo < that.options.data.length ? that.options.data.length : that.pageTo;
290 var z = that.options.pagination ? that.options.sidePagination === 'server' ? that.pageTo : that.options.totalRows : that.pageTo;
291
292 $.each(that.header.fields, function (j, field) {
293 var column = that.columns[that.fieldsColumnsIndex[field]];
294 var selectControl = $('.bootstrap-table-filter-control-' + UtilsFilterControl.escapeID(column.field));
295
296 if (UtilsFilterControl.isColumnSearchableViaSelect(column) && UtilsFilterControl.isFilterDataNotGiven(column) && UtilsFilterControl.hasSelectControlElement(selectControl)) {
297 if (selectControl.get(selectControl.length - 1).options.length === 0) {
298 // Added the default option
299 UtilsFilterControl.addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder);
300 }
301
302 var uniqueValues = {};
303 for (var i = 0; i < z; i++) {
304 // Added a new value
305 var fieldValue = data[i][field];
306 var formattedValue = Utils.calculateObjectValue(that.header, that.header.formatters[j], [fieldValue, data[i], i], fieldValue);
307
308 uniqueValues[formattedValue] = fieldValue;
309 }
310
311 // eslint-disable-next-line guard-for-in
312 for (var key in uniqueValues) {
313 UtilsFilterControl.addOptionToSelectControl(selectControl, uniqueValues[key], key);
314 }
315
316 UtilsFilterControl.sortSelectControl(selectControl);
317
318 if (that.options.hideUnusedSelectOptions) {
319 UtilsFilterControl.hideUnusedSelectOptions(selectControl, uniqueValues);
320 }
321 }
322 });
323
324 that.trigger('created-controls');
325 },
326 getFilterDataMethod: function getFilterDataMethod(objFilterDataMethod, searchTerm) {
327 var keys = Object.keys(objFilterDataMethod);
328 for (var i = 0; i < keys.length; i++) {
329 if (keys[i] === searchTerm) {
330 return objFilterDataMethod[searchTerm];
331 }
332 }
333 return null;
334 },
335 createControls: function createControls(that, header) {
336 var addedFilterControl = false;
337 var isVisible = void 0;
338 var html = void 0;
339
340 $.each(that.columns, function (i, column) {
341 isVisible = 'hidden';
342 html = [];
343
344 if (!column.visible) {
345 return;
346 }
347
348 if (!column.filterControl) {
349 html.push('<div class="no-filter-control"></div>');
350 } else {
351 html.push('<div class="filter-control">');
352
353 var nameControl = column.filterControl.toLowerCase();
354 if (column.searchable && that.options.filterTemplate[nameControl]) {
355 addedFilterControl = true;
356 isVisible = 'visible';
357 html.push(that.options.filterTemplate[nameControl](that, column.field, isVisible, column.filterControlPlaceholder ? column.filterControlPlaceholder : '', 'filter-control-' + i));
358 }
359 }
360
361 $.each(header.children().children(), function (i, tr) {
362 var $tr = $(tr);
363 if ($tr.data('field') === column.field) {
364 $tr.find('.fht-cell').append(html.join(''));
365 return false;
366 }
367 });
368
369 if (column.filterData !== undefined && column.filterData.toLowerCase() !== 'column') {
370 var filterDataType = UtilsFilterControl.getFilterDataMethod(
371 /* eslint-disable no-use-before-define */
372 filterDataMethods, column.filterData.substring(0, column.filterData.indexOf(':')));
373 var filterDataSource = void 0;
374 var selectControl = void 0;
375
376 if (filterDataType !== null) {
377 filterDataSource = column.filterData.substring(column.filterData.indexOf(':') + 1, column.filterData.length);
378 selectControl = $('.bootstrap-table-filter-control-' + UtilsFilterControl.escapeID(column.field));
379
380 UtilsFilterControl.addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder);
381 filterDataType(filterDataSource, selectControl);
382 } else {
383 throw new SyntaxError('Error. You should use any of these allowed filter data methods: var, json, url.' + ' Use like this: var: {key: "value"}');
384 }
385
386 var variableValues = void 0;
387 var key = void 0;
388 // eslint-disable-next-line default-case
389 switch (filterDataType) {
390 case 'url':
391 $.ajax({
392 url: filterDataSource,
393 dataType: 'json',
394 success: function success(data) {
395 // eslint-disable-next-line guard-for-in
396 for (var _key in data) {
397 UtilsFilterControl.addOptionToSelectControl(selectControl, _key, data[_key]);
398 }
399 UtilsFilterControl.sortSelectControl(selectControl);
400 }
401 });
402 break;
403 case 'var':
404 variableValues = window[filterDataSource];
405 // eslint-disable-next-line guard-for-in
406 for (key in variableValues) {
407 UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key]);
408 }
409 UtilsFilterControl.sortSelectControl(selectControl);
410 break;
411 case 'jso':
412 variableValues = JSON.parse(filterDataSource);
413 // eslint-disable-next-line guard-for-in
414 for (key in variableValues) {
415 UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key]);
416 }
417 UtilsFilterControl.sortSelectControl(selectControl);
418 break;
419 }
420 }
421 });
422
423 if (addedFilterControl) {
424 header.off('keyup', 'input').on('keyup', 'input', function (event, obj) {
425 // Simulate enter key action from clear button
426 event.keyCode = obj ? obj.keyCode : event.keyCode;
427
428 if (that.options.searchOnEnterKey && event.keyCode !== 13) {
429 return;
430 }
431
432 if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
433 return;
434 }
435
436 var $currentTarget = $(event.currentTarget);
437
438 if ($currentTarget.is(':checkbox') || $currentTarget.is(':radio')) {
439 return;
440 }
441
442 clearTimeout(event.currentTarget.timeoutId || 0);
443 event.currentTarget.timeoutId = setTimeout(function () {
444 that.onColumnSearch(event);
445 }, that.options.searchTimeOut);
446 });
447
448 header.off('change', 'select').on('change', 'select', function (event) {
449 if (that.options.searchOnEnterKey && event.keyCode !== 13) {
450 return;
451 }
452
453 if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
454 return;
455 }
456
457 clearTimeout(event.currentTarget.timeoutId || 0);
458 event.currentTarget.timeoutId = setTimeout(function () {
459 that.onColumnSearch(event);
460 }, that.options.searchTimeOut);
461 });
462
463 header.off('mouseup', 'input').on('mouseup', 'input', function (event) {
464 var $input = $(this);
465 var oldValue = $input.val();
466
467 if (oldValue === '') {
468 return;
469 }
470
471 setTimeout(function () {
472 var newValue = $input.val();
473
474 if (newValue === '') {
475 clearTimeout(event.currentTarget.timeoutId || 0);
476 event.currentTarget.timeoutId = setTimeout(function () {
477 that.onColumnSearch(event);
478 }, that.options.searchTimeOut);
479 }
480 }, 1);
481 });
482
483 if (header.find('.date-filter-control').length > 0) {
484 $.each(that.columns, function (i, _ref6) {
485 var filterControl = _ref6.filterControl,
486 field = _ref6.field,
487 filterDatepickerOptions = _ref6.filterDatepickerOptions;
488
489 if (filterControl !== undefined && filterControl.toLowerCase() === 'datepicker') {
490 header.find('.date-filter-control.bootstrap-table-filter-control-' + field).datepicker(filterDatepickerOptions).on('changeDate', function (_ref7) {
491 var currentTarget = _ref7.currentTarget;
492
493 $(currentTarget).val(currentTarget.value);
494 // Fired the keyup event
495 $(currentTarget).keyup();
496 });
497 }
498 });
499 }
500 } else {
501 header.find('.filterControl').hide();
502 }
503 },
504 getDirectionOfSelectOptions: function getDirectionOfSelectOptions(_alignment) {
505 var alignment = _alignment === undefined ? 'left' : _alignment.toLowerCase();
506
507 switch (alignment) {
508 case 'left':
509 return 'ltr';
510 case 'right':
511 return 'rtl';
512 case 'auto':
513 return 'auto';
514 default:
515 return 'ltr';
516 }
517 }
518 };
519 var filterDataMethods = {
520 var: function _var(filterDataSource, selectControl) {
521 var variableValues = window[filterDataSource];
522 // eslint-disable-next-line guard-for-in
523 for (var key in variableValues) {
524 UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key]);
525 }
526 UtilsFilterControl.sortSelectControl(selectControl);
527 },
528 url: function url(filterDataSource, selectControl) {
529 $.ajax({
530 url: filterDataSource,
531 dataType: 'json',
532 success: function success(data) {
533 // eslint-disable-next-line guard-for-in
534 for (var key in data) {
535 UtilsFilterControl.addOptionToSelectControl(selectControl, key, data[key]);
536 }
537 UtilsFilterControl.sortSelectControl(selectControl);
538 }
539 });
540 },
541 json: function json(filterDataSource, selectControl) {
542 var variableValues = JSON.parse(filterDataSource);
543 // eslint-disable-next-line guard-for-in
544 for (var key in variableValues) {
545 UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key]);
546 }
547 UtilsFilterControl.sortSelectControl(selectControl);
548 }
549 };
550
551 var bootstrap = {
552 3: {
553 icons: {
554 clear: 'glyphicon-trash icon-clear'
555 }
556 },
557 4: {
558 icons: {
559 clear: 'fa-trash icon-clear'
560 }
561 }
562 }[Utils.bootstrapVersion];
563
564 $.extend($.fn.bootstrapTable.defaults, {
565 filterControl: false,
566 onColumnSearch: function onColumnSearch(field, text) {
567 return false;
568 },
569 onCreatedControls: function onCreatedControls() {
570 return true;
571 },
572
573 filterShowClear: false,
574 alignmentSelectControlOptions: undefined,
575 filterTemplate: {
576 input: function input(that, field, isVisible, placeholder) {
577 return Utils.sprintf('<input type="text" class="form-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s" placeholder="%s">', field, isVisible, placeholder);
578 },
579 select: function select(_ref8, field, isVisible) {
580 var options = _ref8.options;
581
582 return Utils.sprintf('<select class="form-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s" dir="%s"></select>', field, isVisible, UtilsFilterControl.getDirectionOfSelectOptions(options.alignmentSelectControlOptions));
583 },
584 datepicker: function datepicker(that, field, isVisible) {
585 return Utils.sprintf('<input type="text" class="form-control date-filter-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s">', field, isVisible);
586 }
587 },
588 disableControlWhenSearch: false,
589 searchOnEnterKey: false,
590 // internal variables
591 valuesFilterControl: []
592 });
593
594 $.extend($.fn.bootstrapTable.columnDefaults, {
595 filterControl: undefined,
596 filterData: undefined,
597 filterDatepickerOptions: undefined,
598 filterStrictSearch: false,
599 filterStartsWithSearch: false,
600 filterControlPlaceholder: ''
601 });
602
603 $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
604 'column-search.bs.table': 'onColumnSearch',
605 'created-controls.bs.table': 'onCreatedControls'
606 });
607
608 $.extend($.fn.bootstrapTable.defaults.icons, {
609 clear: bootstrap.icons.clear
610 });
611
612 $.extend($.fn.bootstrapTable.locales, {
613 formatClearFilters: function formatClearFilters() {
614 return 'Clear Filters';
615 }
616 });
617
618 $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);
619
620 $.fn.bootstrapTable.methods.push('triggerSearch');
621 $.fn.bootstrapTable.methods.push('clearFilterControl');
622
623 $.BootstrapTable = function (_$$BootstrapTable) {
624 _inherits(_class, _$$BootstrapTable);
625
626 function _class() {
627 _classCallCheck(this, _class);
628
629 return _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments));
630 }
631
632 _createClass(_class, [{
633 key: 'init',
634 value: function init() {
635 // Make sure that the filterControl option is set
636 if (this.options.filterControl) {
637 var that = this;
638
639 // Make sure that the internal variables are set correctly
640 this.options.valuesFilterControl = [];
641
642 this.$el.on('reset-view.bs.table', function () {
643 // Create controls on $tableHeader if the height is set
644 if (!that.options.height) {
645 return;
646 }
647
648 // Avoid recreate the controls
649 if (that.$tableHeader.find('select').length > 0 || that.$tableHeader.find('input').length > 0) {
650 return;
651 }
652
653 UtilsFilterControl.createControls(that, that.$tableHeader);
654 }).on('post-header.bs.table', function () {
655 UtilsFilterControl.setValues(that);
656 }).on('post-body.bs.table', function () {
657 if (that.options.height) {
658 UtilsFilterControl.fixHeaderCSS(that);
659 }
660 }).on('column-switch.bs.table', function () {
661 UtilsFilterControl.setValues(that);
662 }).on('load-success.bs.table', function () {
663 that.EnableControls(true);
664 }).on('load-error.bs.table', function () {
665 that.EnableControls(true);
666 });
667 }
668
669 _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'init', this).call(this);
670 }
671 }, {
672 key: 'initToolbar',
673 value: function initToolbar() {
674 this.showToolbar = this.showToolbar || this.options.filterControl && this.options.filterShowClear;
675
676 _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'initToolbar', this).call(this);
677
678 if (this.options.filterControl && this.options.filterShowClear) {
679 var $btnGroup = this.$toolbar.find('>.btn-group');
680 var $btnClear = $btnGroup.find('.filter-show-clear');
681
682 if (!$btnClear.length) {
683 $btnClear = $([Utils.sprintf('<button class="btn btn-%s filter-show-clear" ', this.options.buttonsClass), Utils.sprintf('type="button" title="%s">', this.options.formatClearFilters()), Utils.sprintf('<i class="%s %s"></i> ', this.options.iconsPrefix, this.options.icons.clear), '</button>'].join('')).appendTo($btnGroup);
684
685 $btnClear.off('click').on('click', $.proxy(this.clearFilterControl, this));
686 }
687 }
688 }
689 }, {
690 key: 'initHeader',
691 value: function initHeader() {
692 _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'initHeader', this).call(this);
693
694 if (!this.options.filterControl) {
695 return;
696 }
697 UtilsFilterControl.createControls(this, this.$header);
698 }
699 }, {
700 key: 'initBody',
701 value: function initBody() {
702 _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'initBody', this).call(this);
703
704 UtilsFilterControl.initFilterSelectControls(this);
705 }
706 }, {
707 key: 'initSearch',
708 value: function initSearch() {
709 var that = this;
710 var fp = $.isEmptyObject(that.filterColumnsPartial) ? null : that.filterColumnsPartial;
711
712 if (fp === null || Object.keys(fp).length <= 1) {
713 _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'initSearch', this).call(this);
714 }
715
716 if (this.options.sidePagination === 'server') {
717 return;
718 }
719
720 if (fp === null) {
721 return;
722 }
723
724 // Check partial column filter
725 that.data = fp ? that.options.data.filter(function (item, i) {
726 var itemIsExpected = [];
727 Object.keys(item).forEach(function (key, index) {
728 var thisColumn = that.columns[that.fieldsColumnsIndex[key]];
729 var fval = (fp[key] || '').toLowerCase();
730 var value = item[key];
731
732 if (fval === '') {
733 itemIsExpected.push(true);
734 } else {
735 // Fix #142: search use formated data
736 if (thisColumn && thisColumn.searchFormatter) {
737 value = $.fn.bootstrapTable.utils.calculateObjectValue(that.header, that.header.formatters[$.inArray(key, that.header.fields)], [value, item, i], value);
738 }
739
740 if ($.inArray(key, that.header.fields) !== -1) {
741 if (typeof value === 'string' || typeof value === 'number') {
742 if (thisColumn.filterStrictSearch) {
743 if (value.toString().toLowerCase() === fval.toString().toLowerCase()) {
744 itemIsExpected.push(true);
745 } else {
746 itemIsExpected.push(false);
747 }
748 } else if (thisColumn.filterStartsWithSearch) {
749 if (('' + value).toLowerCase().indexOf(fval) === 0) {
750 itemIsExpected.push(true);
751 } else {
752 itemIsExpected.push(false);
753 }
754 } else {
755 if (('' + value).toLowerCase().includes(fval)) {
756 itemIsExpected.push(true);
757 } else {
758 itemIsExpected.push(false);
759 }
760 }
761 }
762 }
763 }
764 });
765
766 return !itemIsExpected.includes(false);
767 }) : that.data;
768 }
769 }, {
770 key: 'initColumnSearch',
771 value: function initColumnSearch(filterColumnsDefaults) {
772 UtilsFilterControl.copyValues(this);
773
774 if (filterColumnsDefaults) {
775 this.filterColumnsPartial = filterColumnsDefaults;
776 this.updatePagination();
777
778 // eslint-disable-next-line guard-for-in
779 for (var filter in filterColumnsDefaults) {
780 this.trigger('column-search', filter, filterColumnsDefaults[filter]);
781 }
782 }
783 }
784 }, {
785 key: 'onColumnSearch',
786 value: function onColumnSearch(event) {
787 if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
788 return;
789 }
790
791 UtilsFilterControl.copyValues(this);
792 var text = $.trim($(event.currentTarget).val());
793 var $field = $(event.currentTarget).closest('[data-field]').data('field');
794
795 if ($.isEmptyObject(this.filterColumnsPartial)) {
796 this.filterColumnsPartial = {};
797 }
798 if (text) {
799 this.filterColumnsPartial[$field] = text;
800 } else {
801 delete this.filterColumnsPartial[$field];
802 }
803
804 // if the searchText is the same as the previously selected column value,
805 // bootstrapTable will not try searching again (even though the selected column
806 // may be different from the previous search). As a work around
807 // we're manually appending some text to bootrap's searchText field
808 // to guarantee that it will perform a search again when we call this.onSearch(event)
809 this.searchText += 'randomText';
810
811 this.options.pageNumber = 1;
812 this.EnableControls(false);
813 this.onSearch(event);
814 this.trigger('column-search', $field, text);
815 }
816 }, {
817 key: 'clearFilterControl',
818 value: function clearFilterControl() {
819 if (this.options.filterControl && this.options.filterShowClear) {
820 var that = this;
821 var cookies = UtilsFilterControl.collectBootstrapCookies();
822 var header = UtilsFilterControl.getCurrentHeader(that);
823 var table = header.closest('table');
824 var controls = header.find(UtilsFilterControl.getCurrentSearchControls(that));
825 var search = that.$toolbar.find('.search input');
826 var hasValues = false;
827 var timeoutId = 0;
828
829 $.each(that.options.valuesFilterControl, function (i, item) {
830 hasValues = hasValues ? true : item.value !== '';
831 item.value = '';
832 });
833
834 UtilsFilterControl.setValues(that);
835
836 // clear cookies once the filters are clean
837 clearTimeout(timeoutId);
838 timeoutId = setTimeout(function () {
839 if (cookies && cookies.length > 0) {
840 $.each(cookies, function (i, item) {
841 if (that.deleteCookie !== undefined) {
842 that.deleteCookie(item);
843 }
844 });
845 }
846 }, that.options.searchTimeOut);
847
848 // If there is not any value in the controls exit this method
849 if (!hasValues) {
850 return;
851 }
852
853 // Clear each type of filter if it exists.
854 // Requires the body to reload each time a type of filter is found because we never know
855 // which ones are going to be present.
856 if (controls.length > 0) {
857 this.filterColumnsPartial = {};
858 $(controls[0]).trigger(controls[0].tagName === 'INPUT' ? 'keyup' : 'change', { keyCode: 13 });
859 } else {
860 return;
861 }
862
863 if (search.length > 0) {
864 that.resetSearch();
865 }
866
867 // use the default sort order if it exists. do nothing if it does not
868 if (that.options.sortName !== table.data('sortName') || that.options.sortOrder !== table.data('sortOrder')) {
869 var sorter = header.find(Utils.sprintf('[data-field="%s"]', $(controls[0]).closest('table').data('sortName')));
870 if (sorter.length > 0) {
871 that.onSort({ type: 'keypress', currentTarget: sorter });
872 $(sorter).find('.sortable').trigger('click');
873 }
874 }
875 }
876 }
877 }, {
878 key: 'triggerSearch',
879 value: function triggerSearch() {
880 var header = UtilsFilterControl.getCurrentHeader(this);
881 var searchControls = UtilsFilterControl.getCurrentSearchControls(this);
882
883 header.find(searchControls).each(function () {
884 var el = $(this);
885 if (el.is('select')) {
886 el.change();
887 } else {
888 el.keyup();
889 }
890 });
891 }
892 }, {
893 key: 'EnableControls',
894 value: function EnableControls(enable) {
895 if (this.options.disableControlWhenSearch && this.options.sidePagination === 'server') {
896 var header = UtilsFilterControl.getCurrentHeader(this);
897 var searchControls = UtilsFilterControl.getCurrentSearchControls(this);
898
899 if (!enable) {
900 header.find(searchControls).prop('disabled', 'disabled');
901 } else {
902 header.find(searchControls).removeProp('disabled');
903 }
904 }
905 }
906 }]);
907
908 return _class;
909 }($.BootstrapTable);
910 })(jQuery);
911});
\No newline at end of file