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