UNPKG

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