UNPKG

104 kBJavaScriptView Raw
1/**
2 * @author zhixin wen <wenzhixin2010@gmail.com>
3 * version: 1.19.1
4 * https://github.com/wenzhixin/bootstrap-table/
5 */
6
7import Constants from './constants/index.js'
8import Utils from './utils/index.js'
9import VirtualScroll from './virtual-scroll/index.js'
10
11class BootstrapTable {
12 constructor (el, options) {
13 this.options = options
14 this.$el = $(el)
15 this.$el_ = this.$el.clone()
16 this.timeoutId_ = 0
17 this.timeoutFooter_ = 0
18 }
19
20 init () {
21 this.initConstants()
22 this.initLocale()
23 this.initContainer()
24 this.initTable()
25 this.initHeader()
26 this.initData()
27 this.initHiddenRows()
28 this.initToolbar()
29 this.initPagination()
30 this.initBody()
31 this.initSearchText()
32 this.initServer()
33 }
34
35 initConstants () {
36 const opts = this.options
37
38 this.constants = Constants.CONSTANTS
39 this.constants.theme = $.fn.bootstrapTable.theme
40 this.constants.dataToggle = this.constants.html.dataToggle || 'data-toggle'
41
42 const buttonsPrefix = opts.buttonsPrefix ? `${opts.buttonsPrefix}-` : ''
43
44 this.constants.buttonsClass = [
45 opts.buttonsPrefix,
46 buttonsPrefix + opts.buttonsClass,
47 Utils.sprintf(`${buttonsPrefix}%s`, opts.iconSize)
48 ].join(' ').trim()
49
50 this.buttons = Utils.calculateObjectValue(this, opts.buttons, [], {})
51 if (typeof this.buttons !== 'object') {
52 this.buttons = {}
53 }
54
55 if (typeof opts.icons === 'string') {
56 opts.icons = Utils.calculateObjectValue(null, opts.icons)
57 }
58 }
59
60 initLocale () {
61 if (this.options.locale) {
62 const locales = $.fn.bootstrapTable.locales
63 const parts = this.options.locale.split(/-|_/)
64
65 parts[0] = parts[0].toLowerCase()
66 if (parts[1]) {
67 parts[1] = parts[1].toUpperCase()
68 }
69
70 let localesToExtend = {}
71
72 if (locales[this.options.locale]) {
73 localesToExtend = locales[this.options.locale]
74 } else if (locales[parts.join('-')]) {
75 localesToExtend = locales[parts.join('-')]
76 } else if (locales[parts[0]]) {
77 localesToExtend = locales[parts[0]]
78 }
79
80 for (const [formatName, func] of Object.entries(localesToExtend)) {
81 if (this.options[formatName] !== BootstrapTable.DEFAULTS[formatName]) {
82 continue
83 }
84
85 this.options[formatName] = func
86 }
87 }
88 }
89
90 initContainer () {
91 const topPagination = ['top', 'both'].includes(this.options.paginationVAlign) ?
92 '<div class="fixed-table-pagination clearfix"></div>' : ''
93 const bottomPagination = ['bottom', 'both'].includes(this.options.paginationVAlign) ?
94 '<div class="fixed-table-pagination"></div>' : ''
95 const loadingTemplate = Utils.calculateObjectValue(this.options,
96 this.options.loadingTemplate, [this.options.formatLoadingMessage()])
97
98 this.$container = $(`
99 <div class="bootstrap-table ${this.constants.theme}">
100 <div class="fixed-table-toolbar"></div>
101 ${topPagination}
102 <div class="fixed-table-container">
103 <div class="fixed-table-header"><table></table></div>
104 <div class="fixed-table-body">
105 <div class="fixed-table-loading">
106 ${loadingTemplate}
107 </div>
108 </div>
109 <div class="fixed-table-footer"></div>
110 </div>
111 ${bottomPagination}
112 </div>
113 `)
114
115 this.$container.insertAfter(this.$el)
116 this.$tableContainer = this.$container.find('.fixed-table-container')
117 this.$tableHeader = this.$container.find('.fixed-table-header')
118 this.$tableBody = this.$container.find('.fixed-table-body')
119 this.$tableLoading = this.$container.find('.fixed-table-loading')
120 this.$tableFooter = this.$el.find('tfoot')
121 // checking if custom table-toolbar exists or not
122 if (this.options.buttonsToolbar) {
123 this.$toolbar = $('body').find(this.options.buttonsToolbar)
124 } else {
125 this.$toolbar = this.$container.find('.fixed-table-toolbar')
126 }
127 this.$pagination = this.$container.find('.fixed-table-pagination')
128
129 this.$tableBody.append(this.$el)
130 this.$container.after('<div class="clearfix"></div>')
131
132 this.$el.addClass(this.options.classes)
133 this.$tableLoading.addClass(this.options.classes)
134
135 if (this.options.height) {
136 this.$tableContainer.addClass('fixed-height')
137
138 if (this.options.showFooter) {
139 this.$tableContainer.addClass('has-footer')
140 }
141
142 if (this.options.classes.split(' ').includes('table-bordered')) {
143 this.$tableBody.append('<div class="fixed-table-border"></div>')
144 this.$tableBorder = this.$tableBody.find('.fixed-table-border')
145 this.$tableLoading.addClass('fixed-table-border')
146 }
147
148 this.$tableFooter = this.$container.find('.fixed-table-footer')
149 }
150 }
151
152 initTable () {
153 const columns = []
154
155 this.$header = this.$el.find('>thead')
156 if (!this.$header.length) {
157 this.$header = $(`<thead class="${this.options.theadClasses}"></thead>`).appendTo(this.$el)
158 } else if (this.options.theadClasses) {
159 this.$header.addClass(this.options.theadClasses)
160 }
161
162 this._headerTrClasses = []
163 this._headerTrStyles = []
164 this.$header.find('tr').each((i, el) => {
165 const $tr = $(el)
166 const column = []
167
168 $tr.find('th').each((i, el) => {
169 const $th = $(el)
170
171 // #2014: getFieldIndex and elsewhere assume this is string, causes issues if not
172 if (typeof $th.data('field') !== 'undefined') {
173 $th.data('field', `${$th.data('field')}`)
174 }
175 column.push($.extend({}, {
176 title: $th.html(),
177 class: $th.attr('class'),
178 titleTooltip: $th.attr('title'),
179 rowspan: $th.attr('rowspan') ? +$th.attr('rowspan') : undefined,
180 colspan: $th.attr('colspan') ? +$th.attr('colspan') : undefined
181 }, $th.data()))
182 })
183 columns.push(column)
184
185 if ($tr.attr('class')) {
186 this._headerTrClasses.push($tr.attr('class'))
187 }
188 if ($tr.attr('style')) {
189 this._headerTrStyles.push($tr.attr('style'))
190 }
191 })
192
193 if (!Array.isArray(this.options.columns[0])) {
194 this.options.columns = [this.options.columns]
195 }
196
197 this.options.columns = $.extend(true, [], columns, this.options.columns)
198 this.columns = []
199 this.fieldsColumnsIndex = []
200
201 Utils.setFieldIndex(this.options.columns)
202
203 this.options.columns.forEach((columns, i) => {
204 columns.forEach((_column, j) => {
205 const column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, _column)
206
207 if (typeof column.fieldIndex !== 'undefined') {
208 this.columns[column.fieldIndex] = column
209 this.fieldsColumnsIndex[column.field] = column.fieldIndex
210 }
211
212 this.options.columns[i][j] = column
213 })
214 })
215
216 // if options.data is setting, do not process tbody and tfoot data
217 if (!this.options.data.length) {
218 const htmlData = Utils.trToData(this.columns, this.$el.find('>tbody>tr'))
219
220 if (htmlData.length) {
221 this.options.data = htmlData
222 this.fromHtml = true
223 }
224 }
225
226 if (!(this.options.pagination && this.options.sidePagination !== 'server')) {
227 this.footerData = Utils.trToData(this.columns, this.$el.find('>tfoot>tr'))
228 }
229
230 if (this.footerData) {
231 this.$el.find('tfoot').html('<tr></tr>')
232 }
233
234 if (!this.options.showFooter || this.options.cardView) {
235 this.$tableFooter.hide()
236 } else {
237 this.$tableFooter.show()
238 }
239 }
240
241 initHeader () {
242 const visibleColumns = {}
243 const headerHtml = []
244
245 this.header = {
246 fields: [],
247 styles: [],
248 classes: [],
249 formatters: [],
250 detailFormatters: [],
251 events: [],
252 sorters: [],
253 sortNames: [],
254 cellStyles: [],
255 searchables: []
256 }
257
258 Utils.updateFieldGroup(this.options.columns)
259
260 this.options.columns.forEach((columns, i) => {
261 const html = []
262
263 html.push(`<tr${Utils.sprintf(' class="%s"', this._headerTrClasses[i])} ${Utils.sprintf(' style="%s"', this._headerTrStyles[i])}>`)
264
265 let detailViewTemplate = ''
266
267 if (i === 0 && Utils.hasDetailViewIcon(this.options)) {
268 const rowspan = this.options.columns.length > 1 ?
269 ` rowspan="${this.options.columns.length}"` : ''
270
271 detailViewTemplate = `<th class="detail"${rowspan}>
272 <div class="fht-cell"></div>
273 </th>`
274 }
275
276 if (detailViewTemplate && this.options.detailViewAlign !== 'right') {
277 html.push(detailViewTemplate)
278 }
279
280 columns.forEach((column, j) => {
281 const class_ = Utils.sprintf(' class="%s"', column['class'])
282 const unitWidth = column.widthUnit
283 const width = parseFloat(column.width)
284
285 const halign = Utils.sprintf('text-align: %s; ', column.halign ? column.halign : column.align)
286 const align = Utils.sprintf('text-align: %s; ', column.align)
287 let style = Utils.sprintf('vertical-align: %s; ', column.valign)
288
289 style += Utils.sprintf('width: %s; ', (column.checkbox || column.radio) && !width ?
290 (!column.showSelectTitle ? '36px' : undefined) :
291 (width ? width + unitWidth : undefined))
292
293 if (typeof column.fieldIndex === 'undefined' && !column.visible) {
294 return
295 }
296
297 const headerStyle = Utils.calculateObjectValue(null, this.options.headerStyle, [column])
298 const csses = []
299 let classes = ''
300
301 if (headerStyle && headerStyle.css) {
302 for (const [key, value] of Object.entries(headerStyle.css)) {
303 csses.push(`${key}: ${value}`)
304 }
305 }
306 if (headerStyle && headerStyle.classes) {
307 classes = Utils.sprintf(' class="%s"', column['class'] ?
308 [column['class'], headerStyle.classes].join(' ') : headerStyle.classes)
309 }
310
311 if (typeof column.fieldIndex !== 'undefined') {
312 this.header.fields[column.fieldIndex] = column.field
313 this.header.styles[column.fieldIndex] = align + style
314 this.header.classes[column.fieldIndex] = class_
315 this.header.formatters[column.fieldIndex] = column.formatter
316 this.header.detailFormatters[column.fieldIndex] = column.detailFormatter
317 this.header.events[column.fieldIndex] = column.events
318 this.header.sorters[column.fieldIndex] = column.sorter
319 this.header.sortNames[column.fieldIndex] = column.sortName
320 this.header.cellStyles[column.fieldIndex] = column.cellStyle
321 this.header.searchables[column.fieldIndex] = column.searchable
322
323 if (!column.visible) {
324 return
325 }
326
327 if (this.options.cardView && (!column.cardVisible)) {
328 return
329 }
330
331 visibleColumns[column.field] = column
332 }
333
334 html.push(`<th${Utils.sprintf(' title="%s"', column.titleTooltip)}`,
335 column.checkbox || column.radio ?
336 Utils.sprintf(' class="bs-checkbox %s"', column['class'] || '') :
337 classes || class_,
338 Utils.sprintf(' style="%s"', halign + style + csses.join('; ')),
339 Utils.sprintf(' rowspan="%s"', column.rowspan),
340 Utils.sprintf(' colspan="%s"', column.colspan),
341 Utils.sprintf(' data-field="%s"', column.field),
342 // If `column` is not the first element of `this.options.columns[0]`, then className 'data-not-first-th' should be added.
343 j === 0 && i > 0 ? ' data-not-first-th' : '',
344 '>')
345
346 html.push(Utils.sprintf('<div class="th-inner %s">', this.options.sortable && column.sortable ?
347 'sortable both' : ''))
348
349 let text = this.options.escape ? Utils.escapeHTML(column.title) : column.title
350
351 const title = text
352
353 if (column.checkbox) {
354 text = ''
355 if (!this.options.singleSelect && this.options.checkboxHeader) {
356 text = '<label><input name="btSelectAll" type="checkbox" /><span></span></label>'
357 }
358 this.header.stateField = column.field
359 }
360 if (column.radio) {
361 text = ''
362 this.header.stateField = column.field
363 }
364 if (!text && column.showSelectTitle) {
365 text += title
366 }
367
368 html.push(text)
369 html.push('</div>')
370 html.push('<div class="fht-cell"></div>')
371 html.push('</div>')
372 html.push('</th>')
373 })
374
375 if (detailViewTemplate && this.options.detailViewAlign === 'right') {
376 html.push(detailViewTemplate)
377 }
378
379 html.push('</tr>')
380
381 if (html.length > 3) {
382 headerHtml.push(html.join(''))
383 }
384 })
385
386 this.$header.html(headerHtml.join(''))
387 this.$header.find('th[data-field]').each((i, el) => {
388 $(el).data(visibleColumns[$(el).data('field')])
389 })
390 this.$container.off('click', '.th-inner').on('click', '.th-inner', e => {
391 const $this = $(e.currentTarget)
392
393 if (this.options.detailView && !$this.parent().hasClass('bs-checkbox')) {
394 if ($this.closest('.bootstrap-table')[0] !== this.$container[0]) {
395 return false
396 }
397 }
398
399 if (this.options.sortable && $this.parent().data().sortable) {
400 this.onSort(e)
401 }
402 })
403
404 const resizeEvent = Utils.getEventName('resize.bootstrap-table', this.$el.attr('id'))
405
406 $(window).off(resizeEvent)
407 if (!this.options.showHeader || this.options.cardView) {
408 this.$header.hide()
409 this.$tableHeader.hide()
410 this.$tableLoading.css('top', 0)
411 } else {
412 this.$header.show()
413 this.$tableHeader.show()
414 this.$tableLoading.css('top', this.$header.outerHeight() + 1)
415 // Assign the correct sortable arrow
416 this.getCaret()
417 $(window).on(resizeEvent, () => this.resetView())
418 }
419
420 this.$selectAll = this.$header.find('[name="btSelectAll"]')
421 this.$selectAll.off('click').on('click', e => {
422 e.stopPropagation()
423 const checked = $(e.currentTarget).prop('checked')
424
425 this[checked ? 'checkAll' : 'uncheckAll']()
426 this.updateSelected()
427 })
428 }
429
430 initData (data, type) {
431 if (type === 'append') {
432 this.options.data = this.options.data.concat(data)
433 } else if (type === 'prepend') {
434 this.options.data = [].concat(data).concat(this.options.data)
435 } else {
436 data = data || Utils.deepCopy(this.options.data)
437 this.options.data = Array.isArray(data) ? data : data[this.options.dataField]
438 }
439
440 this.data = [...this.options.data]
441
442 if (this.options.sortReset) {
443 this.unsortedData = [...this.data]
444 }
445
446 if (this.options.sidePagination === 'server') {
447 return
448 }
449 this.initSort()
450 }
451
452 initSort () {
453 let name = this.options.sortName
454 const order = this.options.sortOrder === 'desc' ? -1 : 1
455 const index = this.header.fields.indexOf(this.options.sortName)
456 let timeoutId = 0
457
458 if (index !== -1) {
459 if (this.options.sortStable) {
460 this.data.forEach((row, i) => {
461 if (!row.hasOwnProperty('_position')) {
462 row._position = i
463 }
464 })
465 }
466
467 if (this.options.customSort) {
468 Utils.calculateObjectValue(this.options, this.options.customSort, [
469 this.options.sortName,
470 this.options.sortOrder,
471 this.data
472 ])
473 } else {
474 this.data.sort((a, b) => {
475 if (this.header.sortNames[index]) {
476 name = this.header.sortNames[index]
477 }
478 const aa = Utils.getItemField(a, name, this.options.escape)
479 const bb = Utils.getItemField(b, name, this.options.escape)
480 const value = Utils.calculateObjectValue(this.header, this.header.sorters[index], [aa, bb, a, b])
481
482 if (value !== undefined) {
483 if (this.options.sortStable && value === 0) {
484 return order * (a._position - b._position)
485 }
486 return order * value
487 }
488
489 return Utils.sort(aa, bb, order, this.options.sortStable,
490 a._position, b._position)
491 })
492 }
493
494 if (this.options.sortClass !== undefined) {
495 clearTimeout(timeoutId)
496 timeoutId = setTimeout(() => {
497 this.$el.removeClass(this.options.sortClass)
498 const index = this.$header.find(`[data-field="${this.options.sortName}"]`).index()
499
500 this.$el.find(`tr td:nth-child(${index + 1})`).addClass(this.options.sortClass)
501 }, 250)
502 }
503 } else if (this.options.sortReset) {
504 this.data = [...this.unsortedData]
505 }
506 }
507
508 onSort ({ type, currentTarget }) {
509 const $this = type === 'keypress' ? $(currentTarget) : $(currentTarget).parent()
510 const $this_ = this.$header.find('th').eq($this.index())
511
512 this.$header.add(this.$header_).find('span.order').remove()
513
514 if (this.options.sortName === $this.data('field')) {
515 const currentSortOrder = this.options.sortOrder
516
517 if (currentSortOrder === undefined) {
518 this.options.sortOrder = 'asc'
519 } else if (currentSortOrder === 'asc') {
520 this.options.sortOrder = 'desc'
521 } else if (this.options.sortOrder === 'desc') {
522 this.options.sortOrder = this.options.sortReset ? undefined : 'asc'
523 }
524
525 if (this.options.sortOrder === undefined) {
526 this.options.sortName = undefined
527 }
528 } else {
529 this.options.sortName = $this.data('field')
530 if (this.options.rememberOrder) {
531 this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc'
532 } else {
533 this.options.sortOrder = this.columns[this.fieldsColumnsIndex[$this.data('field')]].sortOrder ||
534 this.columns[this.fieldsColumnsIndex[$this.data('field')]].order
535 }
536 }
537 this.trigger('sort', this.options.sortName, this.options.sortOrder)
538
539 $this.add($this_).data('order', this.options.sortOrder)
540
541 // Assign the correct sortable arrow
542 this.getCaret()
543
544 if (this.options.sidePagination === 'server' && this.options.serverSort) {
545 this.options.pageNumber = 1
546 this.initServer(this.options.silentSort)
547 return
548 }
549
550 this.initSort()
551 this.initBody()
552 }
553
554 initToolbar () {
555 const opts = this.options
556 let html = []
557 let timeoutId = 0
558 let $keepOpen
559 let switchableCount = 0
560
561 if (this.$toolbar.find('.bs-bars').children().length) {
562 $('body').append($(opts.toolbar))
563 }
564 this.$toolbar.html('')
565
566 if (typeof opts.toolbar === 'string' || typeof opts.toolbar === 'object') {
567 $(Utils.sprintf('<div class="bs-bars %s-%s"></div>', this.constants.classes.pull, opts.toolbarAlign))
568 .appendTo(this.$toolbar)
569 .append($(opts.toolbar))
570 }
571
572 // showColumns, showToggle, showRefresh
573 html = [`<div class="${[
574 'columns',
575 `columns-${opts.buttonsAlign}`,
576 this.constants.classes.buttonsGroup,
577 `${this.constants.classes.pull}-${opts.buttonsAlign}`
578 ].join(' ')}">`]
579
580 if (typeof opts.buttonsOrder === 'string') {
581 opts.buttonsOrder = opts.buttonsOrder.replace(/\[|\]| |'/g, '').split(',')
582 }
583
584 this.buttons = Object.assign(this.buttons, {
585 paginationSwitch: {
586 text: opts.pagination ? opts.formatPaginationSwitchUp() : opts.formatPaginationSwitchDown(),
587 icon: opts.pagination ? opts.icons.paginationSwitchDown : opts.icons.paginationSwitchUp,
588 render: false,
589 event: this.togglePagination,
590 attributes: {
591 'aria-label': opts.formatPaginationSwitch(),
592 title: opts.formatPaginationSwitch()
593 }
594 },
595 refresh: {
596 text: opts.formatRefresh(),
597 icon: opts.icons.refresh,
598 render: false,
599 event: this.refresh,
600 attributes: {
601 'aria-label': opts.formatRefresh(),
602 title: opts.formatRefresh()
603 }
604 },
605 toggle: {
606 text: opts.formatToggle(),
607 icon: opts.icons.toggleOff,
608 render: false,
609 event: this.toggleView,
610 attributes: {
611 'aria-label': opts.formatToggleOn(),
612 title: opts.formatToggleOn()
613 }
614 },
615 fullscreen: {
616 text: opts.formatFullscreen(),
617 icon: opts.icons.fullscreen,
618 render: false,
619 event: this.toggleFullscreen,
620 attributes: {
621 'aria-label': opts.formatFullscreen(),
622 title: opts.formatFullscreen()
623 }
624 },
625 columns: {
626 render: false,
627 html: (() => {
628 const html = []
629
630 html.push(`<div class="keep-open ${this.constants.classes.buttonsDropdown}" title="${opts.formatColumns()}">
631 <button class="${this.constants.buttonsClass} dropdown-toggle" type="button" ${this.constants.dataToggle}="dropdown"
632 aria-label="Columns" title="${opts.formatColumns()}">
633 ${opts.showButtonIcons ? Utils.sprintf(this.constants.html.icon, opts.iconsPrefix, opts.icons.columns) : ''}
634 ${opts.showButtonText ? opts.formatColumns() : ''}
635 ${this.constants.html.dropdownCaret}
636 </button>
637 ${this.constants.html.toolbarDropdown[0]}`)
638
639 if (opts.showColumnsSearch) {
640 html.push(
641 Utils.sprintf(this.constants.html.toolbarDropdownItem,
642 Utils.sprintf('<input type="text" class="%s" name="columnsSearch" placeholder="%s" autocomplete="off">', this.constants.classes.input, opts.formatSearch())
643 )
644 )
645 html.push(this.constants.html.toolbarDropdownSeparator)
646 }
647
648 if (opts.showColumnsToggleAll) {
649 const allFieldsVisible = this.getVisibleColumns().length === this.columns.filter(column => !this.isSelectionColumn(column)).length
650
651 html.push(
652 Utils.sprintf(this.constants.html.toolbarDropdownItem,
653 Utils.sprintf('<input type="checkbox" class="toggle-all" %s> <span>%s</span>',
654 allFieldsVisible ? 'checked="checked"' : '', opts.formatColumnsToggleAll())
655 )
656 )
657
658 html.push(this.constants.html.toolbarDropdownSeparator)
659 }
660
661 let visibleColumns = 0
662
663 this.columns.forEach(column => {
664 if (column.visible) {
665 visibleColumns++
666 }
667 })
668
669 this.columns.forEach((column, i) => {
670 if (this.isSelectionColumn(column)) {
671 return
672 }
673
674 if (opts.cardView && !column.cardVisible) {
675 return
676 }
677
678 const checked = column.visible ? ' checked="checked"' : ''
679 const disabled = (visibleColumns <= opts.minimumCountColumns) && checked ? ' disabled="disabled"' : ''
680
681 if (column.switchable) {
682 html.push(Utils.sprintf(this.constants.html.toolbarDropdownItem,
683 Utils.sprintf('<input type="checkbox" data-field="%s" value="%s"%s%s> <span>%s</span>',
684 column.field, i, checked, disabled, column.title)))
685 switchableCount++
686 }
687 })
688 html.push(this.constants.html.toolbarDropdown[1], '</div>')
689 return html.join('')
690 })
691 }
692 })
693
694 const buttonsHtml = {}
695
696 for (const [buttonName, buttonConfig] of Object.entries(this.buttons)) {
697 let buttonHtml
698
699 if (buttonConfig.hasOwnProperty('html')) {
700 if (typeof buttonConfig.html === 'function') {
701 buttonHtml = buttonConfig.html()
702 } else if (typeof buttonConfig.html === 'string') {
703 buttonHtml = buttonConfig.html
704 }
705 } else {
706 buttonHtml = `<button class="${this.constants.buttonsClass}" type="button" name="${buttonName}"`
707
708 if (buttonConfig.hasOwnProperty('attributes')) {
709 for (const [attributeName, value] of Object.entries(buttonConfig.attributes)) {
710 buttonHtml += ` ${attributeName}="${value}"`
711 }
712 }
713
714 buttonHtml += '>'
715
716 if (opts.showButtonIcons && buttonConfig.hasOwnProperty('icon')) {
717 buttonHtml += `${Utils.sprintf(this.constants.html.icon, opts.iconsPrefix, buttonConfig.icon) } `
718 }
719
720 if (opts.showButtonText && buttonConfig.hasOwnProperty('text')) {
721 buttonHtml += buttonConfig.text
722 }
723
724 buttonHtml += '</button>'
725 }
726
727 buttonsHtml[buttonName] = buttonHtml
728 const optionName = `show${buttonName.charAt(0).toUpperCase()}${buttonName.substring(1)}`
729 const showOption = opts[optionName]
730
731 if ((
732 !buttonConfig.hasOwnProperty('render') ||
733 buttonConfig.hasOwnProperty('render') &&
734 buttonConfig.render) &&
735 (showOption === undefined || showOption === true)
736 ) {
737 opts[optionName] = true
738 }
739
740 if (!opts.buttonsOrder.includes(buttonName)) {
741 opts.buttonsOrder.push(buttonName)
742 }
743 }
744
745 // Adding the button html to the final toolbar html when the showOption is true
746 for (const button of opts.buttonsOrder) {
747 const showOption = opts[`show${button.charAt(0).toUpperCase()}${button.substring(1)}`]
748
749 if (showOption) {
750 html.push(buttonsHtml[button])
751 }
752 }
753
754 html.push('</div>')
755
756 // Fix #188: this.showToolbar is for extensions
757 if (this.showToolbar || html.length > 2) {
758 this.$toolbar.append(html.join(''))
759 }
760
761 for (const [buttonName, buttonConfig] of Object.entries(this.buttons)) {
762 if (buttonConfig.hasOwnProperty('event')) {
763 if (typeof buttonConfig.event === 'function' || typeof buttonConfig.event === 'string') {
764 const event = typeof buttonConfig.event === 'string' ? window[buttonConfig.event] : buttonConfig.event
765
766 this.$toolbar.find(`button[name="${buttonName}"]`)
767 .off('click')
768 .on('click', () => event.call(this))
769 continue
770 }
771
772 for (const [eventType, eventFunction] of Object.entries(buttonConfig.event)) {
773 const event = typeof eventFunction === 'string' ? window[eventFunction] : eventFunction
774
775 this.$toolbar.find(`button[name="${buttonName}"]`)
776 .off(eventType)
777 .on(eventType, () => event.call(this))
778 }
779 }
780 }
781
782 if (opts.showColumns) {
783 $keepOpen = this.$toolbar.find('.keep-open')
784 const $checkboxes = $keepOpen.find('input[type="checkbox"]:not(".toggle-all")')
785 const $toggleAll = $keepOpen.find('input[type="checkbox"].toggle-all')
786
787 if (switchableCount <= opts.minimumCountColumns) {
788 $keepOpen.find('input').prop('disabled', true)
789 }
790
791 $keepOpen.find('li, label').off('click').on('click', e => {
792 e.stopImmediatePropagation()
793 })
794
795 $checkboxes.off('click').on('click', ({ currentTarget }) => {
796 const $this = $(currentTarget)
797
798 this._toggleColumn($this.val(), $this.prop('checked'), false)
799 this.trigger('column-switch', $this.data('field'), $this.prop('checked'))
800 $toggleAll.prop('checked', $checkboxes.filter(':checked').length === this.columns.filter(column => !this.isSelectionColumn(column)).length)
801 })
802
803 $toggleAll.off('click').on('click', ({ currentTarget }) => {
804 this._toggleAllColumns($(currentTarget).prop('checked'))
805 })
806
807 if (opts.showColumnsSearch) {
808 const $columnsSearch = $keepOpen.find('[name="columnsSearch"]')
809 const $listItems = $keepOpen.find('.dropdown-item-marker')
810
811 $columnsSearch.on('keyup paste change', ({ currentTarget }) => {
812 const $this = $(currentTarget)
813 const searchValue = $this.val().toLowerCase()
814
815 $listItems.show()
816 $checkboxes.each((i, el) => {
817 const $checkbox = $(el)
818 const $listItem = $checkbox.parents('.dropdown-item-marker')
819 const text = $listItem.text().toLowerCase()
820
821 if (!text.includes(searchValue)) {
822 $listItem.hide()
823 }
824 })
825 })
826 }
827 }
828 const handleInputEvent = $searchInput => {
829 const eventTriggers = 'keyup drop blur mouseup'
830
831 $searchInput.off(eventTriggers).on(eventTriggers, event => {
832 if (opts.searchOnEnterKey && event.keyCode !== 13) {
833 return
834 }
835
836 if ([37, 38, 39, 40].includes(event.keyCode)) {
837 return
838 }
839
840 clearTimeout(timeoutId) // doesn't matter if it's 0
841 timeoutId = setTimeout(() => {
842 this.onSearch({ currentTarget: event.currentTarget })
843 }, opts.searchTimeOut)
844 })
845 }
846
847 // Fix #4516: this.showSearchClearButton is for extensions
848 if (
849 (opts.search || this.showSearchClearButton) &&
850 typeof opts.searchSelector !== 'string'
851 ) {
852 html = []
853 const showSearchButton = Utils.sprintf(this.constants.html.searchButton,
854 this.constants.buttonsClass,
855 opts.formatSearch(),
856 opts.showButtonIcons ? Utils.sprintf(this.constants.html.icon, opts.iconsPrefix, opts.icons.search) : '',
857 opts.showButtonText ? opts.formatSearch() : ''
858 )
859 const showSearchClearButton = Utils.sprintf(this.constants.html.searchClearButton,
860 this.constants.buttonsClass,
861 opts.formatClearSearch(),
862 opts.showButtonIcons ? Utils.sprintf(this.constants.html.icon, opts.iconsPrefix, opts.icons.clearSearch) : '',
863 opts.showButtonText ? opts.formatClearSearch() : ''
864 )
865 const searchInputHtml = `<input class="${this.constants.classes.input}
866 ${Utils.sprintf(' %s%s', this.constants.classes.inputPrefix, opts.iconSize)}
867 search-input" type="search" placeholder="${opts.formatSearch()}" autocomplete="off">`
868 let searchInputFinalHtml = searchInputHtml
869
870 if (opts.showSearchButton || opts.showSearchClearButton) {
871 const buttonsHtml = (opts.showSearchButton ? showSearchButton : '') +
872 (opts.showSearchClearButton ? showSearchClearButton : '')
873
874 searchInputFinalHtml = opts.search ? Utils.sprintf(this.constants.html.inputGroup,
875 searchInputHtml, buttonsHtml) : buttonsHtml
876 }
877
878 html.push(Utils.sprintf(`
879 <div class="${this.constants.classes.pull}-${opts.searchAlign} search ${this.constants.classes.inputGroup}">
880 %s
881 </div>
882 `, searchInputFinalHtml))
883
884 this.$toolbar.append(html.join(''))
885 const $searchInput = Utils.getSearchInput(this)
886
887 if (opts.showSearchButton) {
888 this.$toolbar.find('.search button[name=search]').off('click').on('click', () => {
889 clearTimeout(timeoutId) // doesn't matter if it's 0
890 timeoutId = setTimeout(() => {
891 this.onSearch({ currentTarget: $searchInput })
892 }, opts.searchTimeOut)
893 })
894
895 if (opts.searchOnEnterKey) {
896 handleInputEvent($searchInput)
897 }
898 } else {
899 handleInputEvent($searchInput)
900 }
901
902 if (opts.showSearchClearButton) {
903 this.$toolbar.find('.search button[name=clearSearch]').click(() => {
904 this.resetSearch()
905 })
906 }
907 } else if (typeof opts.searchSelector === 'string') {
908 const $searchInput = Utils.getSearchInput(this)
909
910 handleInputEvent($searchInput)
911 }
912 }
913
914 onSearch ({ currentTarget, firedByInitSearchText } = {}, overwriteSearchText = true) {
915 if (currentTarget !== undefined && $(currentTarget).length && overwriteSearchText) {
916 const text = $(currentTarget).val().trim()
917
918 if (this.options.trimOnSearch && $(currentTarget).val() !== text) {
919 $(currentTarget).val(text)
920 }
921
922 if (this.searchText === text) {
923 return
924 }
925
926 const $searchInput = Utils.getSearchInput(this)
927 const $currentTarget = currentTarget instanceof jQuery ? currentTarget : $(currentTarget)
928
929 if ($currentTarget.is($searchInput) || $currentTarget.hasClass('search-input')) {
930 this.searchText = text
931 this.options.searchText = text
932 }
933 }
934
935 if (!firedByInitSearchText) {
936 this.options.pageNumber = 1
937 }
938 this.initSearch()
939 if (firedByInitSearchText) {
940 if (this.options.sidePagination === 'client') {
941 this.updatePagination()
942 }
943 } else {
944 this.updatePagination()
945 }
946 this.trigger('search', this.searchText)
947 }
948
949 initSearch () {
950 this.filterOptions = this.filterOptions || this.options.filterOptions
951 if (this.options.sidePagination !== 'server') {
952 if (this.options.customSearch) {
953 this.data = Utils.calculateObjectValue(this.options, this.options.customSearch,
954 [this.options.data, this.searchText, this.filterColumns])
955
956 if (this.options.sortReset) {
957 this.unsortedData = [...this.data]
958 }
959 return
960 }
961
962 const rawSearchText = this.searchText && (this.fromHtml ? Utils.escapeHTML(this.searchText) : this.searchText)
963 let searchText = rawSearchText ? rawSearchText.toLowerCase() : ''
964 const f = Utils.isEmptyObject(this.filterColumns) ? null : this.filterColumns
965
966 if (this.options.searchAccentNeutralise) {
967 searchText = Utils.normalizeAccent(searchText)
968 }
969
970 // Check filter
971 if (typeof this.filterOptions.filterAlgorithm === 'function') {
972 this.data = this.options.data.filter(item => this.filterOptions.filterAlgorithm.apply(null, [item, f]))
973 } else if (typeof this.filterOptions.filterAlgorithm === 'string') {
974 this.data = f ? this.options.data.filter(item => {
975 const filterAlgorithm = this.filterOptions.filterAlgorithm
976
977 if (filterAlgorithm === 'and') {
978 for (const key in f) {
979 if (
980 (Array.isArray(f[key]) &&
981 !f[key].includes(item[key])) ||
982 (!Array.isArray(f[key]) &&
983 item[key] !== f[key])
984 ) {
985 return false
986 }
987 }
988 } else if (filterAlgorithm === 'or') {
989 let match = false
990
991 for (const key in f) {
992 if (
993 (Array.isArray(f[key]) &&
994 f[key].includes(item[key])) ||
995 (!Array.isArray(f[key]) &&
996 item[key] === f[key])
997 ) {
998 match = true
999 }
1000 }
1001
1002 return match
1003 }
1004
1005 return true
1006 }) : [...this.options.data]
1007 }
1008
1009 const visibleFields = this.getVisibleFields()
1010
1011 this.data = searchText ? this.data.filter((item, i) => {
1012 for (let j = 0; j < this.header.fields.length; j++) {
1013 if (!this.header.searchables[j] || (this.options.visibleSearch && visibleFields.indexOf(this.header.fields[j]) === -1)) {
1014 continue
1015 }
1016
1017 const key = Utils.isNumeric(this.header.fields[j]) ? parseInt(this.header.fields[j], 10) : this.header.fields[j]
1018 const column = this.columns[this.fieldsColumnsIndex[key]]
1019 let value
1020
1021 if (typeof key === 'string') {
1022 value = item
1023 const props = key.split('.')
1024
1025 for (let i = 0; i < props.length; i++) {
1026 if (value[props[i]] !== null) {
1027 value = value[props[i]]
1028 }
1029 }
1030 } else {
1031 value = item[key]
1032 }
1033
1034 if (this.options.searchAccentNeutralise) {
1035 value = Utils.normalizeAccent(value)
1036 }
1037
1038 // Fix #142: respect searchFormatter boolean
1039 if (column && column.searchFormatter) {
1040 value = Utils.calculateObjectValue(column,
1041 this.header.formatters[j], [value, item, i, column.field], value)
1042 }
1043
1044 if (typeof value === 'string' || typeof value === 'number') {
1045 if (
1046 this.options.strictSearch && (`${value}`).toLowerCase() === searchText ||
1047 (this.options.regexSearch && Utils.regexCompare(value, rawSearchText))
1048 ) {
1049 return true
1050 }
1051
1052 const largerSmallerEqualsRegex = /(?:(<=|=>|=<|>=|>|<)(?:\s+)?(-?\d+)?|(-?\d+)?(\s+)?(<=|=>|=<|>=|>|<))/gm
1053 const matches = largerSmallerEqualsRegex.exec(this.searchText)
1054 let comparisonCheck = false
1055
1056 if (matches) {
1057 const operator = matches[1] || `${matches[5]}l`
1058 const comparisonValue = matches[2] || matches[3]
1059 const int = parseInt(value, 10)
1060 const comparisonInt = parseInt(comparisonValue, 10)
1061
1062 switch (operator) {
1063 case '>':
1064 case '<l':
1065 comparisonCheck = int > comparisonInt
1066 break
1067 case '<':
1068 case '>l':
1069 comparisonCheck = int < comparisonInt
1070 break
1071 case '<=':
1072 case '=<':
1073 case '>=l':
1074 case '=>l':
1075 comparisonCheck = int <= comparisonInt
1076 break
1077 case '>=':
1078 case '=>':
1079 case '<=l':
1080 case '=<l':
1081 comparisonCheck = int >= comparisonInt
1082 break
1083 default:
1084 break
1085 }
1086 }
1087
1088 if (comparisonCheck || (`${value}`).toLowerCase().includes(searchText)) {
1089 return true
1090 }
1091 }
1092 }
1093 return false
1094 }) : this.data
1095
1096 if (this.options.sortReset) {
1097 this.unsortedData = [...this.data]
1098 }
1099
1100 this.initSort()
1101 }
1102 }
1103
1104 initPagination () {
1105 const opts = this.options
1106
1107 if (!opts.pagination) {
1108 this.$pagination.hide()
1109 return
1110 }
1111 this.$pagination.show()
1112
1113 const html = []
1114 let allSelected = false
1115 let i
1116 let from
1117 let to
1118 let $pageList
1119 let $pre
1120 let $next
1121 let $number
1122 const data = this.getData({ includeHiddenRows: false })
1123 let pageList = opts.pageList
1124
1125 if (typeof pageList === 'string') {
1126 pageList = pageList.replace(/\[|\]| /g, '').toLowerCase().split(',')
1127 }
1128
1129 pageList = pageList.map(value => {
1130 if (typeof value === 'string') {
1131 return (value.toLowerCase() === opts.formatAllRows().toLowerCase() ||
1132 ['all', 'unlimited'].includes(value.toLowerCase())) ? opts.formatAllRows() : +value
1133 }
1134 return value
1135 })
1136
1137 this.paginationParts = opts.paginationParts
1138 if (typeof this.paginationParts === 'string') {
1139 this.paginationParts = this.paginationParts.replace(/\[|\]| |'/g, '').split(',')
1140 }
1141
1142 if (opts.sidePagination !== 'server') {
1143 opts.totalRows = data.length
1144 }
1145
1146 this.totalPages = 0
1147 if (opts.totalRows) {
1148 if (opts.pageSize === opts.formatAllRows()) {
1149 opts.pageSize = opts.totalRows
1150 allSelected = true
1151 }
1152
1153 this.totalPages = ~~((opts.totalRows - 1) / opts.pageSize) + 1
1154
1155 opts.totalPages = this.totalPages
1156 }
1157 if (this.totalPages > 0 && opts.pageNumber > this.totalPages) {
1158 opts.pageNumber = this.totalPages
1159 }
1160
1161 this.pageFrom = (opts.pageNumber - 1) * opts.pageSize + 1
1162 this.pageTo = opts.pageNumber * opts.pageSize
1163 if (this.pageTo > opts.totalRows) {
1164 this.pageTo = opts.totalRows
1165 }
1166
1167 if (this.options.pagination && this.options.sidePagination !== 'server') {
1168 this.options.totalNotFiltered = this.options.data.length
1169 }
1170
1171 if (!this.options.showExtendedPagination) {
1172 this.options.totalNotFiltered = undefined
1173 }
1174
1175 if (this.paginationParts.includes('pageInfo') || this.paginationParts.includes('pageInfoShort') || this.paginationParts.includes('pageSize')) {
1176 html.push(`<div class="${this.constants.classes.pull}-${opts.paginationDetailHAlign} pagination-detail">`)
1177 }
1178
1179 if (this.paginationParts.includes('pageInfo') || this.paginationParts.includes('pageInfoShort')) {
1180 const paginationInfo = this.paginationParts.includes('pageInfoShort') ? opts.formatDetailPagination(opts.totalRows) : opts.formatShowingRows(this.pageFrom, this.pageTo, opts.totalRows, opts.totalNotFiltered)
1181
1182 html.push(`<span class="pagination-info">
1183 ${paginationInfo}
1184 </span>`)
1185 }
1186
1187 if (this.paginationParts.includes('pageSize')) {
1188 html.push('<div class="page-list">')
1189
1190 const pageNumber = [
1191 `<div class="${this.constants.classes.paginationDropdown}">
1192 <button class="${this.constants.buttonsClass} dropdown-toggle" type="button" ${this.constants.dataToggle}="dropdown">
1193 <span class="page-size">
1194 ${allSelected ? opts.formatAllRows() : opts.pageSize}
1195 </span>
1196 ${this.constants.html.dropdownCaret}
1197 </button>
1198 ${this.constants.html.pageDropdown[0]}`
1199 ]
1200
1201 pageList.forEach((page, i) => {
1202 if (!opts.smartDisplay || i === 0 || pageList[i - 1] < opts.totalRows || page === opts.formatAllRows()) {
1203 let active
1204
1205 if (allSelected) {
1206 active = page === opts.formatAllRows() ? this.constants.classes.dropdownActive : ''
1207 } else {
1208 active = page === opts.pageSize ? this.constants.classes.dropdownActive : ''
1209 }
1210 pageNumber.push(Utils.sprintf(this.constants.html.pageDropdownItem, active, page))
1211 }
1212 })
1213 pageNumber.push(`${this.constants.html.pageDropdown[1]}</div>`)
1214
1215 html.push(opts.formatRecordsPerPage(pageNumber.join('')))
1216 }
1217
1218 if (this.paginationParts.includes('pageInfo') || this.paginationParts.includes('pageInfoShort') || this.paginationParts.includes('pageSize')) {
1219 html.push('</div></div>')
1220 }
1221
1222 if (this.paginationParts.includes('pageList')) {
1223 html.push(`<div class="${this.constants.classes.pull}-${opts.paginationHAlign} pagination">`,
1224 Utils.sprintf(this.constants.html.pagination[0], Utils.sprintf(' pagination-%s', opts.iconSize)),
1225 Utils.sprintf(this.constants.html.paginationItem, ' page-pre', opts.formatSRPaginationPreText(), opts.paginationPreText))
1226
1227 if (this.totalPages < opts.paginationSuccessivelySize) {
1228 from = 1
1229 to = this.totalPages
1230 } else {
1231 from = opts.pageNumber - opts.paginationPagesBySide
1232 to = from + (opts.paginationPagesBySide * 2)
1233 }
1234
1235 if (opts.pageNumber < (opts.paginationSuccessivelySize - 1)) {
1236 to = opts.paginationSuccessivelySize
1237 }
1238
1239 if (opts.paginationSuccessivelySize > this.totalPages - from) {
1240 from = from - (opts.paginationSuccessivelySize - (this.totalPages - from)) + 1
1241 }
1242
1243 if (from < 1) {
1244 from = 1
1245 }
1246
1247 if (to > this.totalPages) {
1248 to = this.totalPages
1249 }
1250
1251 const middleSize = Math.round(opts.paginationPagesBySide / 2)
1252 const pageItem = (i, classes = '') => Utils.sprintf(this.constants.html.paginationItem,
1253 classes + (i === opts.pageNumber ? ` ${this.constants.classes.paginationActive}` : ''), opts.formatSRPaginationPageText(i), i)
1254
1255 if (from > 1) {
1256 let max = opts.paginationPagesBySide
1257
1258 if (max >= from) max = from - 1
1259 for (i = 1; i <= max; i++) {
1260 html.push(pageItem(i))
1261 }
1262 if ((from - 1) === max + 1) {
1263 i = from - 1
1264 html.push(pageItem(i))
1265 } else if ((from - 1) > max) {
1266 if (
1267 (from - opts.paginationPagesBySide * 2) > opts.paginationPagesBySide &&
1268 opts.paginationUseIntermediate
1269 ) {
1270 i = Math.round(((from - middleSize) / 2) + middleSize)
1271 html.push(pageItem(i, ' page-intermediate'))
1272 } else {
1273 html.push(Utils.sprintf(this.constants.html.paginationItem,
1274 ' page-first-separator disabled', '', '...'))
1275 }
1276 }
1277 }
1278
1279 for (i = from; i <= to; i++) {
1280 html.push(pageItem(i))
1281 }
1282
1283 if (this.totalPages > to) {
1284 let min = this.totalPages - (opts.paginationPagesBySide - 1)
1285
1286 if (to >= min) min = to + 1
1287 if ((to + 1) === min - 1) {
1288 i = to + 1
1289 html.push(pageItem(i))
1290 } else if (min > (to + 1)) {
1291 if (
1292 (this.totalPages - to) > opts.paginationPagesBySide * 2 &&
1293 opts.paginationUseIntermediate
1294 ) {
1295 i = Math.round(((this.totalPages - middleSize - to) / 2) + to)
1296 html.push(pageItem(i, ' page-intermediate'))
1297 } else {
1298 html.push(Utils.sprintf(this.constants.html.paginationItem,
1299 ' page-last-separator disabled', '', '...'))
1300 }
1301 }
1302
1303 for (i = min; i <= this.totalPages; i++) {
1304 html.push(pageItem(i))
1305 }
1306 }
1307
1308 html.push(Utils.sprintf(this.constants.html.paginationItem, ' page-next', opts.formatSRPaginationNextText(), opts.paginationNextText))
1309 html.push(this.constants.html.pagination[1], '</div>')
1310 }
1311 this.$pagination.html(html.join(''))
1312
1313 const dropupClass = ['bottom', 'both'].includes(opts.paginationVAlign) ?
1314 ` ${this.constants.classes.dropup}` : ''
1315
1316 this.$pagination.last().find('.page-list > div').addClass(dropupClass)
1317
1318 if (!opts.onlyInfoPagination) {
1319 $pageList = this.$pagination.find('.page-list a')
1320 $pre = this.$pagination.find('.page-pre')
1321 $next = this.$pagination.find('.page-next')
1322 $number = this.$pagination.find('.page-item').not('.page-next, .page-pre, .page-last-separator, .page-first-separator')
1323
1324 if (this.totalPages <= 1) {
1325 this.$pagination.find('div.pagination').hide()
1326 }
1327
1328 if (opts.smartDisplay) {
1329 if (pageList.length < 2 || opts.totalRows <= pageList[0]) {
1330 this.$pagination.find('div.page-list').hide()
1331 }
1332 }
1333
1334 // when data is empty, hide the pagination
1335 this.$pagination[this.getData().length ? 'show' : 'hide']()
1336
1337 if (!opts.paginationLoop) {
1338 if (opts.pageNumber === 1) {
1339 $pre.addClass('disabled')
1340 }
1341 if (opts.pageNumber === this.totalPages) {
1342 $next.addClass('disabled')
1343 }
1344 }
1345
1346 if (allSelected) {
1347 opts.pageSize = opts.formatAllRows()
1348 }
1349 // removed the events for last and first, onPageNumber executeds the same logic
1350 $pageList.off('click').on('click', e => this.onPageListChange(e))
1351 $pre.off('click').on('click', e => this.onPagePre(e))
1352 $next.off('click').on('click', e => this.onPageNext(e))
1353 $number.off('click').on('click', e => this.onPageNumber(e))
1354 }
1355 }
1356
1357 updatePagination (event) {
1358 // Fix #171: IE disabled button can be clicked bug.
1359 if (event && $(event.currentTarget).hasClass('disabled')) {
1360 return
1361 }
1362
1363 if (!this.options.maintainMetaData) {
1364 this.resetRows()
1365 }
1366
1367 this.initPagination()
1368
1369 this.trigger('page-change', this.options.pageNumber, this.options.pageSize)
1370
1371 if (this.options.sidePagination === 'server') {
1372 this.initServer()
1373 } else {
1374 this.initBody()
1375 }
1376 }
1377
1378 onPageListChange (event) {
1379 event.preventDefault()
1380 const $this = $(event.currentTarget)
1381
1382 $this.parent().addClass(this.constants.classes.dropdownActive)
1383 .siblings().removeClass(this.constants.classes.dropdownActive)
1384 this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase() ?
1385 this.options.formatAllRows() : +$this.text()
1386 this.$toolbar.find('.page-size').text(this.options.pageSize)
1387
1388 this.updatePagination(event)
1389 return false
1390 }
1391
1392 onPagePre (event) {
1393 if ($(event.target).hasClass('disabled')) {
1394 return
1395 }
1396 event.preventDefault()
1397 if ((this.options.pageNumber - 1) === 0) {
1398 this.options.pageNumber = this.options.totalPages
1399 } else {
1400 this.options.pageNumber--
1401 }
1402 this.updatePagination(event)
1403 return false
1404 }
1405
1406 onPageNext (event) {
1407 if ($(event.target).hasClass('disabled')) {
1408 return
1409 }
1410 event.preventDefault()
1411 if ((this.options.pageNumber + 1) > this.options.totalPages) {
1412 this.options.pageNumber = 1
1413 } else {
1414 this.options.pageNumber++
1415 }
1416 this.updatePagination(event)
1417 return false
1418 }
1419
1420 onPageNumber (event) {
1421 event.preventDefault()
1422 if (this.options.pageNumber === +$(event.currentTarget).text()) {
1423 return
1424 }
1425 this.options.pageNumber = +$(event.currentTarget).text()
1426 this.updatePagination(event)
1427 return false
1428 }
1429
1430 // eslint-disable-next-line no-unused-vars
1431 initRow (item, i, data, trFragments) {
1432 const html = []
1433 let style = {}
1434 const csses = []
1435 let data_ = ''
1436 let attributes = {}
1437 const htmlAttributes = []
1438
1439 if (Utils.findIndex(this.hiddenRows, item) > -1) {
1440 return
1441 }
1442
1443 style = Utils.calculateObjectValue(this.options, this.options.rowStyle, [item, i], style)
1444
1445 if (style && style.css) {
1446 for (const [key, value] of Object.entries(style.css)) {
1447 csses.push(`${key}: ${value}`)
1448 }
1449 }
1450
1451 attributes = Utils.calculateObjectValue(this.options,
1452 this.options.rowAttributes, [item, i], attributes)
1453
1454 if (attributes) {
1455 for (const [key, value] of Object.entries(attributes)) {
1456 htmlAttributes.push(`${key}="${Utils.escapeHTML(value)}"`)
1457 }
1458 }
1459
1460 if (item._data && !Utils.isEmptyObject(item._data)) {
1461 for (const [k, v] of Object.entries(item._data)) {
1462 // ignore data-index
1463 if (k === 'index') {
1464 return
1465 }
1466 data_ += ` data-${k}='${typeof v === 'object' ? JSON.stringify(v) : v}'`
1467 }
1468 }
1469
1470 html.push('<tr',
1471 Utils.sprintf(' %s', htmlAttributes.length ? htmlAttributes.join(' ') : undefined),
1472 Utils.sprintf(' id="%s"', Array.isArray(item) ? undefined : item._id),
1473 Utils.sprintf(' class="%s"', style.classes || (Array.isArray(item) ? undefined : item._class)),
1474 Utils.sprintf(' style="%s"', Array.isArray(item) ? undefined : item._style),
1475 ` data-index="${i}"`,
1476 Utils.sprintf(' data-uniqueid="%s"', Utils.getItemField(item, this.options.uniqueId, false)),
1477 Utils.sprintf(' data-has-detail-view="%s"', (this.options.detailView && Utils.calculateObjectValue(null, this.options.detailFilter, [i, item])) ? 'true' : undefined),
1478 Utils.sprintf('%s', data_),
1479 '>'
1480 )
1481
1482 if (this.options.cardView) {
1483 html.push(`<td colspan="${this.header.fields.length}"><div class="card-views">`)
1484 }
1485
1486 let detailViewTemplate = ''
1487
1488 if (Utils.hasDetailViewIcon(this.options)) {
1489 detailViewTemplate = '<td>'
1490
1491 if (Utils.calculateObjectValue(null, this.options.detailFilter, [i, item])) {
1492 detailViewTemplate += `
1493 <a class="detail-icon" href="#">
1494 ${Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailOpen)}
1495 </a>
1496 `
1497 }
1498
1499 detailViewTemplate += '</td>'
1500 }
1501
1502 if (detailViewTemplate && this.options.detailViewAlign !== 'right') {
1503 html.push(detailViewTemplate)
1504 }
1505
1506 this.header.fields.forEach((field, j) => {
1507 let text = ''
1508 let value_ = Utils.getItemField(item, field, this.options.escape)
1509 let value = ''
1510 let type = ''
1511 let cellStyle = {}
1512 let id_ = ''
1513 let class_ = this.header.classes[j]
1514 let style_ = ''
1515 let styleToAdd_ = ''
1516 let data_ = ''
1517 let rowspan_ = ''
1518 let colspan_ = ''
1519 let title_ = ''
1520 const column = this.columns[j]
1521
1522 if ((this.fromHtml || this.autoMergeCells) && typeof value_ === 'undefined') {
1523 if ((!column.checkbox) && (!column.radio)) {
1524 return
1525 }
1526 }
1527
1528 if (!column.visible) {
1529 return
1530 }
1531
1532 if (this.options.cardView && (!column.cardVisible)) {
1533 return
1534 }
1535
1536 if (column.escape) {
1537 value_ = Utils.escapeHTML(value_)
1538 }
1539
1540 // Style concat
1541 if (csses.concat([this.header.styles[j]]).length) {
1542 styleToAdd_ += `${csses.concat([this.header.styles[j]]).join('; ')}`
1543 }
1544 if (item[`_${field}_style`]) {
1545 styleToAdd_ += `${item[`_${field}_style`]}`
1546 }
1547
1548 if (styleToAdd_) {
1549 style_ = ` style="${styleToAdd_}"`
1550 }
1551 // Style concat
1552
1553 // handle id and class of td
1554 if (item[`_${field}_id`]) {
1555 id_ = Utils.sprintf(' id="%s"', item[`_${field}_id`])
1556 }
1557 if (item[`_${field}_class`]) {
1558 class_ = Utils.sprintf(' class="%s"', item[`_${field}_class`])
1559 }
1560 if (item[`_${field}_rowspan`]) {
1561 rowspan_ = Utils.sprintf(' rowspan="%s"', item[`_${field}_rowspan`])
1562 }
1563 if (item[`_${field}_colspan`]) {
1564 colspan_ = Utils.sprintf(' colspan="%s"', item[`_${field}_colspan`])
1565 }
1566 if (item[`_${field}_title`]) {
1567 title_ = Utils.sprintf(' title="%s"', item[`_${field}_title`])
1568 }
1569 cellStyle = Utils.calculateObjectValue(this.header,
1570 this.header.cellStyles[j], [value_, item, i, field], cellStyle)
1571 if (cellStyle.classes) {
1572 class_ = ` class="${cellStyle.classes}"`
1573 }
1574 if (cellStyle.css) {
1575 const csses_ = []
1576
1577 for (const [key, value] of Object.entries(cellStyle.css)) {
1578 csses_.push(`${key}: ${value}`)
1579 }
1580 style_ = ` style="${csses_.concat(this.header.styles[j]).join('; ')}"`
1581 }
1582
1583 value = Utils.calculateObjectValue(column,
1584 this.header.formatters[j], [value_, item, i, field], value_)
1585
1586 if (!(column.checkbox || column.radio)) {
1587 value = typeof value === 'undefined' || value === null ?
1588 this.options.undefinedText : value
1589 }
1590
1591 if (column.searchable && this.searchText && this.options.searchHighlight && !(column.checkbox || column.radio)) {
1592 let defValue = ''
1593 const regExp = new RegExp(`(${ this.searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') })`, 'gim')
1594 const marker = '<mark>$1</mark>'
1595 const isHTML = value && /<(?=.*? .*?\/ ?>|br|hr|input|!--|wbr)[a-z]+.*?>|<([a-z]+).*?<\/\1>/i.test(value)
1596
1597 if (isHTML) {
1598 // value can contains a HTML tags
1599 let textContent = new DOMParser().parseFromString(value.toString(), 'text/html').documentElement.textContent
1600 const textReplaced = textContent.replace(regExp, marker)
1601
1602 textContent = textContent.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1603 defValue = value.replace(new RegExp(`(>\\s*)(${textContent})(\\s*)`, 'gm'), `$1${textReplaced}$3`)
1604 } else {
1605 // but usually not
1606 defValue = value.toString().replace(regExp, marker)
1607 }
1608 value = Utils.calculateObjectValue(column, column.searchHighlightFormatter, [value, this.searchText], defValue)
1609 }
1610
1611 if (item[`_${field}_data`] && !Utils.isEmptyObject(item[`_${field}_data`])) {
1612 for (const [k, v] of Object.entries(item[`_${field}_data`])) {
1613 // ignore data-index
1614 if (k === 'index') {
1615 return
1616 }
1617 data_ += ` data-${k}="${v}"`
1618 }
1619 }
1620
1621 if (column.checkbox || column.radio) {
1622 type = column.checkbox ? 'checkbox' : type
1623 type = column.radio ? 'radio' : type
1624
1625 const c = column['class'] || ''
1626 const isChecked = Utils.isObject(value) && value.hasOwnProperty('checked') ?
1627 value.checked : (value === true || value_) && value !== false
1628 const isDisabled = !column.checkboxEnabled || (value && value.disabled)
1629
1630 text = [
1631 this.options.cardView ?
1632 `<div class="card-view ${c}">` :
1633 `<td class="bs-checkbox ${c}"${class_}${style_}>`,
1634 `<label>
1635 <input
1636 data-index="${i}"
1637 name="${this.options.selectItemName}"
1638 type="${type}"
1639 ${Utils.sprintf('value="%s"', item[this.options.idField])}
1640 ${Utils.sprintf('checked="%s"', isChecked ? 'checked' : undefined)}
1641 ${Utils.sprintf('disabled="%s"', isDisabled ? 'disabled' : undefined)} />
1642 <span></span>
1643 </label>`,
1644 this.header.formatters[j] && typeof value === 'string' ? value : '',
1645 this.options.cardView ? '</div>' : '</td>'
1646 ].join('')
1647
1648 item[this.header.stateField] = value === true || (!!value_ || (value && value.checked))
1649 } else if (this.options.cardView) {
1650 const cardTitle = this.options.showHeader ?
1651 `<span class="card-view-title ${cellStyle.classes}"${style_}>${Utils.getFieldTitle(this.columns, field)}</span>` : ''
1652
1653 text = `<div class="card-view">${cardTitle}<span class="card-view-value ${cellStyle.classes}"${style_}>${value}</span></div>`
1654
1655 if (this.options.smartDisplay && value === '') {
1656 text = '<div class="card-view"></div>'
1657 }
1658 } else {
1659 text = `<td${id_}${class_}${style_}${data_}${rowspan_}${colspan_}${title_}>${value}</td>`
1660 }
1661
1662 html.push(text)
1663 })
1664
1665 if (detailViewTemplate && this.options.detailViewAlign === 'right') {
1666 html.push(detailViewTemplate)
1667 }
1668
1669 if (this.options.cardView) {
1670 html.push('</div></td>')
1671 }
1672 html.push('</tr>')
1673
1674 return html.join('')
1675 }
1676
1677 initBody (fixedScroll, updatedUid) {
1678 const data = this.getData()
1679
1680 this.trigger('pre-body', data)
1681
1682 this.$body = this.$el.find('>tbody')
1683 if (!this.$body.length) {
1684 this.$body = $('<tbody></tbody>').appendTo(this.$el)
1685 }
1686
1687 // Fix #389 Bootstrap-table-flatJSON is not working
1688 if (!this.options.pagination || this.options.sidePagination === 'server') {
1689 this.pageFrom = 1
1690 this.pageTo = data.length
1691 }
1692
1693 const rows = []
1694 const trFragments = $(document.createDocumentFragment())
1695 let hasTr = false
1696 const toExpand = []
1697
1698 this.autoMergeCells = Utils.checkAutoMergeCells(data.slice(this.pageFrom - 1, this.pageTo))
1699
1700 for (let i = this.pageFrom - 1; i < this.pageTo; i++) {
1701 const item = data[i]
1702 let tr = this.initRow(item, i, data, trFragments)
1703
1704 hasTr = hasTr || !!tr
1705 if (tr && typeof tr === 'string') {
1706
1707 const uniqueId = this.options.uniqueId
1708
1709 if (uniqueId && item.hasOwnProperty(uniqueId)) {
1710 const itemUniqueId = item[uniqueId]
1711
1712 const oldTr = this.$body.find(Utils.sprintf('> tr[data-uniqueid="%s"][data-has-detail-view]', itemUniqueId))
1713 const oldTrNext = oldTr.next()
1714
1715 if (oldTrNext.is('tr.detail-view')) {
1716
1717 toExpand.push(i)
1718
1719 if (!updatedUid || itemUniqueId !== updatedUid) {
1720 tr += oldTrNext[0].outerHTML
1721 }
1722 }
1723 }
1724
1725 if (!this.options.virtualScroll) {
1726 trFragments.append(tr)
1727 } else {
1728 rows.push(tr)
1729 }
1730 }
1731 }
1732
1733 // show no records
1734 if (!hasTr) {
1735 this.$body.html(`<tr class="no-records-found">${Utils.sprintf('<td colspan="%s">%s</td>',
1736 this.getVisibleFields().length + Utils.getDetailViewIndexOffset(this.options),
1737 this.options.formatNoMatches())}</tr>`)
1738 } else if (!this.options.virtualScroll) {
1739 this.$body.html(trFragments)
1740 } else {
1741 if (this.virtualScroll) {
1742 this.virtualScroll.destroy()
1743 }
1744 this.virtualScroll = new VirtualScroll({
1745 rows,
1746 fixedScroll,
1747 scrollEl: this.$tableBody[0],
1748 contentEl: this.$body[0],
1749 itemHeight: this.options.virtualScrollItemHeight,
1750 callback: (startIndex, endIndex) => {
1751 this.fitHeader()
1752 this.initBodyEvent()
1753 this.trigger('virtual-scroll', startIndex, endIndex)
1754 }
1755 })
1756 }
1757
1758 toExpand.forEach(index => { this.expandRow(index) })
1759
1760 if (!fixedScroll) {
1761 this.scrollTo(0)
1762 }
1763
1764 this.initBodyEvent()
1765 this.initFooter()
1766 this.resetView()
1767 this.updateSelected()
1768
1769 if (this.options.sidePagination !== 'server') {
1770 this.options.totalRows = data.length
1771 }
1772
1773 this.trigger('post-body', data)
1774 }
1775
1776 initBodyEvent () {
1777 // click to select by column
1778 this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', e => {
1779 const $td = $(e.currentTarget)
1780 const $tr = $td.parent()
1781 const $cardViewArr = $(e.target).parents('.card-views').children()
1782 const $cardViewTarget = $(e.target).parents('.card-view')
1783 const rowIndex = $tr.data('index')
1784 const item = this.data[rowIndex]
1785 const index = this.options.cardView ? $cardViewArr.index($cardViewTarget) : $td[0].cellIndex
1786 const fields = this.getVisibleFields()
1787 const field = fields[index - Utils.getDetailViewIndexOffset(this.options)]
1788 const column = this.columns[this.fieldsColumnsIndex[field]]
1789 const value = Utils.getItemField(item, field, this.options.escape)
1790
1791 if ($td.find('.detail-icon').length) {
1792 return
1793 }
1794
1795 this.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td)
1796 this.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr, field)
1797
1798 // if click to select - then trigger the checkbox/radio click
1799 if (
1800 e.type === 'click' &&
1801 this.options.clickToSelect &&
1802 column.clickToSelect &&
1803 !Utils.calculateObjectValue(this.options, this.options.ignoreClickToSelectOn, [e.target])
1804 ) {
1805 const $selectItem = $tr.find(Utils.sprintf('[name="%s"]', this.options.selectItemName))
1806
1807 if ($selectItem.length) {
1808 $selectItem[0].click()
1809 }
1810 }
1811
1812 if (e.type === 'click' && this.options.detailViewByClick) {
1813 this.toggleDetailView(rowIndex, this.header.detailFormatters[this.fieldsColumnsIndex[field]])
1814 }
1815 }).off('mousedown').on('mousedown', e => {
1816 // https://github.com/jquery/jquery/issues/1741
1817 this.multipleSelectRowCtrlKey = e.ctrlKey || e.metaKey
1818 this.multipleSelectRowShiftKey = e.shiftKey
1819 })
1820
1821 this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', e => {
1822 e.preventDefault()
1823 this.toggleDetailView($(e.currentTarget).parent().parent().data('index'))
1824 return false
1825 })
1826
1827 this.$selectItem = this.$body.find(Utils.sprintf('[name="%s"]', this.options.selectItemName))
1828 this.$selectItem.off('click').on('click', e => {
1829 e.stopImmediatePropagation()
1830
1831 const $this = $(e.currentTarget)
1832
1833 this._toggleCheck($this.prop('checked'), $this.data('index'))
1834 })
1835
1836 this.header.events.forEach((_events, i) => {
1837 let events = _events
1838
1839 if (!events) {
1840 return
1841 }
1842 // fix bug, if events is defined with namespace
1843 if (typeof events === 'string') {
1844 events = Utils.calculateObjectValue(null, events)
1845 }
1846
1847 const field = this.header.fields[i]
1848 let fieldIndex = this.getVisibleFields().indexOf(field)
1849
1850 if (fieldIndex === -1) {
1851 return
1852 }
1853
1854 fieldIndex += Utils.getDetailViewIndexOffset(this.options)
1855
1856 for (const key in events) {
1857 if (!events.hasOwnProperty(key)) {
1858 continue
1859 }
1860 const event = events[key]
1861
1862 this.$body.find('>tr:not(.no-records-found)').each((i, tr) => {
1863 const $tr = $(tr)
1864 const $td = $tr.find(this.options.cardView ? '.card-views>.card-view' : '>td').eq(fieldIndex)
1865 const index = key.indexOf(' ')
1866 const name = key.substring(0, index)
1867 const el = key.substring(index + 1)
1868
1869 $td.find(el).off(name).on(name, e => {
1870 const index = $tr.data('index')
1871 const row = this.data[index]
1872 const value = row[field]
1873
1874 event.apply(this, [e, value, row, index])
1875 })
1876 })
1877 }
1878 })
1879 }
1880
1881 initServer (silent, query, url) {
1882 let data = {}
1883 const index = this.header.fields.indexOf(this.options.sortName)
1884
1885 let params = {
1886 searchText: this.searchText,
1887 sortName: this.options.sortName,
1888 sortOrder: this.options.sortOrder
1889 }
1890
1891 if (this.header.sortNames[index]) {
1892 params.sortName = this.header.sortNames[index]
1893 }
1894
1895 if (this.options.pagination && this.options.sidePagination === 'server') {
1896 params.pageSize = this.options.pageSize === this.options.formatAllRows() ?
1897 this.options.totalRows : this.options.pageSize
1898 params.pageNumber = this.options.pageNumber
1899 }
1900
1901 if (!(url || this.options.url) && !this.options.ajax) {
1902 return
1903 }
1904
1905 if (this.options.queryParamsType === 'limit') {
1906 params = {
1907 search: params.searchText,
1908 sort: params.sortName,
1909 order: params.sortOrder
1910 }
1911
1912 if (this.options.pagination && this.options.sidePagination === 'server') {
1913 params.offset = this.options.pageSize === this.options.formatAllRows() ?
1914 0 : this.options.pageSize * (this.options.pageNumber - 1)
1915 params.limit = this.options.pageSize
1916 if (params.limit === 0 || this.options.pageSize === this.options.formatAllRows()) {
1917 delete params.limit
1918 }
1919 }
1920 }
1921
1922 if (
1923 this.options.search &&
1924 this.options.sidePagination === 'server' &&
1925 this.columns.filter(column => !column.searchable).length
1926 ) {
1927 params.searchable = []
1928
1929 for (const column of this.columns) {
1930 if (
1931 !column.checkbox &&
1932 column.searchable &&
1933 (
1934 this.options.visibleSearch &&
1935 column.visible ||
1936 !this.options.visibleSearch
1937 )
1938 ) {
1939 params.searchable.push(column.field)
1940 }
1941 }
1942 }
1943
1944 if (!(Utils.isEmptyObject(this.filterColumnsPartial))) {
1945 params.filter = JSON.stringify(this.filterColumnsPartial, null)
1946 }
1947
1948 $.extend(params, query || {})
1949
1950 data = Utils.calculateObjectValue(this.options, this.options.queryParams, [params], data)
1951
1952 // false to stop request
1953 if (data === false) {
1954 return
1955 }
1956
1957 if (!silent) {
1958 this.showLoading()
1959 }
1960 const request = $.extend({}, Utils.calculateObjectValue(null, this.options.ajaxOptions), {
1961 type: this.options.method,
1962 url: url || this.options.url,
1963 data: this.options.contentType === 'application/json' && this.options.method === 'post' ?
1964 JSON.stringify(data) : data,
1965 cache: this.options.cache,
1966 contentType: this.options.contentType,
1967 dataType: this.options.dataType,
1968 success: (_res, textStatus, jqXHR) => {
1969 const res = Utils.calculateObjectValue(this.options,
1970 this.options.responseHandler, [_res, jqXHR], _res)
1971
1972 this.load(res)
1973 this.trigger('load-success', res, jqXHR && jqXHR.status, jqXHR)
1974 if (!silent) {
1975 this.hideLoading()
1976 }
1977
1978 if (
1979 this.options.sidePagination === 'server' &&
1980 this.options.pageNumber > 1 &&
1981 res[this.options.totalField] > 0 &&
1982 !res[this.options.dataField].length
1983 ) {
1984 this.updatePagination()
1985 }
1986 },
1987 error: jqXHR => {
1988 // abort ajax by multiple request
1989 if (jqXHR && jqXHR.status === 0 && this._xhrAbort) {
1990 this._xhrAbort = false
1991 return
1992 }
1993
1994 let data = []
1995
1996 if (this.options.sidePagination === 'server') {
1997 data = {}
1998 data[this.options.totalField] = 0
1999 data[this.options.dataField] = []
2000 }
2001 this.load(data)
2002 this.trigger('load-error', jqXHR && jqXHR.status, jqXHR)
2003 if (!silent) this.$tableLoading.hide()
2004 }
2005 })
2006
2007 if (this.options.ajax) {
2008 Utils.calculateObjectValue(this, this.options.ajax, [request], null)
2009 } else {
2010 if (this._xhr && this._xhr.readyState !== 4) {
2011 this._xhrAbort = true
2012 this._xhr.abort()
2013 }
2014 this._xhr = $.ajax(request)
2015 }
2016
2017 return data
2018 }
2019
2020 initSearchText () {
2021 if (this.options.search) {
2022 this.searchText = ''
2023 if (this.options.searchText !== '') {
2024 const $search = Utils.getSearchInput(this)
2025
2026 $search.val(this.options.searchText)
2027 this.onSearch({ currentTarget: $search, firedByInitSearchText: true })
2028 }
2029 }
2030 }
2031
2032 getCaret () {
2033 this.$header.find('th').each((i, th) => {
2034 $(th).find('.sortable').removeClass('desc asc')
2035 .addClass($(th).data('field') === this.options.sortName ?
2036 this.options.sortOrder : 'both')
2037 })
2038 }
2039
2040 updateSelected () {
2041 const checkAll = this.$selectItem.filter(':enabled').length &&
2042 this.$selectItem.filter(':enabled').length ===
2043 this.$selectItem.filter(':enabled').filter(':checked').length
2044
2045 this.$selectAll.add(this.$selectAll_).prop('checked', checkAll)
2046
2047 this.$selectItem.each((i, el) => {
2048 $(el).closest('tr')[$(el).prop('checked') ? 'addClass' : 'removeClass']('selected')
2049 })
2050 }
2051
2052 updateRows () {
2053 this.$selectItem.each((i, el) => {
2054 this.data[$(el).data('index')][this.header.stateField] = $(el).prop('checked')
2055 })
2056 }
2057
2058 resetRows () {
2059 for (const row of this.data) {
2060 this.$selectAll.prop('checked', false)
2061 this.$selectItem.prop('checked', false)
2062 if (this.header.stateField) {
2063 row[this.header.stateField] = false
2064 }
2065 }
2066 this.initHiddenRows()
2067 }
2068
2069 trigger (_name, ...args) {
2070 const name = `${_name}.bs.table`
2071
2072 this.options[BootstrapTable.EVENTS[name]](...[...args, this])
2073 this.$el.trigger($.Event(name, { sender: this }), args)
2074
2075 this.options.onAll(name, ...[...args, this])
2076 this.$el.trigger($.Event('all.bs.table', { sender: this }), [name, args])
2077 }
2078
2079 resetHeader () {
2080 // fix #61: the hidden table reset header bug.
2081 // fix bug: get $el.css('width') error sometime (height = 500)
2082 clearTimeout(this.timeoutId_)
2083 this.timeoutId_ = setTimeout(() => this.fitHeader(), this.$el.is(':hidden') ? 100 : 0)
2084 }
2085
2086 fitHeader () {
2087 if (this.$el.is(':hidden')) {
2088 this.timeoutId_ = setTimeout(() => this.fitHeader(), 100)
2089 return
2090 }
2091
2092 const fixedBody = this.$tableBody.get(0)
2093 const scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
2094 fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ?
2095 Utils.getScrollBarWidth() : 0
2096
2097 this.$el.css('margin-top', -this.$header.outerHeight())
2098
2099 const focused = $(':focus')
2100
2101 if (focused.length > 0) {
2102 const $th = focused.parents('th')
2103
2104 if ($th.length > 0) {
2105 const dataField = $th.attr('data-field')
2106
2107 if (dataField !== undefined) {
2108 const $headerTh = this.$header.find(`[data-field='${dataField}']`)
2109
2110 if ($headerTh.length > 0) {
2111 $headerTh.find(':input').addClass('focus-temp')
2112 }
2113 }
2114 }
2115 }
2116
2117 this.$header_ = this.$header.clone(true, true)
2118 this.$selectAll_ = this.$header_.find('[name="btSelectAll"]')
2119 this.$tableHeader
2120 .css('margin-right', scrollWidth)
2121 .find('table').css('width', this.$el.outerWidth())
2122 .html('').attr('class', this.$el.attr('class'))
2123 .append(this.$header_)
2124
2125 this.$tableLoading.css('width', this.$el.outerWidth())
2126
2127 const focusedTemp = $('.focus-temp:visible:eq(0)')
2128
2129 if (focusedTemp.length > 0) {
2130 focusedTemp.focus()
2131 this.$header.find('.focus-temp').removeClass('focus-temp')
2132 }
2133
2134 // fix bug: $.data() is not working as expected after $.append()
2135 this.$header.find('th[data-field]').each((i, el) => {
2136 this.$header_.find(Utils.sprintf('th[data-field="%s"]', $(el).data('field'))).data($(el).data())
2137 })
2138
2139 const visibleFields = this.getVisibleFields()
2140 const $ths = this.$header_.find('th')
2141 let $tr = this.$body.find('>tr:not(.no-records-found,.virtual-scroll-top)').eq(0)
2142
2143 while ($tr.length && $tr.find('>td[colspan]:not([colspan="1"])').length) {
2144 $tr = $tr.next()
2145 }
2146
2147 const trLength = $tr.find('> *').length
2148
2149 $tr.find('> *').each((i, el) => {
2150 const $this = $(el)
2151
2152 if (Utils.hasDetailViewIcon(this.options)) {
2153 if (
2154 i === 0 && this.options.detailViewAlign !== 'right' ||
2155 i === trLength - 1 && this.options.detailViewAlign === 'right'
2156 ) {
2157 const $thDetail = $ths.filter('.detail')
2158 const zoomWidth = $thDetail.innerWidth() - $thDetail.find('.fht-cell').width()
2159
2160 $thDetail.find('.fht-cell').width($this.innerWidth() - zoomWidth)
2161 return
2162 }
2163 }
2164
2165 const index = i - Utils.getDetailViewIndexOffset(this.options)
2166 let $th = this.$header_.find(Utils.sprintf('th[data-field="%s"]', visibleFields[index]))
2167
2168 if ($th.length > 1) {
2169 $th = $($ths[$this[0].cellIndex])
2170 }
2171
2172 const zoomWidth = $th.innerWidth() - $th.find('.fht-cell').width()
2173
2174 $th.find('.fht-cell').width($this.innerWidth() - zoomWidth)
2175 })
2176
2177 this.horizontalScroll()
2178 this.trigger('post-header')
2179 }
2180
2181 initFooter () {
2182 if (!this.options.showFooter || this.options.cardView) { // do nothing
2183 return
2184 }
2185
2186 const data = this.getData()
2187 const html = []
2188 let detailTemplate = ''
2189
2190 if (Utils.hasDetailViewIcon(this.options)) {
2191 detailTemplate = '<th class="detail"><div class="th-inner"></div><div class="fht-cell"></div></th>'
2192 }
2193
2194 if (detailTemplate && this.options.detailViewAlign !== 'right') {
2195 html.push(detailTemplate)
2196 }
2197
2198 for (const column of this.columns) {
2199 let falign = ''
2200 let valign = ''
2201 const csses = []
2202 let style = {}
2203 let class_ = Utils.sprintf(' class="%s"', column['class'])
2204
2205 if (
2206 !column.visible ||
2207 (this.footerData && this.footerData.length > 0 && !(column.field in this.footerData[0]))
2208 ) {
2209 continue
2210 }
2211
2212 if (this.options.cardView && (!column.cardVisible)) {
2213 return
2214 }
2215
2216 falign = Utils.sprintf('text-align: %s; ', column.falign ? column.falign : column.align)
2217 valign = Utils.sprintf('vertical-align: %s; ', column.valign)
2218
2219 style = Utils.calculateObjectValue(null, this.options.footerStyle, [column])
2220
2221 if (style && style.css) {
2222 for (const [key, value] of Object.entries(style.css)) {
2223 csses.push(`${key}: ${value}`)
2224 }
2225 }
2226 if (style && style.classes) {
2227 class_ = Utils.sprintf(' class="%s"', column['class'] ?
2228 [column['class'], style.classes].join(' ') : style.classes)
2229 }
2230
2231 html.push('<th', class_, Utils.sprintf(' style="%s"', falign + valign + csses.concat().join('; ')))
2232 let colspan = 0
2233
2234 if (this.footerData && this.footerData.length > 0) {
2235 colspan = this.footerData[0][`_${ column.field }_colspan`] || 0
2236 }
2237 if (colspan) {
2238 html.push(` colspan="${colspan}" `)
2239 }
2240
2241 html.push('>')
2242 html.push('<div class="th-inner">')
2243
2244 let value = ''
2245
2246 if (this.footerData && this.footerData.length > 0) {
2247 value = this.footerData[0][column.field] || ''
2248 }
2249 html.push(Utils.calculateObjectValue(column, column.footerFormatter,
2250 [data, value], value))
2251
2252 html.push('</div>')
2253 html.push('<div class="fht-cell"></div>')
2254 html.push('</div>')
2255 html.push('</th>')
2256 }
2257
2258 if (detailTemplate && this.options.detailViewAlign === 'right') {
2259 html.push(detailTemplate)
2260 }
2261
2262 if (!this.options.height && !this.$tableFooter.length) {
2263 this.$el.append('<tfoot><tr></tr></tfoot>')
2264 this.$tableFooter = this.$el.find('tfoot')
2265 }
2266
2267 if (!this.$tableFooter.find('tr').length) {
2268 this.$tableFooter.html('<table><thead><tr></tr></thead></table>')
2269 }
2270
2271 this.$tableFooter.find('tr').html(html.join(''))
2272
2273 this.trigger('post-footer', this.$tableFooter)
2274 }
2275
2276 fitFooter () {
2277 if (this.$el.is(':hidden')) {
2278 setTimeout(() => this.fitFooter(), 100)
2279 return
2280 }
2281
2282 const fixedBody = this.$tableBody.get(0)
2283 const scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
2284 fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ?
2285 Utils.getScrollBarWidth() : 0
2286
2287 this.$tableFooter
2288 .css('margin-right', scrollWidth)
2289 .find('table').css('width', this.$el.outerWidth())
2290 .attr('class', this.$el.attr('class'))
2291
2292 const $ths = this.$tableFooter.find('th')
2293 let $tr = this.$body.find('>tr:first-child:not(.no-records-found)')
2294
2295 $ths.find('.fht-cell').width('auto')
2296
2297 while ($tr.length && $tr.find('>td[colspan]:not([colspan="1"])').length) {
2298 $tr = $tr.next()
2299 }
2300
2301 const trLength = $tr.find('> *').length
2302
2303 $tr.find('> *').each((i, el) => {
2304 const $this = $(el)
2305
2306 if (Utils.hasDetailViewIcon(this.options)) {
2307 if (
2308 i === 0 && this.options.detailViewAlign === 'left' ||
2309 i === trLength - 1 && this.options.detailViewAlign === 'right'
2310 ) {
2311 const $thDetail = $ths.filter('.detail')
2312 const zoomWidth = $thDetail.innerWidth() - $thDetail.find('.fht-cell').width()
2313
2314 $thDetail.find('.fht-cell').width($this.innerWidth() - zoomWidth)
2315 return
2316 }
2317 }
2318
2319 const $th = $ths.eq(i)
2320 const zoomWidth = $th.innerWidth() - $th.find('.fht-cell').width()
2321
2322 $th.find('.fht-cell').width($this.innerWidth() - zoomWidth)
2323 })
2324
2325 this.horizontalScroll()
2326 }
2327
2328 horizontalScroll () {
2329 // horizontal scroll event
2330 // TODO: it's probably better improving the layout than binding to scroll event
2331 this.$tableBody.off('scroll').on('scroll', () => {
2332 const scrollLeft = this.$tableBody.scrollLeft()
2333
2334 if (this.options.showHeader && this.options.height) {
2335 this.$tableHeader.scrollLeft(scrollLeft)
2336 }
2337
2338 if (this.options.showFooter && !this.options.cardView) {
2339 this.$tableFooter.scrollLeft(scrollLeft)
2340 }
2341
2342 this.trigger('scroll-body', this.$tableBody)
2343 })
2344 }
2345
2346 getVisibleFields () {
2347 const visibleFields = []
2348
2349 for (const field of this.header.fields) {
2350 const column = this.columns[this.fieldsColumnsIndex[field]]
2351
2352 if (!column || !column.visible) {
2353 continue
2354 }
2355 visibleFields.push(field)
2356 }
2357 return visibleFields
2358 }
2359
2360 initHiddenRows () {
2361 this.hiddenRows = []
2362 }
2363
2364 // PUBLIC FUNCTION DEFINITION
2365 // =======================
2366
2367 getOptions () {
2368 // deep copy and remove data
2369 const options = $.extend({}, this.options)
2370
2371 delete options.data
2372 return $.extend(true, {}, options)
2373 }
2374
2375 refreshOptions (options) {
2376 // If the objects are equivalent then avoid the call of destroy / init methods
2377 if (Utils.compareObjects(this.options, options, true)) {
2378 return
2379 }
2380 this.options = $.extend(this.options, options)
2381 this.trigger('refresh-options', this.options)
2382 this.destroy()
2383 this.init()
2384 }
2385
2386 getData (params) {
2387 let data = this.options.data
2388
2389 if (
2390 (
2391 this.searchText ||
2392 this.options.customSearch ||
2393 this.options.sortName !== undefined ||
2394 this.enableCustomSort || // Fix #4616: this.enableCustomSort is for extensions
2395 !Utils.isEmptyObject(this.filterColumns) ||
2396 !Utils.isEmptyObject(this.filterColumnsPartial)
2397 ) && (!params || !params.unfiltered)
2398 ) {
2399 data = this.data
2400 }
2401
2402 if (params && params.useCurrentPage) {
2403 data = data.slice(this.pageFrom - 1, this.pageTo)
2404 }
2405
2406 if (params && !params.includeHiddenRows) {
2407 const hiddenRows = this.getHiddenRows()
2408
2409 data = data.filter(row => Utils.findIndex(hiddenRows, row) === -1)
2410 }
2411
2412 if (params && params.formatted) {
2413 data.forEach(row => {
2414 for (const [key, value] of Object.entries(row)) {
2415 const column = this.columns[this.fieldsColumnsIndex[key]]
2416
2417 if (!column) {
2418 return
2419 }
2420
2421 row[key] = Utils.calculateObjectValue(column, this.header.formatters[column.fieldIndex], [value, row, row.index, column.field], value)
2422 }
2423 })
2424 }
2425
2426 return data
2427 }
2428
2429 getSelections () {
2430 return (this.options.maintainMetaData ? this.options.data : this.data)
2431 .filter(row => row[this.header.stateField] === true)
2432 }
2433
2434 load (_data) {
2435 let fixedScroll = false
2436 let data = _data
2437
2438 // #431: support pagination
2439 if (this.options.pagination && this.options.sidePagination === 'server') {
2440 this.options.totalRows = data[this.options.totalField]
2441 this.options.totalNotFiltered = data[this.options.totalNotFilteredField]
2442 this.footerData = data[this.options.footerField] ? [data[this.options.footerField]] : undefined
2443 }
2444
2445 fixedScroll = data.fixedScroll
2446 data = Array.isArray(data) ? data : data[this.options.dataField]
2447
2448 this.initData(data)
2449 this.initSearch()
2450 this.initPagination()
2451 this.initBody(fixedScroll)
2452 }
2453
2454 append (data) {
2455 this.initData(data, 'append')
2456 this.initSearch()
2457 this.initPagination()
2458 this.initSort()
2459 this.initBody(true)
2460 }
2461
2462 prepend (data) {
2463 this.initData(data, 'prepend')
2464 this.initSearch()
2465 this.initPagination()
2466 this.initSort()
2467 this.initBody(true)
2468 }
2469
2470 remove (params) {
2471 let removed = 0
2472
2473 for (let i = this.options.data.length - 1; i >= 0; i--) {
2474
2475 const row = this.options.data[i]
2476
2477 if (!row.hasOwnProperty(params.field) && params.field !== '$index') {
2478 continue
2479 }
2480
2481 if (
2482 !row.hasOwnProperty(params.field) &&
2483 params.field === '$index' &&
2484 params.values.includes(i) ||
2485 params.values.includes(row[params.field])
2486 ) {
2487 removed++
2488
2489 this.options.data.splice(i, 1)
2490 }
2491 }
2492
2493 if (!removed) {
2494 return
2495 }
2496
2497 if (this.options.sidePagination === 'server') {
2498 this.options.totalRows -= removed
2499 this.data = [...this.options.data]
2500 }
2501
2502 this.initSearch()
2503 this.initPagination()
2504 this.initSort()
2505 this.initBody(true)
2506 }
2507
2508 removeAll () {
2509 if (this.options.data.length > 0) {
2510 this.options.data.splice(0, this.options.data.length)
2511 this.initSearch()
2512 this.initPagination()
2513 this.initBody(true)
2514 }
2515 }
2516
2517 insertRow (params) {
2518 if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
2519 return
2520 }
2521 this.options.data.splice(params.index, 0, params.row)
2522 this.initSearch()
2523 this.initPagination()
2524 this.initSort()
2525 this.initBody(true)
2526 }
2527
2528 updateRow (params) {
2529 const allParams = Array.isArray(params) ? params : [params]
2530
2531 for (const params of allParams) {
2532 if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
2533 continue
2534 }
2535
2536 if (params.hasOwnProperty('replace') && params.replace) {
2537 this.options.data[params.index] = params.row
2538 } else {
2539 $.extend(this.options.data[params.index], params.row)
2540 }
2541 }
2542
2543 this.initSearch()
2544 this.initPagination()
2545 this.initSort()
2546 this.initBody(true)
2547 }
2548
2549 getRowByUniqueId (_id) {
2550 const uniqueId = this.options.uniqueId
2551 const len = this.options.data.length
2552 let id = _id
2553 let dataRow = null
2554 let i
2555 let row
2556 let rowUniqueId
2557
2558 for (i = len - 1; i >= 0; i--) {
2559 row = this.options.data[i]
2560
2561 if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column
2562 rowUniqueId = row[uniqueId]
2563 } else if (row._data && row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property
2564 rowUniqueId = row._data[uniqueId]
2565 } else {
2566 continue
2567 }
2568
2569 if (typeof rowUniqueId === 'string') {
2570 id = id.toString()
2571 } else if (typeof rowUniqueId === 'number') {
2572 if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) {
2573 id = parseInt(id, 10)
2574 } else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) {
2575 id = parseFloat(id)
2576 }
2577 }
2578
2579 if (rowUniqueId === id) {
2580 dataRow = row
2581 break
2582 }
2583 }
2584
2585 return dataRow
2586 }
2587
2588 updateByUniqueId (params) {
2589 const allParams = Array.isArray(params) ? params : [params]
2590 let updatedUid = null
2591
2592 for (const params of allParams) {
2593 if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
2594 continue
2595 }
2596
2597 const rowId = this.options.data.indexOf(this.getRowByUniqueId(params.id))
2598
2599 if (rowId === -1) {
2600 continue
2601 }
2602
2603 if (params.hasOwnProperty('replace') && params.replace) {
2604 this.options.data[rowId] = params.row
2605 } else {
2606 $.extend(this.options.data[rowId], params.row)
2607 }
2608 updatedUid = params.id
2609 }
2610
2611 this.initSearch()
2612 this.initPagination()
2613 this.initSort()
2614 this.initBody(true, updatedUid)
2615 }
2616
2617 removeByUniqueId (id) {
2618 const len = this.options.data.length
2619 const row = this.getRowByUniqueId(id)
2620
2621 if (row) {
2622 this.options.data.splice(this.options.data.indexOf(row), 1)
2623 }
2624
2625 if (len === this.options.data.length) {
2626 return
2627 }
2628
2629 if (this.options.sidePagination === 'server') {
2630 this.options.totalRows -= 1
2631 this.data = [...this.options.data]
2632 }
2633
2634 this.initSearch()
2635 this.initPagination()
2636 this.initBody(true)
2637 }
2638
2639 updateCell (params) {
2640 if (!params.hasOwnProperty('index') ||
2641 !params.hasOwnProperty('field') ||
2642 !params.hasOwnProperty('value')) {
2643 return
2644 }
2645 this.data[params.index][params.field] = params.value
2646
2647 if (params.reinit === false) {
2648 return
2649 }
2650 this.initSort()
2651 this.initBody(true)
2652 }
2653
2654 updateCellByUniqueId (params) {
2655 const allParams = Array.isArray(params) ? params : [params]
2656
2657 allParams.forEach(({ id, field, value }) => {
2658 const rowId = this.options.data.indexOf(this.getRowByUniqueId(id))
2659
2660 if (rowId === -1) {
2661 return
2662 }
2663 this.options.data[rowId][field] = value
2664 })
2665
2666 if (params.reinit === false) {
2667 return
2668 }
2669 this.initSort()
2670 this.initBody(true)
2671 }
2672
2673 showRow (params) {
2674 this._toggleRow(params, true)
2675 }
2676
2677 hideRow (params) {
2678 this._toggleRow(params, false)
2679 }
2680
2681 _toggleRow (params, visible) {
2682 let row
2683
2684 if (params.hasOwnProperty('index')) {
2685 row = this.getData()[params.index]
2686 } else if (params.hasOwnProperty('uniqueId')) {
2687 row = this.getRowByUniqueId(params.uniqueId)
2688 }
2689
2690 if (!row) {
2691 return
2692 }
2693
2694 const index = Utils.findIndex(this.hiddenRows, row)
2695
2696 if (!visible && index === -1) {
2697 this.hiddenRows.push(row)
2698 } else if (visible && index > -1) {
2699 this.hiddenRows.splice(index, 1)
2700 }
2701
2702 this.initBody(true)
2703 this.initPagination()
2704 }
2705
2706 getHiddenRows (show) {
2707 if (show) {
2708 this.initHiddenRows()
2709 this.initBody(true)
2710 this.initPagination()
2711 return
2712 }
2713 const data = this.getData()
2714 const rows = []
2715
2716 for (const row of data) {
2717 if (this.hiddenRows.includes(row)) {
2718 rows.push(row)
2719 }
2720 }
2721 this.hiddenRows = rows
2722 return rows
2723 }
2724
2725 showColumn (field) {
2726 const fields = Array.isArray(field) ? field : [field]
2727
2728 fields.forEach(field => {
2729 this._toggleColumn(this.fieldsColumnsIndex[field], true, true)
2730 })
2731 }
2732
2733 hideColumn (field) {
2734 const fields = Array.isArray(field) ? field : [field]
2735
2736 fields.forEach(field => {
2737 this._toggleColumn(this.fieldsColumnsIndex[field], false, true)
2738 })
2739 }
2740
2741 _toggleColumn (index, checked, needUpdate) {
2742 if (index === -1 || this.columns[index].visible === checked) {
2743 return
2744 }
2745 this.columns[index].visible = checked
2746 this.initHeader()
2747 this.initSearch()
2748 this.initPagination()
2749 this.initBody()
2750
2751 if (this.options.showColumns) {
2752 const $items = this.$toolbar.find('.keep-open input:not(".toggle-all")').prop('disabled', false)
2753
2754 if (needUpdate) {
2755 $items.filter(Utils.sprintf('[value="%s"]', index)).prop('checked', checked)
2756 }
2757
2758 if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
2759 $items.filter(':checked').prop('disabled', true)
2760 }
2761 }
2762 }
2763
2764 getVisibleColumns () {
2765 return this.columns.filter(column => column.visible && !this.isSelectionColumn(column))
2766 }
2767
2768 getHiddenColumns () {
2769 return this.columns.filter(({ visible }) => !visible)
2770 }
2771
2772 isSelectionColumn (column) {
2773 return column.radio || column.checkbox
2774 }
2775
2776 showAllColumns () {
2777 this._toggleAllColumns(true)
2778 }
2779
2780 hideAllColumns () {
2781 this._toggleAllColumns(false)
2782 }
2783
2784 _toggleAllColumns (visible) {
2785 for (const column of this.columns.slice().reverse()) {
2786 if (column.switchable) {
2787 if (!visible && this.options.showColumns && this.getVisibleColumns().length === this.options.minimumCountColumns) {
2788 continue
2789 }
2790 column.visible = visible
2791 }
2792 }
2793
2794 this.initHeader()
2795 this.initSearch()
2796 this.initPagination()
2797 this.initBody()
2798 if (this.options.showColumns) {
2799 const $items = this.$toolbar.find('.keep-open input[type="checkbox"]:not(".toggle-all")').prop('disabled', false)
2800
2801 if (visible) {
2802 $items.prop('checked', visible)
2803 } else {
2804 $items.get().reverse().forEach(item => {
2805 if ($items.filter(':checked').length > this.options.minimumCountColumns) {
2806 $(item).prop('checked', visible)
2807 }
2808 })
2809 }
2810
2811 if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
2812 $items.filter(':checked').prop('disabled', true)
2813 }
2814 }
2815 }
2816
2817 mergeCells (options) {
2818 const row = options.index
2819 let col = this.getVisibleFields().indexOf(options.field)
2820 const rowspan = options.rowspan || 1
2821 const colspan = options.colspan || 1
2822 let i
2823 let j
2824 const $tr = this.$body.find('>tr[data-index]')
2825
2826 col += Utils.getDetailViewIndexOffset(this.options)
2827
2828 const $td = $tr.eq(row).find('>td').eq(col)
2829
2830 if (row < 0 || col < 0 || row >= this.data.length) {
2831 return
2832 }
2833
2834 for (i = row; i < row + rowspan; i++) {
2835 for (j = col; j < col + colspan; j++) {
2836 $tr.eq(i).find('>td').eq(j).hide()
2837 }
2838 }
2839
2840 $td.attr('rowspan', rowspan).attr('colspan', colspan).show()
2841 }
2842
2843 checkAll () {
2844 this._toggleCheckAll(true)
2845 }
2846
2847 uncheckAll () {
2848 this._toggleCheckAll(false)
2849 }
2850
2851 _toggleCheckAll (checked) {
2852 const rowsBefore = this.getSelections()
2853
2854 this.$selectAll.add(this.$selectAll_).prop('checked', checked)
2855 this.$selectItem.filter(':enabled').prop('checked', checked)
2856 this.updateRows()
2857 this.updateSelected()
2858
2859 const rowsAfter = this.getSelections()
2860
2861 if (checked) {
2862 this.trigger('check-all', rowsAfter, rowsBefore)
2863 return
2864 }
2865
2866 this.trigger('uncheck-all', rowsAfter, rowsBefore)
2867 }
2868
2869 checkInvert () {
2870 const $items = this.$selectItem.filter(':enabled')
2871 let checked = $items.filter(':checked')
2872
2873 $items.each((i, el) => {
2874 $(el).prop('checked', !$(el).prop('checked'))
2875 })
2876 this.updateRows()
2877 this.updateSelected()
2878 this.trigger('uncheck-some', checked)
2879 checked = this.getSelections()
2880 this.trigger('check-some', checked)
2881 }
2882
2883 check (index) {
2884 this._toggleCheck(true, index)
2885 }
2886
2887 uncheck (index) {
2888 this._toggleCheck(false, index)
2889 }
2890
2891 _toggleCheck (checked, index) {
2892 const $el = this.$selectItem.filter(`[data-index="${index}"]`)
2893 const row = this.data[index]
2894
2895 if (
2896 $el.is(':radio') ||
2897 this.options.singleSelect ||
2898 this.options.multipleSelectRow &&
2899 !this.multipleSelectRowCtrlKey &&
2900 !this.multipleSelectRowShiftKey
2901 ) {
2902 for (const r of this.options.data) {
2903 r[this.header.stateField] = false
2904 }
2905 this.$selectItem.filter(':checked').not($el).prop('checked', false)
2906 }
2907
2908 row[this.header.stateField] = checked
2909
2910 if (this.options.multipleSelectRow) {
2911 if (this.multipleSelectRowShiftKey && this.multipleSelectRowLastSelectedIndex >= 0) {
2912 const [fromIndex, toIndex] = this.multipleSelectRowLastSelectedIndex < index ?
2913 [this.multipleSelectRowLastSelectedIndex, index] : [index, this.multipleSelectRowLastSelectedIndex]
2914
2915 for (let i = fromIndex + 1; i < toIndex; i++) {
2916 this.data[i][this.header.stateField] = true
2917 this.$selectItem.filter(`[data-index="${i}"]`).prop('checked', true)
2918 }
2919 }
2920
2921 this.multipleSelectRowCtrlKey = false
2922 this.multipleSelectRowShiftKey = false
2923 this.multipleSelectRowLastSelectedIndex = checked ? index : -1
2924 }
2925
2926 $el.prop('checked', checked)
2927 this.updateSelected()
2928 this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el)
2929 }
2930
2931 checkBy (obj) {
2932 this._toggleCheckBy(true, obj)
2933 }
2934
2935 uncheckBy (obj) {
2936 this._toggleCheckBy(false, obj)
2937 }
2938
2939 _toggleCheckBy (checked, obj) {
2940 if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
2941 return
2942 }
2943
2944 const rows = []
2945
2946 this.data.forEach((row, i) => {
2947 if (!row.hasOwnProperty(obj.field)) {
2948 return false
2949 }
2950 if (obj.values.includes(row[obj.field])) {
2951 let $el = this.$selectItem.filter(':enabled')
2952 .filter(Utils.sprintf('[data-index="%s"]', i))
2953 const onlyCurrentPage = obj.hasOwnProperty('onlyCurrentPage') ? obj.onlyCurrentPage : false
2954
2955 $el = checked ? $el.not(':checked') : $el.filter(':checked')
2956
2957 if (!$el.length && onlyCurrentPage) {
2958 return
2959 }
2960
2961 $el.prop('checked', checked)
2962 row[this.header.stateField] = checked
2963 rows.push(row)
2964 this.trigger(checked ? 'check' : 'uncheck', row, $el)
2965 }
2966 })
2967 this.updateSelected()
2968 this.trigger(checked ? 'check-some' : 'uncheck-some', rows)
2969 }
2970
2971 refresh (params) {
2972 if (params && params.url) {
2973 this.options.url = params.url
2974 }
2975 if (params && params.pageNumber) {
2976 this.options.pageNumber = params.pageNumber
2977 }
2978 if (params && params.pageSize) {
2979 this.options.pageSize = params.pageSize
2980 }
2981 this.trigger('refresh', this.initServer(params && params.silent,
2982 params && params.query, params && params.url))
2983 }
2984
2985 destroy () {
2986 this.$el.insertBefore(this.$container)
2987 $(this.options.toolbar).insertBefore(this.$el)
2988 this.$container.next().remove()
2989 this.$container.remove()
2990 this.$el.html(this.$el_.html())
2991 .css('margin-top', '0')
2992 .attr('class', this.$el_.attr('class') || '') // reset the class
2993 }
2994
2995 resetView (params) {
2996 let padding = 0
2997
2998 if (params && params.height) {
2999 this.options.height = params.height
3000 }
3001
3002 this.$tableContainer.toggleClass('has-card-view', this.options.cardView)
3003
3004 if (!this.options.cardView && this.options.showHeader && this.options.height) {
3005 this.$tableHeader.show()
3006 this.resetHeader()
3007 padding += this.$header.outerHeight(true) + 1
3008 } else {
3009 this.$tableHeader.hide()
3010 this.trigger('post-header')
3011 }
3012
3013 if (!this.options.cardView && this.options.showFooter) {
3014 this.$tableFooter.show()
3015 this.fitFooter()
3016 if (this.options.height) {
3017 padding += this.$tableFooter.outerHeight(true)
3018 }
3019 }
3020
3021 if (this.$container.hasClass('fullscreen')) {
3022 this.$tableContainer.css('height', '')
3023 this.$tableContainer.css('width', '')
3024 } else if (this.options.height) {
3025 if (this.$tableBorder) {
3026 this.$tableBorder.css('width', '')
3027 this.$tableBorder.css('height', '')
3028 }
3029
3030 const toolbarHeight = this.$toolbar.outerHeight(true)
3031 const paginationHeight = this.$pagination.outerHeight(true)
3032 const height = this.options.height - toolbarHeight - paginationHeight
3033 const $bodyTable = this.$tableBody.find('>table')
3034 const tableHeight = $bodyTable.outerHeight()
3035
3036 this.$tableContainer.css('height', `${height}px`)
3037
3038 if (this.$tableBorder && $bodyTable.is(':visible')) {
3039 let tableBorderHeight = height - tableHeight - 2
3040
3041 if (this.$tableBody[0].scrollWidth - this.$tableBody.innerWidth()) {
3042 tableBorderHeight -= Utils.getScrollBarWidth()
3043 }
3044 this.$tableBorder.css('width', `${$bodyTable.outerWidth()}px`)
3045 this.$tableBorder.css('height', `${tableBorderHeight}px`)
3046 }
3047 }
3048
3049 if (this.options.cardView) {
3050 // remove the element css
3051 this.$el.css('margin-top', '0')
3052 this.$tableContainer.css('padding-bottom', '0')
3053 this.$tableFooter.hide()
3054 } else {
3055 // Assign the correct sortable arrow
3056 this.getCaret()
3057 this.$tableContainer.css('padding-bottom', `${padding}px`)
3058 }
3059
3060 this.trigger('reset-view')
3061 }
3062
3063 showLoading () {
3064 this.$tableLoading.toggleClass('open', true)
3065
3066 let fontSize = this.options.loadingFontSize
3067
3068 if (this.options.loadingFontSize === 'auto') {
3069 fontSize = this.$tableLoading.width() * 0.04
3070 fontSize = Math.max(12, fontSize)
3071 fontSize = Math.min(32, fontSize)
3072 fontSize = `${fontSize}px`
3073 }
3074
3075 this.$tableLoading.find('.loading-text').css('font-size', fontSize)
3076 }
3077
3078 hideLoading () {
3079 this.$tableLoading.toggleClass('open', false)
3080 }
3081
3082 togglePagination () {
3083 this.options.pagination = !this.options.pagination
3084
3085 const icon = this.options.showButtonIcons ? this.options.pagination ? this.options.icons.paginationSwitchDown : this.options.icons.paginationSwitchUp : ''
3086 const text = this.options.showButtonText ? this.options.pagination ? this.options.formatPaginationSwitchUp() : this.options.formatPaginationSwitchDown() : ''
3087
3088 this.$toolbar.find('button[name="paginationSwitch"]')
3089 .html(`${Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, icon) } ${ text}`)
3090 this.updatePagination()
3091 this.trigger('toggle-pagination', this.options.pagination)
3092 }
3093
3094 toggleFullscreen () {
3095 this.$el.closest('.bootstrap-table').toggleClass('fullscreen')
3096 this.resetView()
3097 }
3098
3099 toggleView () {
3100 this.options.cardView = !this.options.cardView
3101 this.initHeader()
3102
3103 const icon = this.options.showButtonIcons ? this.options.cardView ? this.options.icons.toggleOn : this.options.icons.toggleOff : ''
3104 const text = this.options.showButtonText ? this.options.cardView ? this.options.formatToggleOff() : this.options.formatToggleOn() : ''
3105
3106 this.$toolbar.find('button[name="toggle"]')
3107 .html(`${Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, icon) } ${ text}`)
3108 this.initBody()
3109 this.trigger('toggle', this.options.cardView)
3110 }
3111
3112 resetSearch (text) {
3113 const $search = Utils.getSearchInput(this)
3114
3115 $search.val(text || '')
3116 this.onSearch({ currentTarget: $search })
3117 }
3118
3119 filterBy (columns, options) {
3120 this.filterOptions = Utils.isEmptyObject(options) ? this.options.filterOptions : $.extend(this.options.filterOptions, options)
3121 this.filterColumns = Utils.isEmptyObject(columns) ? {} : columns
3122 this.options.pageNumber = 1
3123 this.initSearch()
3124 this.updatePagination()
3125 }
3126
3127 scrollTo (params) {
3128 let options = { unit: 'px', value: 0 }
3129
3130 if (typeof params === 'object') {
3131 options = Object.assign(options, params)
3132 } else if (typeof params === 'string' && params === 'bottom') {
3133 options.value = this.$tableBody[0].scrollHeight
3134 } else if (typeof params === 'string' || typeof params === 'number') {
3135 options.value = params
3136 }
3137
3138 let scrollTo = options.value
3139
3140 if (options.unit === 'rows') {
3141 scrollTo = 0
3142 this.$body.find(`> tr:lt(${options.value})`).each((i, el) => {
3143 scrollTo += $(el).outerHeight(true)
3144 })
3145 }
3146
3147 this.$tableBody.scrollTop(scrollTo)
3148 }
3149
3150 getScrollPosition () {
3151 return this.$tableBody.scrollTop()
3152 }
3153
3154 selectPage (page) {
3155 if (page > 0 && page <= this.options.totalPages) {
3156 this.options.pageNumber = page
3157 this.updatePagination()
3158 }
3159 }
3160
3161 prevPage () {
3162 if (this.options.pageNumber > 1) {
3163 this.options.pageNumber--
3164 this.updatePagination()
3165 }
3166 }
3167
3168 nextPage () {
3169 if (this.options.pageNumber < this.options.totalPages) {
3170 this.options.pageNumber++
3171 this.updatePagination()
3172 }
3173 }
3174
3175 toggleDetailView (index, _columnDetailFormatter) {
3176 const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"]', index))
3177
3178 if ($tr.next().is('tr.detail-view')) {
3179 this.collapseRow(index)
3180 } else {
3181 this.expandRow(index, _columnDetailFormatter)
3182 }
3183
3184 this.resetView()
3185 }
3186
3187 expandRow (index, _columnDetailFormatter) {
3188 const row = this.data[index]
3189 const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"][data-has-detail-view]', index))
3190
3191 if (this.options.detailViewIcon) {
3192 $tr.find('a.detail-icon').html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailClose))
3193 }
3194
3195 if ($tr.next().is('tr.detail-view')) {
3196 return
3197 }
3198
3199 $tr.after(Utils.sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.children('td').length))
3200
3201 const $element = $tr.next().find('td')
3202
3203 const detailFormatter = _columnDetailFormatter || this.options.detailFormatter
3204 const content = Utils.calculateObjectValue(this.options, detailFormatter, [index, row, $element], '')
3205
3206 if ($element.length === 1) {
3207 $element.append(content)
3208 }
3209
3210 this.trigger('expand-row', index, row, $element)
3211 }
3212
3213 expandRowByUniqueId (uniqueId) {
3214 const row = this.getRowByUniqueId(uniqueId)
3215
3216 if (!row) {
3217 return
3218 }
3219
3220 this.expandRow(this.data.indexOf(row))
3221 }
3222
3223 collapseRow (index) {
3224 const row = this.data[index]
3225 const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"][data-has-detail-view]', index))
3226
3227 if (!$tr.next().is('tr.detail-view')) {
3228 return
3229 }
3230
3231 if (this.options.detailViewIcon) {
3232 $tr.find('a.detail-icon').html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailOpen))
3233 }
3234
3235 this.trigger('collapse-row', index, row, $tr.next())
3236 $tr.next().remove()
3237 }
3238
3239 collapseRowByUniqueId (uniqueId) {
3240 const row = this.getRowByUniqueId(uniqueId)
3241
3242 if (!row) {
3243 return
3244 }
3245
3246 this.collapseRow(this.data.indexOf(row))
3247 }
3248
3249 expandAllRows () {
3250 const trs = this.$body.find('> tr[data-index][data-has-detail-view]')
3251
3252 for (let i = 0; i < trs.length; i++) {
3253 this.expandRow($(trs[i]).data('index'))
3254 }
3255 }
3256
3257 collapseAllRows () {
3258 const trs = this.$body.find('> tr[data-index][data-has-detail-view]')
3259
3260 for (let i = 0; i < trs.length; i++) {
3261 this.collapseRow($(trs[i]).data('index'))
3262 }
3263 }
3264
3265 updateColumnTitle (params) {
3266 if (!params.hasOwnProperty('field') || !params.hasOwnProperty('title')) {
3267 return
3268 }
3269
3270 this.columns[this.fieldsColumnsIndex[params.field]].title =
3271 this.options.escape ? Utils.escapeHTML(params.title) : params.title
3272
3273 if (this.columns[this.fieldsColumnsIndex[params.field]].visible) {
3274 this.$header.find('th[data-field]').each((i, el) => {
3275 if ($(el).data('field') === params.field) {
3276 $($(el).find('.th-inner')[0]).text(params.title)
3277 return false
3278 }
3279 })
3280
3281 this.resetView()
3282 }
3283 }
3284
3285 updateFormatText (formatName, text) {
3286 if (!/^format/.test(formatName) || !this.options[formatName]) {
3287 return
3288 }
3289 if (typeof text === 'string') {
3290 this.options[formatName] = () => text
3291 } else if (typeof text === 'function') {
3292 this.options[formatName] = text
3293 }
3294 this.initToolbar()
3295 this.initPagination()
3296 this.initBody()
3297 }
3298}
3299
3300BootstrapTable.VERSION = Constants.VERSION
3301BootstrapTable.DEFAULTS = Constants.DEFAULTS
3302BootstrapTable.LOCALES = Constants.LOCALES
3303BootstrapTable.COLUMN_DEFAULTS = Constants.COLUMN_DEFAULTS
3304BootstrapTable.METHODS = Constants.METHODS
3305BootstrapTable.EVENTS = Constants.EVENTS
3306
3307// BOOTSTRAP TABLE PLUGIN DEFINITION
3308// =======================
3309
3310$.BootstrapTable = BootstrapTable
3311$.fn.bootstrapTable = function (option, ...args) {
3312 let value
3313
3314 this.each((i, el) => {
3315 let data = $(el).data('bootstrap.table')
3316 const options = $.extend({}, BootstrapTable.DEFAULTS, $(el).data(),
3317 typeof option === 'object' && option)
3318
3319 if (typeof option === 'string') {
3320 if (!Constants.METHODS.includes(option)) {
3321 throw new Error(`Unknown method: ${option}`)
3322 }
3323
3324 if (!data) {
3325 return
3326 }
3327
3328 value = data[option](...args)
3329
3330 if (option === 'destroy') {
3331 $(el).removeData('bootstrap.table')
3332 }
3333 }
3334
3335 if (!data) {
3336 data = new $.BootstrapTable(el, options)
3337 $(el).data('bootstrap.table', data)
3338 data.init()
3339 }
3340 })
3341
3342 return typeof value === 'undefined' ? this : value
3343}
3344
3345$.fn.bootstrapTable.Constructor = BootstrapTable
3346$.fn.bootstrapTable.theme = Constants.THEME
3347$.fn.bootstrapTable.VERSION = Constants.VERSION
3348$.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS
3349$.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS
3350$.fn.bootstrapTable.events = BootstrapTable.EVENTS
3351$.fn.bootstrapTable.locales = BootstrapTable.LOCALES
3352$.fn.bootstrapTable.methods = BootstrapTable.METHODS
3353$.fn.bootstrapTable.utils = Utils
3354
3355// BOOTSTRAP TABLE INIT
3356// =======================
3357
3358$(() => {
3359 $('[data-toggle="table"]').bootstrapTable()
3360})
3361
3362export default BootstrapTable