bootstrap-table.js 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872
  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * version: 1.15.4
  4. * https://github.com/wenzhixin/bootstrap-table/
  5. */
  6. import Constants from './constants/index.js'
  7. import Utils from './utils/index.js'
  8. import VirtualScroll from './virtual-scroll/index.js'
  9. class BootstrapTable {
  10. constructor (el, options) {
  11. this.options = options
  12. this.$el = $(el)
  13. this.$el_ = this.$el.clone()
  14. this.timeoutId_ = 0
  15. this.timeoutFooter_ = 0
  16. this.init()
  17. }
  18. init () {
  19. this.initConstants()
  20. this.initLocale()
  21. this.initContainer()
  22. this.initTable()
  23. this.initHeader()
  24. this.initData()
  25. this.initHiddenRows()
  26. this.initToolbar()
  27. this.initPagination()
  28. this.initBody()
  29. this.initSearchText()
  30. this.initServer()
  31. }
  32. initConstants () {
  33. const o = this.options
  34. this.constants = Constants.CONSTANTS
  35. this.constants.theme = $.fn.bootstrapTable.theme
  36. const buttonsPrefix = o.buttonsPrefix ? `${o.buttonsPrefix}-` : ''
  37. this.constants.buttonsClass = [
  38. o.buttonsPrefix,
  39. buttonsPrefix + o.buttonsClass,
  40. Utils.sprintf(`${buttonsPrefix}%s`, o.iconSize)
  41. ].join(' ').trim()
  42. }
  43. initLocale () {
  44. if (this.options.locale) {
  45. const locales = $.fn.bootstrapTable.locales
  46. const parts = this.options.locale.split(/-|_/)
  47. parts[0] = parts[0].toLowerCase()
  48. if (parts[1]) {
  49. parts[1] = parts[1].toUpperCase()
  50. }
  51. if (locales[this.options.locale]) {
  52. $.extend(this.options, locales[this.options.locale])
  53. } else if (locales[parts.join('-')]) {
  54. $.extend(this.options, locales[parts.join('-')])
  55. } else if (locales[parts[0]]) {
  56. $.extend(this.options, locales[parts[0]])
  57. }
  58. }
  59. }
  60. initContainer () {
  61. const topPagination = ['top', 'both'].includes(this.options.paginationVAlign)
  62. ? '<div class="fixed-table-pagination clearfix"></div>' : ''
  63. const bottomPagination = ['bottom', 'both'].includes(this.options.paginationVAlign)
  64. ? '<div class="fixed-table-pagination"></div>' : ''
  65. this.$container = $(`
  66. <div class="bootstrap-table ${this.constants.theme}">
  67. <div class="fixed-table-toolbar"></div>
  68. ${topPagination}
  69. <div class="fixed-table-container">
  70. <div class="fixed-table-header"><table></table></div>
  71. <div class="fixed-table-body">
  72. <div class="fixed-table-loading">
  73. <span class="loading-wrap">
  74. <span class="loading-text">${this.options.formatLoadingMessage()}</span>
  75. <span class="animation-wrap"><span class="animation-dot"></span></span>
  76. </span>
  77. </div>
  78. </div>
  79. <div class="fixed-table-footer"><table><thead><tr></tr></thead></table></div>
  80. </div>
  81. ${bottomPagination}
  82. </div>
  83. `)
  84. this.$container.insertAfter(this.$el)
  85. this.$tableContainer = this.$container.find('.fixed-table-container')
  86. this.$tableHeader = this.$container.find('.fixed-table-header')
  87. this.$tableBody = this.$container.find('.fixed-table-body')
  88. this.$tableLoading = this.$container.find('.fixed-table-loading')
  89. this.$tableFooter = this.$el.find('tfoot')
  90. // checking if custom table-toolbar exists or not
  91. if (this.options.buttonsToolbar) {
  92. this.$toolbar = $('body').find(this.options.buttonsToolbar)
  93. } else {
  94. this.$toolbar = this.$container.find('.fixed-table-toolbar')
  95. }
  96. this.$pagination = this.$container.find('.fixed-table-pagination')
  97. this.$tableBody.append(this.$el)
  98. this.$container.after('<div class="clearfix"></div>')
  99. this.$el.addClass(this.options.classes)
  100. this.$tableLoading.addClass(this.options.classes)
  101. if (this.options.height) {
  102. this.$tableContainer.addClass('fixed-height')
  103. if (this.options.showFooter) {
  104. this.$tableContainer.addClass('has-footer')
  105. }
  106. if (this.options.classes.split(' ').includes('table-bordered')) {
  107. this.$tableBody.append('<div class="fixed-table-border"></div>')
  108. this.$tableBorder = this.$tableBody.find('.fixed-table-border')
  109. this.$tableLoading.addClass('fixed-table-border')
  110. }
  111. this.$tableFooter = this.$container.find('.fixed-table-footer')
  112. } else {
  113. if (!this.$tableFooter.length) {
  114. this.$el.append('<tfoot><tr></tr></tfoot>')
  115. this.$tableFooter = this.$el.find('tfoot')
  116. }
  117. }
  118. }
  119. initTable () {
  120. const columns = []
  121. const data = []
  122. this.$header = this.$el.find('>thead')
  123. if (!this.$header.length) {
  124. this.$header = $(`<thead class="${this.options.theadClasses}"></thead>`).appendTo(this.$el)
  125. } else if (this.options.theadClasses) {
  126. this.$header.addClass(this.options.theadClasses)
  127. }
  128. this.$header.find('tr').each((i, el) => {
  129. const column = []
  130. $(el).find('th').each((i, el) => {
  131. // #2014: getFieldIndex and elsewhere assume this is string, causes issues if not
  132. if (typeof $(el).data('field') !== 'undefined') {
  133. $(el).data('field', `${$(el).data('field')}`)
  134. }
  135. column.push($.extend({}, {
  136. title: $(el).html(),
  137. 'class': $(el).attr('class'),
  138. titleTooltip: $(el).attr('title'),
  139. rowspan: $(el).attr('rowspan') ? +$(el).attr('rowspan') : undefined,
  140. colspan: $(el).attr('colspan') ? +$(el).attr('colspan') : undefined
  141. }, $(el).data()))
  142. })
  143. columns.push(column)
  144. })
  145. if (!Array.isArray(this.options.columns[0])) {
  146. this.options.columns = [this.options.columns]
  147. }
  148. this.options.columns = $.extend(true, [], columns, this.options.columns)
  149. this.columns = []
  150. this.fieldsColumnsIndex = []
  151. Utils.setFieldIndex(this.options.columns)
  152. this.options.columns.forEach((columns, i) => {
  153. columns.forEach((_column, j) => {
  154. const column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, _column)
  155. if (typeof column.fieldIndex !== 'undefined') {
  156. this.columns[column.fieldIndex] = column
  157. this.fieldsColumnsIndex[column.field] = column.fieldIndex
  158. }
  159. this.options.columns[i][j] = column
  160. })
  161. })
  162. // if options.data is setting, do not process tbody and tfoot data
  163. if (!this.options.data.length) {
  164. this.options.data = Utils.trToData(this.columns, this.$el.find('>tbody>tr'))
  165. if (data.length) {
  166. this.fromHtml = true
  167. }
  168. }
  169. this.footerData = Utils.trToData(this.columns, this.$el.find('>tfoot>tr'))
  170. if (this.footerData) {
  171. this.$el.find('tfoot').html('<tr></tr>')
  172. }
  173. if (!this.options.showFooter || this.options.cardView) {
  174. this.$tableFooter.hide()
  175. } else {
  176. this.$tableFooter.show()
  177. }
  178. }
  179. initHeader () {
  180. const visibleColumns = {}
  181. const html = []
  182. this.header = {
  183. fields: [],
  184. styles: [],
  185. classes: [],
  186. formatters: [],
  187. detailFormatters: [],
  188. events: [],
  189. sorters: [],
  190. sortNames: [],
  191. cellStyles: [],
  192. searchables: []
  193. }
  194. Utils.updateFieldGroup(this.options.columns)
  195. this.options.columns.forEach((columns, i) => {
  196. html.push('<tr>')
  197. if (i === 0 && !this.options.cardView && this.options.detailView && this.options.detailViewIcon) {
  198. html.push(`<th class="detail" rowspan="${this.options.columns.length}">
  199. <div class="fht-cell"></div>
  200. </th>
  201. `)
  202. }
  203. columns.forEach((column, j) => {
  204. const class_ = Utils.sprintf(' class="%s"', column['class'])
  205. const unitWidth = column.widthUnit
  206. const width = parseFloat(column.width)
  207. const halign = Utils.sprintf('text-align: %s; ', column.halign ? column.halign : column.align)
  208. const align = Utils.sprintf('text-align: %s; ', column.align)
  209. let style = Utils.sprintf('vertical-align: %s; ', column.valign)
  210. style += Utils.sprintf('width: %s; ', (column.checkbox || column.radio) && !width
  211. ? (!column.showSelectTitle ? '36px' : undefined)
  212. : (width ? width + unitWidth : undefined))
  213. if (typeof column.fieldIndex === 'undefined' && !column.visible) {
  214. return
  215. }
  216. if (typeof column.fieldIndex !== 'undefined') {
  217. this.header.fields[column.fieldIndex] = column.field
  218. this.header.styles[column.fieldIndex] = align + style
  219. this.header.classes[column.fieldIndex] = class_
  220. this.header.formatters[column.fieldIndex] = column.formatter
  221. this.header.detailFormatters[column.fieldIndex] = column.detailFormatter
  222. this.header.events[column.fieldIndex] = column.events
  223. this.header.sorters[column.fieldIndex] = column.sorter
  224. this.header.sortNames[column.fieldIndex] = column.sortName
  225. this.header.cellStyles[column.fieldIndex] = column.cellStyle
  226. this.header.searchables[column.fieldIndex] = column.searchable
  227. if (!column.visible) {
  228. return
  229. }
  230. if (this.options.cardView && (!column.cardVisible)) {
  231. return
  232. }
  233. visibleColumns[column.field] = column
  234. }
  235. html.push(`<th${Utils.sprintf(' title="%s"', column.titleTooltip)}`,
  236. column.checkbox || column.radio
  237. ? Utils.sprintf(' class="bs-checkbox %s"', column['class'] || '')
  238. : class_,
  239. Utils.sprintf(' style="%s"', halign + style),
  240. Utils.sprintf(' rowspan="%s"', column.rowspan),
  241. Utils.sprintf(' colspan="%s"', column.colspan),
  242. Utils.sprintf(' data-field="%s"', column.field),
  243. // If `column` is not the first element of `this.options.columns[0]`, then className 'data-not-first-th' should be added.
  244. j === 0 && i > 0 ? ' data-not-first-th' : '',
  245. '>')
  246. html.push(Utils.sprintf('<div class="th-inner %s">', this.options.sortable && column.sortable
  247. ? 'sortable both' : ''))
  248. let text = this.options.escape ? Utils.escapeHTML(column.title) : column.title
  249. const title = text
  250. if (column.checkbox) {
  251. text = ''
  252. if (!this.options.singleSelect && this.options.checkboxHeader) {
  253. text = '<label><input name="btSelectAll" type="checkbox" /><span></span></label>'
  254. }
  255. this.header.stateField = column.field
  256. }
  257. if (column.radio) {
  258. text = ''
  259. this.header.stateField = column.field
  260. this.options.singleSelect = true
  261. }
  262. if (!text && column.showSelectTitle) {
  263. text += title
  264. }
  265. html.push(text)
  266. html.push('</div>')
  267. html.push('<div class="fht-cell"></div>')
  268. html.push('</div>')
  269. html.push('</th>')
  270. })
  271. html.push('</tr>')
  272. })
  273. this.$header.html(html.join(''))
  274. this.$header.find('th[data-field]').each((i, el) => {
  275. $(el).data(visibleColumns[$(el).data('field')])
  276. })
  277. this.$container.off('click', '.th-inner').on('click', '.th-inner', e => {
  278. const $this = $(e.currentTarget)
  279. if (this.options.detailView && !$this.parent().hasClass('bs-checkbox')) {
  280. if ($this.closest('.bootstrap-table')[0] !== this.$container[0]) {
  281. return false
  282. }
  283. }
  284. if (this.options.sortable && $this.parent().data().sortable) {
  285. this.onSort(e)
  286. }
  287. })
  288. this.$header.children().children().off('keypress').on('keypress', e => {
  289. if (this.options.sortable && $(e.currentTarget).data().sortable) {
  290. const code = e.keyCode || e.which
  291. if (code === 13) { // Enter keycode
  292. this.onSort(e)
  293. }
  294. }
  295. })
  296. const resizeEvent = `resize.bootstrap-table${this.$el.attr('id') || ''}`
  297. $(window).off(resizeEvent)
  298. if (!this.options.showHeader || this.options.cardView) {
  299. this.$header.hide()
  300. this.$tableHeader.hide()
  301. this.$tableLoading.css('top', 0)
  302. } else {
  303. this.$header.show()
  304. this.$tableHeader.show()
  305. this.$tableLoading.css('top', this.$header.outerHeight() + 1)
  306. // Assign the correct sortable arrow
  307. this.getCaret()
  308. $(window).on(resizeEvent, e => this.resetWidth(e))
  309. }
  310. this.$selectAll = this.$header.find('[name="btSelectAll"]')
  311. this.$selectAll.off('click').on('click', ({currentTarget}) => {
  312. const checked = $(currentTarget).prop('checked')
  313. this[checked ? 'checkAll' : 'uncheckAll']()
  314. this.updateSelected()
  315. })
  316. }
  317. initData (data, type) {
  318. if (type === 'append') {
  319. this.options.data = this.options.data.concat(data)
  320. } else if (type === 'prepend') {
  321. this.options.data = [].concat(data).concat(this.options.data)
  322. } else {
  323. this.options.data = data || this.options.data
  324. }
  325. this.data = this.options.data
  326. if (this.options.sidePagination === 'server') {
  327. return
  328. }
  329. this.initSort()
  330. }
  331. initSort () {
  332. let name = this.options.sortName
  333. const order = this.options.sortOrder === 'desc' ? -1 : 1
  334. const index = this.header.fields.indexOf(this.options.sortName)
  335. let timeoutId = 0
  336. if (index !== -1) {
  337. if (this.options.sortStable) {
  338. this.data.forEach((row, i) => {
  339. if (!row.hasOwnProperty('_position')) {
  340. row._position = i
  341. }
  342. })
  343. }
  344. if (this.options.customSort) {
  345. Utils.calculateObjectValue(this.options, this.options.customSort, [
  346. this.options.sortName,
  347. this.options.sortOrder,
  348. this.data
  349. ])
  350. } else {
  351. this.data.sort((a, b) => {
  352. if (this.header.sortNames[index]) {
  353. name = this.header.sortNames[index]
  354. }
  355. const aa = Utils.getItemField(a, name, this.options.escape)
  356. const bb = Utils.getItemField(b, name, this.options.escape)
  357. const value = Utils.calculateObjectValue(this.header, this.header.sorters[index], [aa, bb, a, b])
  358. if (value !== undefined) {
  359. if (this.options.sortStable && value === 0) {
  360. return order * (a._position - b._position)
  361. }
  362. return order * value
  363. }
  364. return Utils.sort(aa, bb, order, this.options.sortStable)
  365. })
  366. }
  367. if (this.options.sortClass !== undefined) {
  368. clearTimeout(timeoutId)
  369. timeoutId = setTimeout(() => {
  370. this.$el.removeClass(this.options.sortClass)
  371. const index = this.$header.find(`[data-field="${this.options.sortName}"]`).index()
  372. this.$el.find(`tr td:nth-child(${index + 1})`).addClass(this.options.sortClass)
  373. }, 250)
  374. }
  375. }
  376. }
  377. onSort ({type, currentTarget}) {
  378. const $this = type === 'keypress' ? $(currentTarget) : $(currentTarget).parent()
  379. const $this_ = this.$header.find('th').eq($this.index())
  380. this.$header.add(this.$header_).find('span.order').remove()
  381. if (this.options.sortName === $this.data('field')) {
  382. this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc'
  383. } else {
  384. this.options.sortName = $this.data('field')
  385. if (this.options.rememberOrder) {
  386. this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc'
  387. } else {
  388. this.options.sortOrder = this.columns[this.fieldsColumnsIndex[$this.data('field')]].sortOrder ||
  389. this.columns[this.fieldsColumnsIndex[$this.data('field')]].order
  390. }
  391. }
  392. this.trigger('sort', this.options.sortName, this.options.sortOrder)
  393. $this.add($this_).data('order', this.options.sortOrder)
  394. // Assign the correct sortable arrow
  395. this.getCaret()
  396. if (this.options.sidePagination === 'server') {
  397. this.options.pageNumber = 1
  398. this.initServer(this.options.silentSort)
  399. return
  400. }
  401. this.initSort()
  402. this.initBody()
  403. }
  404. initToolbar () {
  405. const o = this.options
  406. let html = []
  407. let timeoutId = 0
  408. let $keepOpen
  409. let $search
  410. let switchableCount = 0
  411. if (this.$toolbar.find('.bs-bars').children().length) {
  412. $('body').append($(o.toolbar))
  413. }
  414. this.$toolbar.html('')
  415. if (typeof o.toolbar === 'string' || typeof o.toolbar === 'object') {
  416. $(Utils.sprintf('<div class="bs-bars %s-%s"></div>', this.constants.classes.pull, o.toolbarAlign))
  417. .appendTo(this.$toolbar)
  418. .append($(o.toolbar))
  419. }
  420. // showColumns, showToggle, showRefresh
  421. html = [`<div class="${[
  422. 'columns',
  423. `columns-${o.buttonsAlign}`,
  424. this.constants.classes.buttonsGroup,
  425. `${this.constants.classes.pull}-${o.buttonsAlign}`
  426. ].join(' ')}">`]
  427. if (typeof o.icons === 'string') {
  428. o.icons = Utils.calculateObjectValue(null, o.icons)
  429. }
  430. if (o.showPaginationSwitch) {
  431. html.push(`<button class="${this.constants.buttonsClass}" type="button" name="paginationSwitch"
  432. aria-label="Pagination Switch" title="${o.formatPaginationSwitch()}">
  433. ${o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.paginationSwitchDown) : ''}
  434. ${o.showButtonText ? o.formatPaginationSwitchUp() : ''}
  435. </button>`)
  436. }
  437. if (o.showRefresh) {
  438. html.push(`<button class="${this.constants.buttonsClass}" type="button" name="refresh"
  439. aria-label="Refresh" title="${o.formatRefresh()}">
  440. ${o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.refresh) : ''}
  441. ${o.showButtonText ? o.formatRefresh() : ''}
  442. </button>`)
  443. }
  444. if (o.showToggle) {
  445. html.push(`<button class="${this.constants.buttonsClass}" type="button" name="toggle"
  446. aria-label="Toggle" title="${o.formatToggle()}">
  447. ${o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.toggleOff) : '' }
  448. ${o.showButtonText ? o.formatToggleOn() : ''}
  449. </button>`)
  450. }
  451. if (o.showFullscreen) {
  452. html.push(`<button class="${this.constants.buttonsClass}" type="button" name="fullscreen"
  453. aria-label="Fullscreen" title="${o.formatFullscreen()}">
  454. ${o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.fullscreen) : '' }
  455. ${o.showButtonText ? o.formatFullscreen() : ''}
  456. </button>`)
  457. }
  458. if (o.showColumns) {
  459. html.push(`<div class="keep-open ${this.constants.classes.buttonsDropdown}" title="${o.formatColumns()}">
  460. <button class="${this.constants.buttonsClass} dropdown-toggle" type="button" data-toggle="dropdown"
  461. aria-label="Columns" title="${o.formatColumns()}">
  462. ${o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.columns) : '' }
  463. ${o.showButtonText ? o.formatColumns() : ''}
  464. ${this.constants.html.dropdownCaret}
  465. </button>
  466. ${this.constants.html.toolbarDropdown[0]}`)
  467. if (o.showColumnsToggleAll) {
  468. const allFieldsVisible = this.getVisibleColumns().length === this.columns.length
  469. html.push(
  470. Utils.sprintf(this.constants.html.toolbarDropdownItem,
  471. Utils.sprintf('<input type="checkbox" class="toggle-all" %s> <span>%s</span>', allFieldsVisible ? 'checked="checked"' : '', o.formatColumnsToggleAll())
  472. )
  473. )
  474. html.push(this.constants.html.toolbarDropdownSeperator)
  475. }
  476. this.columns.forEach((column, i) => {
  477. if (column.radio || column.checkbox) {
  478. return
  479. }
  480. if (o.cardView && !column.cardVisible) {
  481. return
  482. }
  483. const checked = column.visible ? ' checked="checked"' : ''
  484. if (column.switchable) {
  485. html.push(Utils.sprintf(this.constants.html.toolbarDropdownItem,
  486. Utils.sprintf('<input type="checkbox" data-field="%s" value="%s"%s> <span>%s</span>',
  487. column.field, i, checked, column.title)))
  488. switchableCount++
  489. }
  490. })
  491. html.push(this.constants.html.toolbarDropdown[1], '</div>')
  492. }
  493. html.push('</div>')
  494. // Fix #188: this.showToolbar is for extensions
  495. if (this.showToolbar || html.length > 2) {
  496. this.$toolbar.append(html.join(''))
  497. }
  498. if (o.showPaginationSwitch) {
  499. this.$toolbar.find('button[name="paginationSwitch"]')
  500. .off('click').on('click', () => this.togglePagination())
  501. }
  502. if (o.showFullscreen) {
  503. this.$toolbar.find('button[name="fullscreen"]')
  504. .off('click').on('click', () => this.toggleFullscreen())
  505. }
  506. if (o.showRefresh) {
  507. this.$toolbar.find('button[name="refresh"]')
  508. .off('click').on('click', () => this.refresh())
  509. }
  510. if (o.showToggle) {
  511. this.$toolbar.find('button[name="toggle"]')
  512. .off('click').on('click', () => {
  513. this.toggleView()
  514. })
  515. }
  516. if (o.showColumns) {
  517. $keepOpen = this.$toolbar.find('.keep-open')
  518. const $checkboxes = $keepOpen.find('input:not(".toggle-all")')
  519. const $toggleAll = $keepOpen.find('input.toggle-all')
  520. if (switchableCount <= o.minimumCountColumns) {
  521. $keepOpen.find('input').prop('disabled', true)
  522. }
  523. $keepOpen.find('li, label').off('click').on('click', e => {
  524. e.stopImmediatePropagation()
  525. })
  526. $checkboxes.off('click').on('click', ({currentTarget}) => {
  527. const $this = $(currentTarget)
  528. this._toggleColumn($this.val(), $this.prop('checked'), false)
  529. this.trigger('column-switch', $this.data('field'), $this.prop('checked'))
  530. $toggleAll.prop('checked', $checkboxes.filter(':checked').length === this.columns.length)
  531. })
  532. $toggleAll.off('click').on('click', ({currentTarget}) => {
  533. this._toggleAllColumns($(currentTarget).prop('checked'))
  534. })
  535. }
  536. // Fix #4516: this.showSearchClearButton is for extensions
  537. if (o.search || this.showSearchClearButton) {
  538. html = []
  539. const showSearchButton = Utils.sprintf(this.constants.html.searchButton,
  540. this.constants.buttonsClass,
  541. o.formatSearch(),
  542. o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.search) : '',
  543. o.showButtonText ? o.formatSearch() : ''
  544. )
  545. const showSearchClearButton = Utils.sprintf(this.constants.html.searchClearButton,
  546. this.constants.buttonsClass,
  547. o.formatClearSearch(),
  548. o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.clearSearch) : '',
  549. o.showButtonText ? o.formatClearSearch() : ''
  550. )
  551. const searchInputHtml = `<input class="${this.constants.classes.input}${Utils.sprintf(' input-%s', o.iconSize)} search-input" type="text" placeholder="${o.formatSearch()}">`
  552. let searchInputFinalHtml = searchInputHtml
  553. if (o.showSearchButton || o.showSearchClearButton) {
  554. const buttonsHtml = (o.showSearchButton ? showSearchButton : '') +
  555. (o.showSearchClearButton ? showSearchClearButton : '')
  556. searchInputFinalHtml = o.search ? Utils.sprintf(this.constants.html.inputGroup,
  557. searchInputHtml, buttonsHtml) : buttonsHtml
  558. }
  559. html.push(Utils.sprintf(`
  560. <div class="${this.constants.classes.pull}-${o.searchAlign} search ${this.constants.classes.inputGroup}">
  561. %s
  562. </div>
  563. `, searchInputFinalHtml))
  564. this.$toolbar.append(html.join(''))
  565. const $searchInput = this.$toolbar.find('.search input')
  566. const handleInputEvent = () => {
  567. const eventTriggers = Utils.isIEBrowser() ? 'mouseup' : 'keyup drop blur'
  568. $searchInput.off(eventTriggers).on(eventTriggers, event => {
  569. if (o.searchOnEnterKey && event.keyCode !== 13) {
  570. return
  571. }
  572. if ([37, 38, 39, 40].includes(event.keyCode)) {
  573. return
  574. }
  575. clearTimeout(timeoutId) // doesn't matter if it's 0
  576. timeoutId = setTimeout(() => {
  577. this.onSearch(event)
  578. }, o.searchTimeOut)
  579. })
  580. }
  581. if (o.showSearchButton) {
  582. this.$toolbar.find('.search button[name=search]').off('click').on('click', event => {
  583. clearTimeout(timeoutId) // doesn't matter if it's 0
  584. timeoutId = setTimeout(() => {
  585. this.onSearch({currentTarget: $searchInput})
  586. }, o.searchTimeOut)
  587. })
  588. if (o.searchOnEnterKey) {
  589. handleInputEvent()
  590. }
  591. } else {
  592. handleInputEvent()
  593. }
  594. if (o.showSearchClearButton) {
  595. this.$toolbar.find('.search button[name=clearSearch]').click(() => {
  596. this.resetSearch()
  597. })
  598. }
  599. }
  600. }
  601. onSearch ({currentTarget, firedByInitSearchText} = {}, overwriteSearchText = true) {
  602. if (currentTarget !== undefined && $(currentTarget).length && overwriteSearchText) {
  603. const text = $(currentTarget).val().trim()
  604. if (this.options.trimOnSearch && $(currentTarget).val() !== text) {
  605. $(currentTarget).val(text)
  606. }
  607. if (this.searchText === text) {
  608. return
  609. }
  610. if ($(currentTarget).hasClass('search-input')) {
  611. this.searchText = text
  612. this.options.searchText = text
  613. }
  614. }
  615. if (!firedByInitSearchText) {
  616. this.options.pageNumber = 1
  617. }
  618. this.initSearch()
  619. if (firedByInitSearchText) {
  620. if (this.options.sidePagination === 'client') {
  621. this.updatePagination()
  622. }
  623. } else {
  624. this.updatePagination()
  625. }
  626. this.trigger('search', this.searchText)
  627. }
  628. initSearch () {
  629. this.filterOptions = this.filterOptions || this.options.filterOptions
  630. if (this.options.sidePagination !== 'server') {
  631. if (this.options.customSearch) {
  632. this.data = Utils.calculateObjectValue(this.options, this.options.customSearch,
  633. [this.options.data, this.searchText, this.filterColumns])
  634. return
  635. }
  636. const s = this.searchText && (this.options.escape
  637. ? Utils.escapeHTML(this.searchText) : this.searchText).toLowerCase()
  638. const f = Utils.isEmptyObject(this.filterColumns) ? null : this.filterColumns
  639. // Check filter
  640. if (typeof this.filterOptions.filterAlgorithm === 'function') {
  641. this.data = this.options.data.filter((item, i) => this.filterOptions.filterAlgorithm.apply(null, [item, f]))
  642. } else if (typeof this.filterOptions.filterAlgorithm === 'string') {
  643. this.data = f ? this.options.data.filter((item, i) => {
  644. const filterAlgorithm = this.filterOptions.filterAlgorithm
  645. if (filterAlgorithm === 'and') {
  646. for (const key in f) {
  647. if (
  648. (Array.isArray(f[key]) &&
  649. !f[key].includes(item[key])) ||
  650. (!Array.isArray(f[key]) &&
  651. item[key] !== f[key])
  652. ) {
  653. return false
  654. }
  655. }
  656. } else if (filterAlgorithm === 'or') {
  657. let match = false
  658. for (const key in f) {
  659. if (
  660. (Array.isArray(f[key]) &&
  661. f[key].includes(item[key])) ||
  662. (!Array.isArray(f[key]) &&
  663. item[key] === f[key])
  664. ) {
  665. match = true
  666. }
  667. }
  668. return match
  669. }
  670. return true
  671. }) : this.options.data
  672. }
  673. const visibleFields = this.getVisibleFields()
  674. this.data = s ? this.data.filter((item, i) => {
  675. for (let j = 0; j < this.header.fields.length; j++) {
  676. if (!this.header.searchables[j] || (this.options.visibleSearch && visibleFields.indexOf(this.header.fields[j]) === -1)) {
  677. continue
  678. }
  679. const key = Utils.isNumeric(this.header.fields[j]) ? parseInt(this.header.fields[j], 10) : this.header.fields[j]
  680. const column = this.columns[this.fieldsColumnsIndex[key]]
  681. let value
  682. if (typeof key === 'string') {
  683. value = item
  684. const props = key.split('.')
  685. for (let i = 0; i < props.length; i++) {
  686. if (value[props[i]] !== null) {
  687. value = value[props[i]]
  688. }
  689. }
  690. } else {
  691. value = item[key]
  692. }
  693. // Fix #142: respect searchFormatter boolean
  694. if (column && column.searchFormatter) {
  695. value = Utils.calculateObjectValue(column,
  696. this.header.formatters[j], [value, item, i, column.field], value)
  697. }
  698. if (typeof value === 'string' || typeof value === 'number') {
  699. if (this.options.strictSearch) {
  700. if ((`${value}`).toLowerCase() === s) {
  701. return true
  702. }
  703. } else {
  704. const largerSmallerEqualsRegex = /(?:(<=|=>|=<|>=|>|<)(?:\s+)?(\d+)?|(\d+)?(\s+)?(<=|=>|=<|>=|>|<))/gm
  705. const matches = largerSmallerEqualsRegex.exec(s)
  706. let comparisonCheck = false
  707. if (matches) {
  708. const operator = matches[1] || `${matches[5]}l`
  709. const comparisonValue = matches[2] || matches[3]
  710. const int = parseInt(value, 10)
  711. const comparisonInt = parseInt(comparisonValue, 10)
  712. switch (operator) {
  713. case '>':
  714. case '<l':
  715. comparisonCheck = int > comparisonInt
  716. break
  717. case '<':
  718. case '>l':
  719. comparisonCheck = int < comparisonInt
  720. break
  721. case '<=':
  722. case '=<':
  723. case '>=l':
  724. case '=>l':
  725. comparisonCheck = int <= comparisonInt
  726. break
  727. case '>=':
  728. case '=>':
  729. case '<=l':
  730. case '=<l':
  731. comparisonCheck = int >= comparisonInt
  732. break
  733. default:
  734. break
  735. }
  736. }
  737. if (comparisonCheck || (`${value}`).toLowerCase().includes(s)) {
  738. return true
  739. }
  740. }
  741. }
  742. }
  743. return false
  744. }) : this.data
  745. }
  746. }
  747. initPagination () {
  748. const o = this.options
  749. if (!o.pagination) {
  750. this.$pagination.hide()
  751. return
  752. }
  753. this.$pagination.show()
  754. const html = []
  755. let $allSelected = false
  756. let i
  757. let from
  758. let to
  759. let $pageList
  760. let $pre
  761. let $next
  762. let $number
  763. const data = this.getData({includeHiddenRows: false})
  764. let pageList = o.pageList
  765. if (o.sidePagination !== 'server') {
  766. o.totalRows = data.length
  767. }
  768. this.totalPages = 0
  769. if (o.totalRows) {
  770. if (o.pageSize === o.formatAllRows()) {
  771. o.pageSize = o.totalRows
  772. $allSelected = true
  773. } else if (o.pageSize === o.totalRows) {
  774. // Fix #667 Table with pagination,
  775. // multiple pages and a search this matches to one page throws exception
  776. const pageLst = typeof o.pageList === 'string'
  777. ? o.pageList.replace('[', '').replace(']', '')
  778. .replace(/ /g, '').toLowerCase().split(',') : o.pageList
  779. if (pageLst.includes(o.formatAllRows().toLowerCase())) {
  780. $allSelected = true
  781. }
  782. }
  783. this.totalPages = ~~((o.totalRows - 1) / o.pageSize) + 1
  784. o.totalPages = this.totalPages
  785. }
  786. if (this.totalPages > 0 && o.pageNumber > this.totalPages) {
  787. o.pageNumber = this.totalPages
  788. }
  789. this.pageFrom = (o.pageNumber - 1) * o.pageSize + 1
  790. this.pageTo = o.pageNumber * o.pageSize
  791. if (this.pageTo > o.totalRows) {
  792. this.pageTo = o.totalRows
  793. }
  794. if (this.options.pagination && this.options.sidePagination !== 'server') {
  795. this.options.totalNotFiltered = this.options.data.length
  796. }
  797. if (!this.options.showExtendedPagination) {
  798. this.options.totalNotFiltered = undefined
  799. }
  800. const paginationInfo = o.onlyInfoPagination ?
  801. o.formatDetailPagination(o.totalRows) :
  802. o.formatShowingRows(this.pageFrom, this.pageTo, o.totalRows, o.totalNotFiltered)
  803. html.push(`<div class="${this.constants.classes.pull}-${o.paginationDetailHAlign} pagination-detail">
  804. <span class="pagination-info">
  805. ${paginationInfo}
  806. </span>`)
  807. if (!o.onlyInfoPagination) {
  808. html.push('<span class="page-list">')
  809. const pageNumber = [
  810. `<span class="${this.constants.classes.paginationDropdown}">
  811. <button class="${this.constants.buttonsClass} dropdown-toggle" type="button" data-toggle="dropdown">
  812. <span class="page-size">
  813. ${$allSelected ? o.formatAllRows() : o.pageSize}
  814. </span>
  815. ${this.constants.html.dropdownCaret}
  816. </button>
  817. ${this.constants.html.pageDropdown[0]}`]
  818. if (typeof o.pageList === 'string') {
  819. const list = o.pageList.replace('[', '').replace(']', '')
  820. .replace(/ /g, '').split(',')
  821. pageList = []
  822. for (const value of list) {
  823. pageList.push(
  824. (value.toLowerCase() === o.formatAllRows().toLowerCase() ||
  825. ['all', 'unlimited'].includes(value.toLowerCase()))
  826. ? o.formatAllRows() : +value)
  827. }
  828. }
  829. pageList.forEach((page, i) => {
  830. if (!o.smartDisplay || i === 0 || pageList[i - 1] < o.totalRows) {
  831. let active
  832. if ($allSelected) {
  833. active = page === o.formatAllRows() ? this.constants.classes.dropdownActive : ''
  834. } else {
  835. active = page === o.pageSize ? this.constants.classes.dropdownActive : ''
  836. }
  837. pageNumber.push(Utils.sprintf(this.constants.html.pageDropdownItem, active, page))
  838. }
  839. })
  840. pageNumber.push(`${this.constants.html.pageDropdown[1]}</span>`)
  841. html.push(o.formatRecordsPerPage(pageNumber.join('')))
  842. html.push('</span></div>')
  843. html.push(`<div class="${this.constants.classes.pull}-${o.paginationHAlign} pagination">`,
  844. Utils.sprintf(this.constants.html.pagination[0], Utils.sprintf(' pagination-%s', o.iconSize)),
  845. Utils.sprintf(this.constants.html.paginationItem, ' page-pre', o.formatSRPaginationPreText(), o.paginationPreText))
  846. if (this.totalPages < o.paginationSuccessivelySize) {
  847. from = 1
  848. to = this.totalPages
  849. } else {
  850. from = o.pageNumber - o.paginationPagesBySide
  851. to = from + (o.paginationPagesBySide * 2)
  852. }
  853. if (o.pageNumber < (o.paginationSuccessivelySize - 1)) {
  854. to = o.paginationSuccessivelySize
  855. }
  856. if (o.paginationSuccessivelySize > this.totalPages - from) {
  857. from = from - (o.paginationSuccessivelySize - (this.totalPages - from)) + 1
  858. }
  859. if (from < 1) {
  860. from = 1
  861. }
  862. if (to > this.totalPages) {
  863. to = this.totalPages
  864. }
  865. const middleSize = Math.round(o.paginationPagesBySide / 2)
  866. const pageItem = (i, classes = '') => Utils.sprintf(this.constants.html.paginationItem,
  867. classes + (i === o.pageNumber ? ` ${this.constants.classes.paginationActive}` : ''), o.formatSRPaginationPageText(i), i)
  868. if (from > 1) {
  869. let max = o.paginationPagesBySide
  870. if (max >= from) max = from - 1
  871. for (i = 1; i <= max; i++) {
  872. html.push(pageItem(i))
  873. }
  874. if ((from - 1) === max + 1) {
  875. i = from - 1
  876. html.push(pageItem(i))
  877. } else {
  878. if ((from - 1) > max) {
  879. if (
  880. (from - o.paginationPagesBySide * 2) > o.paginationPagesBySide &&
  881. o.paginationUseIntermediate
  882. ) {
  883. i = Math.round(((from - middleSize) / 2) + middleSize)
  884. html.push(pageItem(i, ' page-intermediate'))
  885. } else {
  886. html.push(Utils.sprintf(this.constants.html.paginationItem,
  887. ' page-first-separator disabled', '', '...'))
  888. }
  889. }
  890. }
  891. }
  892. for (i = from; i <= to; i++) {
  893. html.push(pageItem(i))
  894. }
  895. if (this.totalPages > to) {
  896. let min = this.totalPages - (o.paginationPagesBySide - 1)
  897. if (to >= min) min = to + 1
  898. if ((to + 1) === min - 1) {
  899. i = to + 1
  900. html.push(pageItem(i))
  901. } else {
  902. if (min > (to + 1)) {
  903. if (
  904. (this.totalPages - to) > o.paginationPagesBySide * 2 &&
  905. o.paginationUseIntermediate
  906. ) {
  907. i = Math.round(((this.totalPages - middleSize - to) / 2) + to)
  908. html.push(pageItem(i, ' page-intermediate'))
  909. } else {
  910. html.push(Utils.sprintf(this.constants.html.paginationItem,
  911. ' page-last-separator disabled', '', '...'))
  912. }
  913. }
  914. }
  915. for (i = min; i <= this.totalPages; i++) {
  916. html.push(pageItem(i))
  917. }
  918. }
  919. html.push(Utils.sprintf(this.constants.html.paginationItem, ' page-next', o.formatSRPaginationNextText(), o.paginationNextText))
  920. html.push(this.constants.html.pagination[1], '</div>')
  921. }
  922. this.$pagination.html(html.join(''))
  923. const dropupClass = ['bottom', 'both'].includes(o.paginationVAlign) ?
  924. ` ${this.constants.classes.dropup}` : ''
  925. this.$pagination.last().find('.page-list > span').addClass(dropupClass)
  926. if (!o.onlyInfoPagination) {
  927. $pageList = this.$pagination.find('.page-list a')
  928. $pre = this.$pagination.find('.page-pre')
  929. $next = this.$pagination.find('.page-next')
  930. $number = this.$pagination.find('.page-item').not('.page-next, .page-pre, .page-last-separator, .page-first-separator')
  931. if (this.totalPages <= 1) {
  932. this.$pagination.find('div.pagination').hide()
  933. }
  934. if (o.smartDisplay) {
  935. if (pageList.length < 2 || o.totalRows <= pageList[0]) {
  936. this.$pagination.find('span.page-list').hide()
  937. }
  938. }
  939. // when data is empty, hide the pagination
  940. this.$pagination[this.getData().length ? 'show' : 'hide']()
  941. if (!o.paginationLoop) {
  942. if (o.pageNumber === 1) {
  943. $pre.addClass('disabled')
  944. }
  945. if (o.pageNumber === this.totalPages) {
  946. $next.addClass('disabled')
  947. }
  948. }
  949. if ($allSelected) {
  950. o.pageSize = o.formatAllRows()
  951. }
  952. // removed the events for last and first, onPageNumber executeds the same logic
  953. $pageList.off('click').on('click', e => this.onPageListChange(e))
  954. $pre.off('click').on('click', e => this.onPagePre(e))
  955. $next.off('click').on('click', e => this.onPageNext(e))
  956. $number.off('click').on('click', e => this.onPageNumber(e))
  957. }
  958. }
  959. updatePagination (event) {
  960. // Fix #171: IE disabled button can be clicked bug.
  961. if (event && $(event.currentTarget).hasClass('disabled')) {
  962. return
  963. }
  964. if (!this.options.maintainMetaData) {
  965. this.resetRows()
  966. }
  967. this.initPagination()
  968. if (this.options.sidePagination === 'server') {
  969. this.initServer()
  970. } else {
  971. this.initBody()
  972. }
  973. this.trigger('page-change', this.options.pageNumber, this.options.pageSize)
  974. }
  975. onPageListChange (event) {
  976. event.preventDefault()
  977. const $this = $(event.currentTarget)
  978. $this.parent().addClass(this.constants.classes.dropdownActive)
  979. .siblings().removeClass(this.constants.classes.dropdownActive)
  980. this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase()
  981. ? this.options.formatAllRows() : +$this.text()
  982. this.$toolbar.find('.page-size').text(this.options.pageSize)
  983. this.updatePagination(event)
  984. return false
  985. }
  986. onPagePre (event) {
  987. event.preventDefault()
  988. if ((this.options.pageNumber - 1) === 0) {
  989. this.options.pageNumber = this.options.totalPages
  990. } else {
  991. this.options.pageNumber--
  992. }
  993. this.updatePagination(event)
  994. return false
  995. }
  996. onPageNext (event) {
  997. event.preventDefault()
  998. if ((this.options.pageNumber + 1) > this.options.totalPages) {
  999. this.options.pageNumber = 1
  1000. } else {
  1001. this.options.pageNumber++
  1002. }
  1003. this.updatePagination(event)
  1004. return false
  1005. }
  1006. onPageNumber (event) {
  1007. event.preventDefault()
  1008. if (this.options.pageNumber === +$(event.currentTarget).text()) {
  1009. return
  1010. }
  1011. this.options.pageNumber = +$(event.currentTarget).text()
  1012. this.updatePagination(event)
  1013. return false
  1014. }
  1015. initRow (item, i, data, trFragments) {
  1016. const html = []
  1017. let style = {}
  1018. const csses = []
  1019. let data_ = ''
  1020. let attributes = {}
  1021. const htmlAttributes = []
  1022. if (Utils.findIndex(this.hiddenRows, item) > -1) {
  1023. return
  1024. }
  1025. style = Utils.calculateObjectValue(this.options, this.options.rowStyle, [item, i], style)
  1026. if (style && style.css) {
  1027. for (const [key, value] of Object.entries(style.css)) {
  1028. csses.push(`${key}: ${value}`)
  1029. }
  1030. }
  1031. attributes = Utils.calculateObjectValue(this.options,
  1032. this.options.rowAttributes, [item, i], attributes)
  1033. if (attributes) {
  1034. for (const [key, value] of Object.entries(attributes)) {
  1035. htmlAttributes.push(`${key}="${Utils.escapeHTML(value)}"`)
  1036. }
  1037. }
  1038. if (item._data && !Utils.isEmptyObject(item._data)) {
  1039. for (const [k, v] of Object.entries(item._data)) {
  1040. // ignore data-index
  1041. if (k === 'index') {
  1042. return
  1043. }
  1044. data_ += ` data-${k}='${typeof v === 'object' ? JSON.stringify(v) : v}'`
  1045. }
  1046. }
  1047. html.push('<tr',
  1048. Utils.sprintf(' %s', htmlAttributes.length ? htmlAttributes.join(' ') : undefined),
  1049. Utils.sprintf(' id="%s"', Array.isArray(item) ? undefined : item._id),
  1050. Utils.sprintf(' class="%s"', style.classes || (Array.isArray(item) ? undefined : item._class)),
  1051. ` data-index="${i}"`,
  1052. Utils.sprintf(' data-uniqueid="%s"', Utils.getItemField(item, this.options.uniqueId, false)),
  1053. Utils.sprintf(' data-has-detail-view="%s"', (!this.options.cardView && this.options.detailView && Utils.calculateObjectValue(null, this.options.detailFilter, [i, item])) ? 'true' : undefined),
  1054. Utils.sprintf('%s', data_),
  1055. '>'
  1056. )
  1057. if (this.options.cardView) {
  1058. html.push(`<td colspan="${this.header.fields.length}"><div class="card-views">`)
  1059. }
  1060. if (!this.options.cardView && this.options.detailView && this.options.detailViewIcon) {
  1061. html.push('<td>')
  1062. if (Utils.calculateObjectValue(null, this.options.detailFilter, [i, item])) {
  1063. html.push(`
  1064. <a class="detail-icon" href="#">
  1065. ${Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailOpen)}
  1066. </a>
  1067. `)
  1068. }
  1069. html.push('</td>')
  1070. }
  1071. this.header.fields.forEach((field, j) => {
  1072. let text = ''
  1073. let value_ = Utils.getItemField(item, field, this.options.escape)
  1074. let value = ''
  1075. let type = ''
  1076. let cellStyle = {}
  1077. let id_ = ''
  1078. let class_ = this.header.classes[j]
  1079. let style_ = ''
  1080. let data_ = ''
  1081. let rowspan_ = ''
  1082. let colspan_ = ''
  1083. let title_ = ''
  1084. const column = this.columns[j]
  1085. if (this.fromHtml && typeof value_ === 'undefined') {
  1086. if ((!column.checkbox) && (!column.radio)) {
  1087. return
  1088. }
  1089. }
  1090. if (!column.visible) {
  1091. return
  1092. }
  1093. if (this.options.cardView && (!column.cardVisible)) {
  1094. return
  1095. }
  1096. if (column.escape) {
  1097. value_ = Utils.escapeHTML(value_)
  1098. }
  1099. if (csses.concat([this.header.styles[j]]).length) {
  1100. style_ = ` style="${csses.concat([this.header.styles[j]]).join('; ')}"`
  1101. }
  1102. // handle td's id and class
  1103. if (item[`_${field}_id`]) {
  1104. id_ = Utils.sprintf(' id="%s"', item[`_${field}_id`])
  1105. }
  1106. if (item[`_${field}_class`]) {
  1107. class_ = Utils.sprintf(' class="%s"', item[`_${field}_class`])
  1108. }
  1109. if (item[`_${field}_rowspan`]) {
  1110. rowspan_ = Utils.sprintf(' rowspan="%s"', item[`_${field}_rowspan`])
  1111. }
  1112. if (item[`_${field}_colspan`]) {
  1113. colspan_ = Utils.sprintf(' colspan="%s"', item[`_${field}_colspan`])
  1114. }
  1115. if (item[`_${field}_title`]) {
  1116. title_ = Utils.sprintf(' title="%s"', item[`_${field}_title`])
  1117. }
  1118. cellStyle = Utils.calculateObjectValue(this.header,
  1119. this.header.cellStyles[j], [value_, item, i, field], cellStyle)
  1120. if (cellStyle.classes) {
  1121. class_ = ` class="${cellStyle.classes}"`
  1122. }
  1123. if (cellStyle.css) {
  1124. const csses_ = []
  1125. for (const [key, value] of Object.entries(cellStyle.css)) {
  1126. csses_.push(`${key}: ${value}`)
  1127. }
  1128. style_ = ` style="${csses_.concat(this.header.styles[j]).join('; ')}"`
  1129. }
  1130. value = Utils.calculateObjectValue(column,
  1131. this.header.formatters[j], [value_, item, i, field], value_)
  1132. if (item[`_${field}_data`] && !Utils.isEmptyObject(item[`_${field}_data`])) {
  1133. for (const [k, v] of Object.entries(item[`_${field}_data`])) {
  1134. // ignore data-index
  1135. if (k === 'index') {
  1136. return
  1137. }
  1138. data_ += ` data-${k}="${v}"`
  1139. }
  1140. }
  1141. if (column.checkbox || column.radio) {
  1142. type = column.checkbox ? 'checkbox' : type
  1143. type = column.radio ? 'radio' : type
  1144. const c = column['class'] || ''
  1145. const isChecked = (value === true || value_ || (value && value.checked)) && value !== false
  1146. const isDisabled = !column.checkboxEnabled || (value && value.disabled)
  1147. text = [
  1148. this.options.cardView
  1149. ? `<div class="card-view ${c}">`
  1150. : `<td class="bs-checkbox ${c}"${class_}${style_}>`,
  1151. `<label>
  1152. <input
  1153. data-index="${i}"
  1154. name="${this.options.selectItemName}"
  1155. type="${type}"
  1156. ${Utils.sprintf('value="%s"', item[this.options.idField])}
  1157. ${Utils.sprintf('checked="%s"', isChecked ? 'checked' : undefined)}
  1158. ${Utils.sprintf('disabled="%s"', isDisabled ? 'disabled' : undefined)} />
  1159. <span></span>
  1160. </label>`,
  1161. this.header.formatters[j] && typeof value === 'string' ? value : '',
  1162. this.options.cardView ? '</div>' : '</td>'
  1163. ].join('')
  1164. item[this.header.stateField] = value === true || (!!value_ || (value && value.checked))
  1165. } else {
  1166. value = typeof value === 'undefined' || value === null
  1167. ? this.options.undefinedText : value
  1168. if (this.options.cardView) {
  1169. const cardTitle = this.options.showHeader
  1170. ? `<span class="card-view-title"${style_}>${Utils.getFieldTitle(this.columns, field)}</span>` : ''
  1171. text = `<div class="card-view">${cardTitle}<span class="card-view-value">${value}</span></div>`
  1172. if (this.options.smartDisplay && value === '') {
  1173. text = '<div class="card-view"></div>'
  1174. }
  1175. } else {
  1176. text = `<td${id_}${class_}${style_}${data_}${rowspan_}${colspan_}${title_}>${value}</td>`
  1177. }
  1178. }
  1179. html.push(text)
  1180. })
  1181. if (this.options.cardView) {
  1182. html.push('</div></td>')
  1183. }
  1184. html.push('</tr>')
  1185. return html.join('')
  1186. }
  1187. initBody (fixedScroll) {
  1188. const data = this.getData()
  1189. this.trigger('pre-body', data)
  1190. this.$body = this.$el.find('>tbody')
  1191. if (!this.$body.length) {
  1192. this.$body = $('<tbody></tbody>').appendTo(this.$el)
  1193. }
  1194. // Fix #389 Bootstrap-table-flatJSON is not working
  1195. if (!this.options.pagination || this.options.sidePagination === 'server') {
  1196. this.pageFrom = 1
  1197. this.pageTo = data.length
  1198. }
  1199. const rows = []
  1200. const trFragments = $(document.createDocumentFragment())
  1201. let hasTr = false
  1202. for (let i = this.pageFrom - 1; i < this.pageTo; i++) {
  1203. const item = data[i]
  1204. const tr = this.initRow(item, i, data, trFragments)
  1205. hasTr = hasTr || !!tr
  1206. if (tr && typeof tr === 'string') {
  1207. if (!this.options.virtualScroll) {
  1208. trFragments.append(tr)
  1209. } else {
  1210. rows.push(tr)
  1211. }
  1212. }
  1213. }
  1214. // show no records
  1215. if (!hasTr) {
  1216. this.$body.html(`<tr class="no-records-found">${Utils.sprintf('<td colspan="%s">%s</td>',
  1217. this.$header.find('th').length,
  1218. this.options.formatNoMatches())}</tr>`)
  1219. } else {
  1220. if (!this.options.virtualScroll) {
  1221. this.$body.html(trFragments)
  1222. } else {
  1223. if (this.virtualScroll) {
  1224. this.virtualScroll.destroy()
  1225. }
  1226. this.virtualScroll = new VirtualScroll({
  1227. rows,
  1228. scrollEl: this.$tableBody[0],
  1229. contentEl: this.$body[0],
  1230. itemHeight: this.options.virtualScrollItemHeight,
  1231. callback: () => {
  1232. this.fitHeader()
  1233. }
  1234. })
  1235. }
  1236. }
  1237. if (!fixedScroll) {
  1238. this.scrollTo(0)
  1239. }
  1240. // click to select by column
  1241. this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', e => {
  1242. const $td = $(e.currentTarget)
  1243. const $tr = $td.parent()
  1244. const $cardViewArr = $(e.target).parents('.card-views').children()
  1245. const $cardViewTarget = $(e.target).parents('.card-view')
  1246. const rowIndex = $tr.data('index')
  1247. const item = this.data[rowIndex]
  1248. const index = this.options.cardView ? $cardViewArr.index($cardViewTarget) : $td[0].cellIndex
  1249. const fields = this.getVisibleFields()
  1250. const field = fields[this.options.detailView && this.options.detailViewIcon && !this.options.cardView ? index - 1 : index]
  1251. const column = this.columns[this.fieldsColumnsIndex[field]]
  1252. const value = Utils.getItemField(item, field, this.options.escape)
  1253. if ($td.find('.detail-icon').length) {
  1254. return
  1255. }
  1256. this.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td)
  1257. this.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr, field)
  1258. // if click to select - then trigger the checkbox/radio click
  1259. if (
  1260. e.type === 'click' &&
  1261. this.options.clickToSelect &&
  1262. column.clickToSelect &&
  1263. !Utils.calculateObjectValue(this.options, this.options.ignoreClickToSelectOn, [e.target])
  1264. ) {
  1265. const $selectItem = $tr.find(Utils.sprintf('[name="%s"]', this.options.selectItemName))
  1266. if ($selectItem.length) {
  1267. $selectItem[0].click()
  1268. }
  1269. }
  1270. if (e.type === 'click' && this.options.detailViewByClick) {
  1271. this.toggleDetailView(rowIndex, this.header.detailFormatters[this.fieldsColumnsIndex[field]])
  1272. }
  1273. }).off('mousedown').on('mousedown', e => {
  1274. // https://github.com/jquery/jquery/issues/1741
  1275. this.multipleSelectRowCtrlKey = e.ctrlKey || e.metaKey
  1276. this.multipleSelectRowShiftKey = e.shiftKey
  1277. })
  1278. this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', e => {
  1279. e.preventDefault()
  1280. this.toggleDetailView($(e.currentTarget).parent().parent().data('index'))
  1281. return false
  1282. })
  1283. this.$selectItem = this.$body.find(Utils.sprintf('[name="%s"]', this.options.selectItemName))
  1284. this.$selectItem.off('click').on('click', e => {
  1285. e.stopImmediatePropagation()
  1286. const $this = $(e.currentTarget)
  1287. this._toggleCheck($this.prop('checked'), $this.data('index'))
  1288. })
  1289. this.header.events.forEach((_events, i) => {
  1290. let events = _events
  1291. if (!events) {
  1292. return
  1293. }
  1294. // fix bug, if events is defined with namespace
  1295. if (typeof events === 'string') {
  1296. events = Utils.calculateObjectValue(null, events)
  1297. }
  1298. const field = this.header.fields[i]
  1299. let fieldIndex = this.getVisibleFields().indexOf(field)
  1300. if (fieldIndex === -1) {
  1301. return
  1302. }
  1303. if (this.options.detailView && !this.options.cardView) {
  1304. fieldIndex += 1
  1305. }
  1306. for (const key in events) {
  1307. if (!events.hasOwnProperty(key)) {
  1308. continue
  1309. }
  1310. const event = events[key]
  1311. this.$body.find('>tr:not(.no-records-found)').each((i, tr) => {
  1312. const $tr = $(tr)
  1313. const $td = $tr.find(this.options.cardView ? '.card-views>.card-view' : '>td').eq(fieldIndex)
  1314. const index = key.indexOf(' ')
  1315. const name = key.substring(0, index)
  1316. const el = key.substring(index + 1)
  1317. $td.find(el).off(name).on(name, e => {
  1318. const index = $tr.data('index')
  1319. const row = this.data[index]
  1320. const value = row[field]
  1321. event.apply(this, [e, value, row, index])
  1322. })
  1323. })
  1324. }
  1325. })
  1326. this.updateSelected()
  1327. this.initFooter()
  1328. this.resetView()
  1329. if (this.options.sidePagination !== 'server') {
  1330. this.options.totalRows = data.length
  1331. }
  1332. this.trigger('post-body', data)
  1333. }
  1334. initServer (silent, query, url) {
  1335. let data = {}
  1336. const index = this.header.fields.indexOf(this.options.sortName)
  1337. let params = {
  1338. searchText: this.searchText,
  1339. sortName: this.options.sortName,
  1340. sortOrder: this.options.sortOrder
  1341. }
  1342. if (this.header.sortNames[index]) {
  1343. params.sortName = this.header.sortNames[index]
  1344. }
  1345. if (this.options.pagination && this.options.sidePagination === 'server') {
  1346. params.pageSize = this.options.pageSize === this.options.formatAllRows()
  1347. ? this.options.totalRows : this.options.pageSize
  1348. params.pageNumber = this.options.pageNumber
  1349. }
  1350. if (!(url || this.options.url) && !this.options.ajax) {
  1351. return
  1352. }
  1353. if (this.options.queryParamsType === 'limit') {
  1354. params = {
  1355. search: params.searchText,
  1356. sort: params.sortName,
  1357. order: params.sortOrder
  1358. }
  1359. if (this.options.pagination && this.options.sidePagination === 'server') {
  1360. params.offset = this.options.pageSize === this.options.formatAllRows()
  1361. ? 0 : this.options.pageSize * (this.options.pageNumber - 1)
  1362. params.limit = this.options.pageSize === this.options.formatAllRows()
  1363. ? this.options.totalRows : this.options.pageSize
  1364. if (params.limit === 0) {
  1365. delete params.limit
  1366. }
  1367. }
  1368. }
  1369. if (!(Utils.isEmptyObject(this.filterColumnsPartial))) {
  1370. params.filter = JSON.stringify(this.filterColumnsPartial, null)
  1371. }
  1372. $.extend(params, query || {})
  1373. data = Utils.calculateObjectValue(this.options, this.options.queryParams, [params], data)
  1374. // false to stop request
  1375. if (data === false) {
  1376. return
  1377. }
  1378. if (!silent) {
  1379. this.showLoading()
  1380. }
  1381. const request = $.extend({}, Utils.calculateObjectValue(null, this.options.ajaxOptions), {
  1382. type: this.options.method,
  1383. url: url || this.options.url,
  1384. data: this.options.contentType === 'application/json' && this.options.method === 'post'
  1385. ? JSON.stringify(data) : data,
  1386. cache: this.options.cache,
  1387. contentType: this.options.contentType,
  1388. dataType: this.options.dataType,
  1389. success: (_res, textStatus, jqXHR) => {
  1390. const res = Utils.calculateObjectValue(this.options,
  1391. this.options.responseHandler, [_res, jqXHR], _res)
  1392. this.load(res)
  1393. this.trigger('load-success', res, jqXHR.status, jqXHR)
  1394. if (!silent) {
  1395. this.hideLoading()
  1396. }
  1397. },
  1398. error: jqXHR => {
  1399. let data = []
  1400. if (this.options.sidePagination === 'server') {
  1401. data = {}
  1402. data[this.options.totalField] = 0
  1403. data[this.options.dataField] = []
  1404. }
  1405. this.load(data)
  1406. this.trigger('load-error', jqXHR.status, jqXHR)
  1407. if (!silent) this.$tableLoading.hide()
  1408. }
  1409. })
  1410. if (this.options.ajax) {
  1411. Utils.calculateObjectValue(this, this.options.ajax, [request], null)
  1412. } else {
  1413. if (this._xhr && this._xhr.readyState !== 4) {
  1414. this._xhr.abort()
  1415. }
  1416. this._xhr = $.ajax(request)
  1417. }
  1418. return data
  1419. }
  1420. initSearchText () {
  1421. if (this.options.search) {
  1422. this.searchText = ''
  1423. if (this.options.searchText !== '') {
  1424. const $search = this.$toolbar.find('.search input')
  1425. $search.val(this.options.searchText)
  1426. this.onSearch({currentTarget: $search, firedByInitSearchText: true})
  1427. }
  1428. }
  1429. }
  1430. getCaret () {
  1431. this.$header.find('th').each((i, th) => {
  1432. $(th).find('.sortable').removeClass('desc asc')
  1433. .addClass($(th).data('field') === this.options.sortName
  1434. ? this.options.sortOrder : 'both')
  1435. })
  1436. }
  1437. updateSelected () {
  1438. const checkAll = this.$selectItem.filter(':enabled').length &&
  1439. this.$selectItem.filter(':enabled').length ===
  1440. this.$selectItem.filter(':enabled').filter(':checked').length
  1441. this.$selectAll.add(this.$selectAll_).prop('checked', checkAll)
  1442. this.$selectItem.each((i, el) => {
  1443. $(el).closest('tr')[$(el).prop('checked') ? 'addClass' : 'removeClass']('selected')
  1444. })
  1445. }
  1446. updateRows () {
  1447. this.$selectItem.each((i, el) => {
  1448. this.data[$(el).data('index')][this.header.stateField] = $(el).prop('checked')
  1449. })
  1450. }
  1451. resetRows () {
  1452. for (const row of this.data) {
  1453. this.$selectAll.prop('checked', false)
  1454. this.$selectItem.prop('checked', false)
  1455. if (this.header.stateField) {
  1456. row[this.header.stateField] = false
  1457. }
  1458. }
  1459. this.initHiddenRows()
  1460. }
  1461. trigger (_name, ...args) {
  1462. const name = `${_name}.bs.table`
  1463. this.options[BootstrapTable.EVENTS[name]](...args)
  1464. this.$el.trigger($.Event(name), args)
  1465. this.options.onAll(name, args)
  1466. this.$el.trigger($.Event('all.bs.table'), [name, args])
  1467. }
  1468. resetHeader () {
  1469. // fix #61: the hidden table reset header bug.
  1470. // fix bug: get $el.css('width') error sometime (height = 500)
  1471. clearTimeout(this.timeoutId_)
  1472. this.timeoutId_ = setTimeout(() => this.fitHeader(), this.$el.is(':hidden') ? 100 : 0)
  1473. }
  1474. fitHeader () {
  1475. if (this.$el.is(':hidden')) {
  1476. this.timeoutId_ = setTimeout(() => this.fitHeader(), 100)
  1477. return
  1478. }
  1479. const fixedBody = this.$tableBody.get(0)
  1480. const scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
  1481. fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight()
  1482. ? Utils.getScrollBarWidth() : 0
  1483. this.$el.css('margin-top', -this.$header.outerHeight())
  1484. const focused = $(':focus')
  1485. if (focused.length > 0) {
  1486. const $th = focused.parents('th')
  1487. if ($th.length > 0) {
  1488. const dataField = $th.attr('data-field')
  1489. if (dataField !== undefined) {
  1490. const $headerTh = this.$header.find(`[data-field='${dataField}']`)
  1491. if ($headerTh.length > 0) {
  1492. $headerTh.find(':input').addClass('focus-temp')
  1493. }
  1494. }
  1495. }
  1496. }
  1497. this.$header_ = this.$header.clone(true, true)
  1498. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]')
  1499. this.$tableHeader
  1500. .css('margin-right', scrollWidth)
  1501. .find('table').css('width', this.$el.outerWidth())
  1502. .html('').attr('class', this.$el.attr('class'))
  1503. .append(this.$header_)
  1504. this.$tableLoading.css('width', this.$el.outerWidth())
  1505. const focusedTemp = $('.focus-temp:visible:eq(0)')
  1506. if (focusedTemp.length > 0) {
  1507. focusedTemp.focus()
  1508. this.$header.find('.focus-temp').removeClass('focus-temp')
  1509. }
  1510. // fix bug: $.data() is not working as expected after $.append()
  1511. this.$header.find('th[data-field]').each((i, el) => {
  1512. this.$header_.find(Utils.sprintf('th[data-field="%s"]', $(el).data('field'))).data($(el).data())
  1513. })
  1514. const visibleFields = this.getVisibleFields()
  1515. const $ths = this.$header_.find('th')
  1516. let $tr = this.$body.find('>tr:not(.no-records-found,.virtual-scroll-top)').eq(0)
  1517. while ($tr.length && $tr.find('>td[colspan]:not([colspan="1"])').length) {
  1518. $tr = $tr.next()
  1519. }
  1520. $tr.find('> *').each((i, el) => {
  1521. const $this = $(el)
  1522. let index = i
  1523. if (this.options.detailView && this.options.detailViewIcon && !this.options.cardView) {
  1524. if (i === 0) {
  1525. const $thDetail = $ths.filter('.detail')
  1526. const zoomWidth = $thDetail.innerWidth() - $thDetail.find('.fht-cell').width()
  1527. $thDetail.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1528. }
  1529. index = i - 1
  1530. }
  1531. if (index === -1) {
  1532. return
  1533. }
  1534. let $th = this.$header_.find(Utils.sprintf('th[data-field="%s"]', visibleFields[index]))
  1535. if ($th.length > 1) {
  1536. $th = $($ths[$this[0].cellIndex])
  1537. }
  1538. const zoomWidth = $th.innerWidth() - $th.find('.fht-cell').width()
  1539. $th.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1540. })
  1541. this.horizontalScroll()
  1542. this.trigger('post-header')
  1543. }
  1544. initFooter () {
  1545. if (!this.options.showFooter || this.options.cardView) { // do nothing
  1546. return
  1547. }
  1548. const data = this.getData()
  1549. const html = []
  1550. if (!this.options.cardView && this.options.detailView && this.options.detailViewIcon) {
  1551. html.push('<th class="detail"><div class="th-inner"></div><div class="fht-cell"></div></th>')
  1552. }
  1553. for (const column of this.columns) {
  1554. let falign = ''
  1555. let valign = ''
  1556. const csses = []
  1557. let style = {}
  1558. let class_ = Utils.sprintf(' class="%s"', column['class'])
  1559. if (!column.visible) {
  1560. continue
  1561. }
  1562. if (this.options.cardView && (!column.cardVisible)) {
  1563. return
  1564. }
  1565. falign = Utils.sprintf('text-align: %s; ', column.falign ? column.falign : column.align)
  1566. valign = Utils.sprintf('vertical-align: %s; ', column.valign)
  1567. style = Utils.calculateObjectValue(null, this.options.footerStyle, [column])
  1568. if (style && style.css) {
  1569. for (const [key, value] of Object.entries(style.css)) {
  1570. csses.push(`${key}: ${value}`)
  1571. }
  1572. }
  1573. if (style && style.classes) {
  1574. class_ = Utils.sprintf(' class="%s"', column['class'] ?
  1575. [column['class'], style.classes].join(' ') : style.classes)
  1576. }
  1577. html.push('<th', class_, Utils.sprintf(' style="%s"', falign + valign + csses.concat().join('; ')), '>')
  1578. html.push('<div class="th-inner">')
  1579. html.push(Utils.calculateObjectValue(column, column.footerFormatter,
  1580. [data], this.footerData[0] && this.footerData[0][column.field] || ''))
  1581. html.push('</div>')
  1582. html.push('<div class="fht-cell"></div>')
  1583. html.push('</div>')
  1584. html.push('</th>')
  1585. }
  1586. this.$tableFooter.find('tr').html(html.join(''))
  1587. this.trigger('post-footer', this.$tableFooter)
  1588. }
  1589. fitFooter () {
  1590. if (this.$el.is(':hidden')) {
  1591. setTimeout(() => this.fitFooter(), 100)
  1592. return
  1593. }
  1594. const fixedBody = this.$tableBody.get(0)
  1595. const scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
  1596. fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight()
  1597. ? Utils.getScrollBarWidth() : 0
  1598. this.$tableFooter
  1599. .css('margin-right', scrollWidth)
  1600. .find('table').css('width', this.$el.outerWidth())
  1601. .attr('class', this.$el.attr('class'))
  1602. const visibleFields = this.getVisibleFields()
  1603. const $ths = this.$tableFooter.find('th')
  1604. let $tr = this.$body.find('>tr:first-child:not(.no-records-found)')
  1605. while ($tr.length && $tr.find('>td[colspan]:not([colspan="1"])').length) {
  1606. $tr = $tr.next()
  1607. }
  1608. $tr.find('> *').each((i, el) => {
  1609. const $this = $(el)
  1610. let index = i
  1611. if (this.options.detailView && !this.options.cardView) {
  1612. if (i === 0) {
  1613. const $thDetail = $ths.filter('.detail')
  1614. const zoomWidth = $thDetail.innerWidth() - $thDetail.find('.fht-cell').width()
  1615. $thDetail.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1616. }
  1617. index = i - 1
  1618. }
  1619. if (index === -1) {
  1620. return
  1621. }
  1622. const $th = $ths.eq(i)
  1623. const zoomWidth = $th.innerWidth() - $th.find('.fht-cell').width()
  1624. $th.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1625. })
  1626. this.horizontalScroll()
  1627. }
  1628. horizontalScroll () {
  1629. // horizontal scroll event
  1630. // TODO: it's probably better improving the layout than binding to scroll event
  1631. this.trigger('scroll-body')
  1632. this.$tableBody.off('scroll').on('scroll', ({currentTarget}) => {
  1633. if (this.options.showHeader && this.options.height) {
  1634. this.$tableHeader.scrollLeft($(currentTarget).scrollLeft())
  1635. }
  1636. if (this.options.showFooter && !this.options.cardView) {
  1637. this.$tableFooter.scrollLeft($(currentTarget).scrollLeft())
  1638. }
  1639. })
  1640. }
  1641. getVisibleFields () {
  1642. const visibleFields = []
  1643. for (const field of this.header.fields) {
  1644. const column = this.columns[this.fieldsColumnsIndex[field]]
  1645. if (!column || !column.visible) {
  1646. continue
  1647. }
  1648. visibleFields.push(field)
  1649. }
  1650. return visibleFields
  1651. }
  1652. initHiddenRows () {
  1653. this.hiddenRows = []
  1654. }
  1655. // PUBLIC FUNCTION DEFINITION
  1656. // =======================
  1657. getOptions () {
  1658. // deep copy and remove data
  1659. const options = $.extend({}, this.options)
  1660. delete options.data
  1661. return $.extend(true, {}, options)
  1662. }
  1663. refreshOptions (options) {
  1664. // If the objects are equivalent then avoid the call of destroy / init methods
  1665. if (Utils.compareObjects(this.options, options, true)) {
  1666. return
  1667. }
  1668. this.options = $.extend(this.options, options)
  1669. this.trigger('refresh-options', this.options)
  1670. this.destroy()
  1671. this.init()
  1672. }
  1673. getData (params) {
  1674. let data = this.options.data
  1675. if (this.searchText || this.options.sortName || !Utils.isEmptyObject(this.filterColumns) || !Utils.isEmptyObject(this.filterColumnsPartial)) {
  1676. data = this.data
  1677. }
  1678. if (params && params.useCurrentPage) {
  1679. data = data.slice(this.pageFrom - 1, this.pageTo)
  1680. }
  1681. if (params && !params.includeHiddenRows) {
  1682. const hiddenRows = this.getHiddenRows()
  1683. data = data.filter(function (row) {
  1684. return Utils.findIndex(hiddenRows, row) === -1
  1685. })
  1686. }
  1687. return data
  1688. }
  1689. getSelections () {
  1690. // fix #2424: from html with checkbox
  1691. return this.data.filter(row => row[this.header.stateField] === true)
  1692. }
  1693. getAllSelections () {
  1694. return this.options.data.filter(row => row[this.header.stateField] === true)
  1695. }
  1696. load (_data) {
  1697. let fixedScroll = false
  1698. let data = _data
  1699. // #431: support pagination
  1700. if (this.options.pagination && this.options.sidePagination === 'server') {
  1701. this.options.totalRows = data[this.options.totalField]
  1702. }
  1703. if (this.options.pagination && this.options.sidePagination === 'server') {
  1704. this.options.totalNotFiltered = data[this.options.totalNotFilteredField]
  1705. }
  1706. fixedScroll = data.fixedScroll
  1707. data = Array.isArray(data) ? data : data[this.options.dataField]
  1708. this.initData(data)
  1709. this.initSearch()
  1710. this.initPagination()
  1711. this.initBody(fixedScroll)
  1712. }
  1713. append (data) {
  1714. this.initData(data, 'append')
  1715. this.initSearch()
  1716. this.initPagination()
  1717. this.initSort()
  1718. this.initBody(true)
  1719. }
  1720. prepend (data) {
  1721. this.initData(data, 'prepend')
  1722. this.initSearch()
  1723. this.initPagination()
  1724. this.initSort()
  1725. this.initBody(true)
  1726. }
  1727. remove (params) {
  1728. const len = this.options.data.length
  1729. let i
  1730. let row
  1731. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
  1732. return
  1733. }
  1734. for (i = len - 1; i >= 0; i--) {
  1735. row = this.options.data[i]
  1736. if (!row.hasOwnProperty(params.field)) {
  1737. continue
  1738. }
  1739. if (params.values.includes(row[params.field])) {
  1740. this.options.data.splice(i, 1)
  1741. if (this.options.sidePagination === 'server') {
  1742. this.options.totalRows -= 1
  1743. }
  1744. }
  1745. }
  1746. if (len === this.options.data.length) {
  1747. return
  1748. }
  1749. this.initSearch()
  1750. this.initPagination()
  1751. this.initSort()
  1752. this.initBody(true)
  1753. }
  1754. removeAll () {
  1755. if (this.options.data.length > 0) {
  1756. this.options.data.splice(0, this.options.data.length)
  1757. this.initSearch()
  1758. this.initPagination()
  1759. this.initBody(true)
  1760. }
  1761. }
  1762. insertRow (params) {
  1763. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1764. return
  1765. }
  1766. this.options.data.splice(params.index, 0, params.row)
  1767. this.initSearch()
  1768. this.initPagination()
  1769. this.initSort()
  1770. this.initBody(true)
  1771. }
  1772. updateRow (params) {
  1773. const allParams = Array.isArray(params) ? params : [params]
  1774. for (const params of allParams) {
  1775. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1776. continue
  1777. }
  1778. $.extend(this.options.data[params.index], params.row)
  1779. if (params.hasOwnProperty('replace') && params.replace) {
  1780. this.options.data[params.index] = params.row
  1781. } else {
  1782. $.extend(this.options.data[params.index], params.row)
  1783. }
  1784. }
  1785. this.initSearch()
  1786. this.initPagination()
  1787. this.initSort()
  1788. this.initBody(true)
  1789. }
  1790. getRowByUniqueId (_id) {
  1791. const uniqueId = this.options.uniqueId
  1792. const len = this.options.data.length
  1793. let id = _id
  1794. let dataRow = null
  1795. let i
  1796. let row
  1797. let rowUniqueId
  1798. for (i = len - 1; i >= 0; i--) {
  1799. row = this.options.data[i]
  1800. if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column
  1801. rowUniqueId = row[uniqueId]
  1802. } else if (row._data && row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property
  1803. rowUniqueId = row._data[uniqueId]
  1804. } else {
  1805. continue
  1806. }
  1807. if (typeof rowUniqueId === 'string') {
  1808. id = id.toString()
  1809. } else if (typeof rowUniqueId === 'number') {
  1810. if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) {
  1811. id = parseInt(id)
  1812. } else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) {
  1813. id = parseFloat(id)
  1814. }
  1815. }
  1816. if (rowUniqueId === id) {
  1817. dataRow = row
  1818. break
  1819. }
  1820. }
  1821. return dataRow
  1822. }
  1823. updateByUniqueId (params) {
  1824. const allParams = Array.isArray(params) ? params : [params]
  1825. for (const params of allParams) {
  1826. if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
  1827. continue
  1828. }
  1829. const rowId = this.options.data.indexOf(this.getRowByUniqueId(params.id))
  1830. if (rowId === -1) {
  1831. continue
  1832. }
  1833. if (params.hasOwnProperty('replace') && params.replace) {
  1834. this.options.data[rowId] = params.row
  1835. } else {
  1836. $.extend(this.options.data[rowId], params.row)
  1837. }
  1838. }
  1839. this.initSearch()
  1840. this.initPagination()
  1841. this.initSort()
  1842. this.initBody(true)
  1843. }
  1844. removeByUniqueId (id) {
  1845. const len = this.options.data.length
  1846. const row = this.getRowByUniqueId(id)
  1847. if (row) {
  1848. this.options.data.splice(this.options.data.indexOf(row), 1)
  1849. }
  1850. if (len === this.options.data.length) {
  1851. return
  1852. }
  1853. this.initSearch()
  1854. this.initPagination()
  1855. this.initBody(true)
  1856. }
  1857. updateCell (params) {
  1858. if (!params.hasOwnProperty('index') ||
  1859. !params.hasOwnProperty('field') ||
  1860. !params.hasOwnProperty('value')) {
  1861. return
  1862. }
  1863. this.data[params.index][params.field] = params.value
  1864. if (params.reinit === false) {
  1865. return
  1866. }
  1867. this.initSort()
  1868. this.initBody(true)
  1869. }
  1870. updateCellByUniqueId (params) {
  1871. if (!params.hasOwnProperty('id') ||
  1872. !params.hasOwnProperty('field') ||
  1873. !params.hasOwnProperty('value')) {
  1874. return
  1875. }
  1876. const allParams = Array.isArray(params) ? params : [params]
  1877. allParams.forEach(({id, field, value}) => {
  1878. const rowId = this.options.data.indexOf(this.getRowByUniqueId(id))
  1879. if (rowId === -1) {
  1880. return
  1881. }
  1882. this.options.data[rowId][field] = value
  1883. })
  1884. if (params.reinit === false) {
  1885. return
  1886. }
  1887. this.initSort()
  1888. this.initBody(true)
  1889. }
  1890. showRow (params) {
  1891. this._toggleRow(params, true)
  1892. }
  1893. hideRow (params) {
  1894. this._toggleRow(params, false)
  1895. }
  1896. _toggleRow (params, visible) {
  1897. let row
  1898. if (params.hasOwnProperty('index')) {
  1899. row = this.getData()[params.index]
  1900. } else if (params.hasOwnProperty('uniqueId')) {
  1901. row = this.getRowByUniqueId(params.uniqueId)
  1902. }
  1903. if (!row) {
  1904. return
  1905. }
  1906. const index = Utils.findIndex(this.hiddenRows, row)
  1907. if (!visible && index === -1) {
  1908. this.hiddenRows.push(row)
  1909. } else if (visible && index > -1) {
  1910. this.hiddenRows.splice(index, 1)
  1911. }
  1912. if (visible) {
  1913. this.updatePagination()
  1914. } else {
  1915. this.initBody(true)
  1916. this.initPagination()
  1917. }
  1918. }
  1919. getHiddenRows (show) {
  1920. if (show) {
  1921. this.initHiddenRows()
  1922. this.initBody(true)
  1923. return
  1924. }
  1925. const data = this.getData()
  1926. const rows = []
  1927. for (const row of data) {
  1928. if (this.hiddenRows.includes(row)) {
  1929. rows.push(row)
  1930. }
  1931. }
  1932. this.hiddenRows = rows
  1933. return rows
  1934. }
  1935. showColumn (field) {
  1936. const fields = Array.isArray(field) ? field : [field]
  1937. fields.forEach(field => {
  1938. this._toggleColumn(this.fieldsColumnsIndex[field], true, true)
  1939. })
  1940. }
  1941. hideColumn (field) {
  1942. const fields = Array.isArray(field) ? field : [field]
  1943. fields.forEach(field => {
  1944. this._toggleColumn(this.fieldsColumnsIndex[field], false, true)
  1945. })
  1946. }
  1947. _toggleColumn (index, checked, needUpdate) {
  1948. if (index === -1 || this.columns[index].visible === checked) {
  1949. return
  1950. }
  1951. this.columns[index].visible = checked
  1952. this.initHeader()
  1953. this.initSearch()
  1954. this.initPagination()
  1955. this.initBody()
  1956. if (this.options.showColumns) {
  1957. const $items = this.$toolbar.find('.keep-open input').prop('disabled', false)
  1958. if (needUpdate) {
  1959. $items.filter(Utils.sprintf('[value="%s"]', index)).prop('checked', checked)
  1960. }
  1961. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  1962. $items.filter(':checked').prop('disabled', true)
  1963. }
  1964. }
  1965. }
  1966. getVisibleColumns () {
  1967. return this.columns.filter(({visible}) => visible)
  1968. }
  1969. getHiddenColumns () {
  1970. return this.columns.filter(({visible}) => !visible)
  1971. }
  1972. showAllColumns () {
  1973. this._toggleAllColumns(true)
  1974. }
  1975. hideAllColumns () {
  1976. this._toggleAllColumns(false)
  1977. }
  1978. _toggleAllColumns (visible) {
  1979. for (const column of this.columns.slice().reverse()) {
  1980. if (column.switchable) {
  1981. if (!visible && this.options.showColumns && this.getVisibleColumns().length === this.options.minimumCountColumns) {
  1982. continue
  1983. }
  1984. column.visible = visible
  1985. }
  1986. }
  1987. this.initHeader()
  1988. this.initSearch()
  1989. this.initPagination()
  1990. this.initBody()
  1991. if (this.options.showColumns) {
  1992. const $items = this.$toolbar.find('.keep-open input:not(".toggle-all")').prop('disabled', false)
  1993. if (visible) {
  1994. $items.prop('checked', visible)
  1995. } else {
  1996. $items.get().reverse().forEach((item) => {
  1997. if ($items.filter(':checked').length > this.options.minimumCountColumns) {
  1998. $(item).prop('checked', visible)
  1999. }
  2000. })
  2001. }
  2002. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  2003. $items.filter(':checked').prop('disabled', true)
  2004. }
  2005. }
  2006. }
  2007. mergeCells (options) {
  2008. const row = options.index
  2009. let col = this.getVisibleFields().indexOf(options.field)
  2010. const rowspan = options.rowspan || 1
  2011. const colspan = options.colspan || 1
  2012. let i
  2013. let j
  2014. const $tr = this.$body.find('>tr')
  2015. if (this.options.detailView && !this.options.cardView) {
  2016. col += 1
  2017. }
  2018. const $td = $tr.eq(row).find('>td').eq(col)
  2019. if (row < 0 || col < 0 || row >= this.data.length) {
  2020. return
  2021. }
  2022. for (i = row; i < row + rowspan; i++) {
  2023. for (j = col; j < col + colspan; j++) {
  2024. $tr.eq(i).find('>td').eq(j).hide()
  2025. }
  2026. }
  2027. $td.attr('rowspan', rowspan).attr('colspan', colspan).show()
  2028. }
  2029. checkAll () {
  2030. this._toggleCheckAll(true)
  2031. }
  2032. uncheckAll () {
  2033. this._toggleCheckAll(false)
  2034. }
  2035. _toggleCheckAll (checked) {
  2036. const rowsBefore = this.getSelections()
  2037. this.$selectAll.add(this.$selectAll_).prop('checked', checked)
  2038. this.$selectItem.filter(':enabled').prop('checked', checked)
  2039. this.updateRows()
  2040. const rowsAfter = this.getSelections()
  2041. if (checked) {
  2042. this.trigger('check-all', rowsAfter, rowsBefore)
  2043. return
  2044. }
  2045. this.trigger('uncheck-all', rowsAfter, rowsBefore)
  2046. }
  2047. checkInvert () {
  2048. const $items = this.$selectItem.filter(':enabled')
  2049. let checked = $items.filter(':checked')
  2050. $items.each((i, el) => {
  2051. $(el).prop('checked', !$(el).prop('checked'))
  2052. })
  2053. this.updateRows()
  2054. this.updateSelected()
  2055. this.trigger('uncheck-some', checked)
  2056. checked = this.getSelections()
  2057. this.trigger('check-some', checked)
  2058. }
  2059. check (index) {
  2060. this._toggleCheck(true, index)
  2061. }
  2062. uncheck (index) {
  2063. this._toggleCheck(false, index)
  2064. }
  2065. _toggleCheck (checked, index) {
  2066. const $el = this.$selectItem.filter(`[data-index="${index}"]`)
  2067. const row = this.data[index]
  2068. if (
  2069. $el.is(':radio') ||
  2070. this.options.singleSelect ||
  2071. this.options.multipleSelectRow &&
  2072. !this.multipleSelectRowCtrlKey &&
  2073. !this.multipleSelectRowShiftKey
  2074. ) {
  2075. for (const r of this.options.data) {
  2076. r[this.header.stateField] = false
  2077. }
  2078. this.$selectItem.filter(':checked').not($el).prop('checked', false)
  2079. }
  2080. row[this.header.stateField] = checked
  2081. if (this.options.multipleSelectRow) {
  2082. if (this.multipleSelectRowShiftKey && this.multipleSelectRowLastSelectedIndex >= 0) {
  2083. const indexes = [this.multipleSelectRowLastSelectedIndex, index].sort()
  2084. for (let i = indexes[0] + 1; i < indexes[1]; i++) {
  2085. this.data[i][this.header.stateField] = true
  2086. this.$selectItem.filter(`[data-index="${i}"]`).prop('checked', true)
  2087. }
  2088. }
  2089. this.multipleSelectRowCtrlKey = false
  2090. this.multipleSelectRowShiftKey = false
  2091. this.multipleSelectRowLastSelectedIndex = checked ? index : -1
  2092. }
  2093. $el.prop('checked', checked)
  2094. this.updateSelected()
  2095. this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el)
  2096. }
  2097. checkBy (obj) {
  2098. this._toggleCheckBy(true, obj)
  2099. }
  2100. uncheckBy (obj) {
  2101. this._toggleCheckBy(false, obj)
  2102. }
  2103. _toggleCheckBy (checked, obj) {
  2104. if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
  2105. return
  2106. }
  2107. const rows = []
  2108. this.data.forEach((row, i) => {
  2109. if (!row.hasOwnProperty(obj.field)) {
  2110. return false
  2111. }
  2112. if (obj.values.includes(row[obj.field])) {
  2113. let $el = this.$selectItem.filter(':enabled')
  2114. .filter(Utils.sprintf('[data-index="%s"]', i))
  2115. $el = checked ? $el.not(':checked') : $el.filter(':checked')
  2116. if (!$el.length) {
  2117. return
  2118. }
  2119. $el.prop('checked', checked)
  2120. row[this.header.stateField] = checked
  2121. rows.push(row)
  2122. this.trigger(checked ? 'check' : 'uncheck', row, $el)
  2123. }
  2124. })
  2125. this.updateSelected()
  2126. this.trigger(checked ? 'check-some' : 'uncheck-some', rows)
  2127. }
  2128. refresh (params) {
  2129. if (params && params.url) {
  2130. this.options.url = params.url
  2131. }
  2132. if (params && params.pageNumber) {
  2133. this.options.pageNumber = params.pageNumber
  2134. }
  2135. if (params && params.pageSize) {
  2136. this.options.pageSize = params.pageSize
  2137. }
  2138. this.trigger('refresh', this.initServer(params && params.silent,
  2139. params && params.query, params && params.url))
  2140. }
  2141. destroy () {
  2142. this.$el.insertBefore(this.$container)
  2143. $(this.options.toolbar).insertBefore(this.$el)
  2144. this.$container.next().remove()
  2145. this.$container.remove()
  2146. this.$el.html(this.$el_.html())
  2147. .css('margin-top', '0')
  2148. .attr('class', this.$el_.attr('class') || '') // reset the class
  2149. }
  2150. resetView (params) {
  2151. let padding = 0
  2152. if (params && params.height) {
  2153. this.options.height = params.height
  2154. }
  2155. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  2156. this.$selectItem.length === this.$selectItem.filter(':checked').length)
  2157. this.$tableContainer.toggleClass('has-card-view', this.options.cardView)
  2158. if (!this.options.cardView && this.options.showHeader && this.options.height) {
  2159. this.$tableHeader.show()
  2160. this.resetHeader()
  2161. padding += this.$header.outerHeight(true)
  2162. } else {
  2163. this.$tableHeader.hide()
  2164. this.trigger('post-header')
  2165. }
  2166. if (!this.options.cardView && this.options.showFooter) {
  2167. this.$tableFooter.show()
  2168. this.fitFooter()
  2169. if (this.options.height) {
  2170. padding += this.$tableFooter.outerHeight(true)
  2171. }
  2172. }
  2173. if (this.options.height) {
  2174. const toolbarHeight = this.$toolbar.outerHeight(true)
  2175. const paginationHeight = this.$pagination.outerHeight(true)
  2176. const height = this.options.height - toolbarHeight - paginationHeight
  2177. const tableHeight = this.$tableBody.find('table').outerHeight(true)
  2178. this.$tableContainer.css('height', `${height}px`)
  2179. this.$tableBorder && this.$tableBorder.css('height', `${height - tableHeight - padding - 1}px`)
  2180. }
  2181. if (this.options.cardView) {
  2182. // remove the element css
  2183. this.$el.css('margin-top', '0')
  2184. this.$tableContainer.css('padding-bottom', '0')
  2185. this.$tableFooter.hide()
  2186. } else {
  2187. // Assign the correct sortable arrow
  2188. this.getCaret()
  2189. this.$tableContainer.css('padding-bottom', `${padding}px`)
  2190. }
  2191. this.trigger('reset-view')
  2192. }
  2193. resetWidth () {
  2194. if (this.options.showHeader && this.options.height) {
  2195. this.fitHeader()
  2196. }
  2197. if (this.options.showFooter && !this.options.cardView) {
  2198. this.fitFooter()
  2199. }
  2200. }
  2201. showLoading () {
  2202. this.$tableLoading.css('display', 'flex')
  2203. }
  2204. hideLoading () {
  2205. this.$tableLoading.css('display', 'none')
  2206. }
  2207. togglePagination () {
  2208. this.options.pagination = !this.options.pagination
  2209. const icon = this.options.showButtonIcons ? this.options.pagination ? this.options.icons.paginationSwitchDown : this.options.icons.paginationSwitchUp : ''
  2210. const text = this.options.showButtonText ? this.options.pagination ? this.options.formatPaginationSwitchUp() : this.options.formatPaginationSwitchDown() : ''
  2211. this.$toolbar.find('button[name="paginationSwitch"]')
  2212. .html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, icon) + ' ' + text)
  2213. this.updatePagination()
  2214. }
  2215. toggleFullscreen () {
  2216. this.$el.closest('.bootstrap-table').toggleClass('fullscreen')
  2217. this.resetView()
  2218. }
  2219. toggleView () {
  2220. this.options.cardView = !this.options.cardView
  2221. this.initHeader()
  2222. const icon = this.options.showButtonIcons ? this.options.cardView ? this.options.icons.toggleOn : this.options.icons.toggleOff : ''
  2223. const text = this.options.showButtonText ? this.options.cardView ? this.options.formatToggleOff() : this.options.formatToggleOn() : ''
  2224. this.$toolbar.find('button[name="toggle"]')
  2225. .html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, icon) + ' ' + text)
  2226. this.initBody()
  2227. this.trigger('toggle', this.options.cardView)
  2228. }
  2229. resetSearch (text) {
  2230. const $search = this.$toolbar.find('.search input')
  2231. $search.val(text || '')
  2232. this.onSearch({currentTarget: $search})
  2233. }
  2234. filterBy (columns, options) {
  2235. this.filterOptions = Utils.isEmptyObject(options) ? this.options.filterOptions : $.extend(this.options.filterOptions, options)
  2236. this.filterColumns = Utils.isEmptyObject(columns) ? {} : columns
  2237. this.options.pageNumber = 1
  2238. this.initSearch()
  2239. this.updatePagination()
  2240. }
  2241. scrollTo (params) {
  2242. if (typeof params === 'undefined') {
  2243. return this.$tableBody.scrollTop()
  2244. }
  2245. let options = {unit: 'px', value: 0}
  2246. if (typeof params === 'object') {
  2247. options = Object.assign(options, params)
  2248. } else if (typeof params === 'string' && params === 'bottom') {
  2249. options.value = this.$tableBody[0].scrollHeight
  2250. } else if (typeof params === 'string') {
  2251. options.value = params
  2252. }
  2253. let scrollTo = options.value
  2254. if (options.unit === 'rows') {
  2255. scrollTo = 0
  2256. this.$body.find(`> tr:lt(${options.value})`).each((i, el) => {
  2257. scrollTo += $(el).outerHeight(true)
  2258. })
  2259. }
  2260. this.$tableBody.scrollTop(scrollTo)
  2261. }
  2262. getScrollPosition () {
  2263. return this.scrollTo()
  2264. }
  2265. selectPage (page) {
  2266. if (page > 0 && page <= this.options.totalPages) {
  2267. this.options.pageNumber = page
  2268. this.updatePagination()
  2269. }
  2270. }
  2271. prevPage () {
  2272. if (this.options.pageNumber > 1) {
  2273. this.options.pageNumber--
  2274. this.updatePagination()
  2275. }
  2276. }
  2277. nextPage () {
  2278. if (this.options.pageNumber < this.options.totalPages) {
  2279. this.options.pageNumber++
  2280. this.updatePagination()
  2281. }
  2282. }
  2283. toggleDetailView (index, _columnDetailFormatter) {
  2284. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"]', index))
  2285. if ($tr.next().is('tr.detail-view')) {
  2286. this.collapseRow(index)
  2287. } else {
  2288. this.expandRow(index, _columnDetailFormatter)
  2289. }
  2290. this.resetView()
  2291. }
  2292. expandRow (index, _columnDetailFormatter) {
  2293. const row = this.data[index]
  2294. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"][data-has-detail-view]', index))
  2295. if ($tr.next().is('tr.detail-view')) {
  2296. return
  2297. }
  2298. if (this.options.detailViewIcon) {
  2299. $tr.find('a.detail-icon').html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailClose))
  2300. }
  2301. $tr.after(Utils.sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.children('td').length))
  2302. const $element = $tr.next().find('td')
  2303. const detailFormatter = _columnDetailFormatter || this.options.detailFormatter
  2304. const content = Utils.calculateObjectValue(this.options, detailFormatter, [index, row, $element], '')
  2305. if ($element.length === 1) {
  2306. $element.append(content)
  2307. }
  2308. this.trigger('expand-row', index, row, $element)
  2309. }
  2310. collapseRow (index) {
  2311. const row = this.data[index]
  2312. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"][data-has-detail-view]', index))
  2313. if (!$tr.next().is('tr.detail-view')) {
  2314. return
  2315. }
  2316. if (this.options.detailViewIcon) {
  2317. $tr.find('a.detail-icon').html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailOpen))
  2318. }
  2319. this.trigger('collapse-row', index, row, $tr.next())
  2320. $tr.next().remove()
  2321. }
  2322. expandAllRows () {
  2323. const trs = this.$body.find('> tr[data-index][data-has-detail-view]')
  2324. for (let i = 0; i < trs.length; i++) {
  2325. this.expandRow($(trs[i]).data('index'))
  2326. }
  2327. }
  2328. collapseAllRows () {
  2329. const trs = this.$body.find('> tr[data-index][data-has-detail-view]')
  2330. for (let i = 0; i < trs.length; i++) {
  2331. this.collapseRow($(trs[i]).data('index'))
  2332. }
  2333. }
  2334. updateColumnTitle (params) {
  2335. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('title')) {
  2336. return
  2337. }
  2338. this.columns[this.fieldsColumnsIndex[params.field]].title =
  2339. this.options.escape ? Utils.escapeHTML(params.title) : params.title
  2340. if (this.columns[this.fieldsColumnsIndex[params.field]].visible) {
  2341. const header = this.options.height !== undefined ? this.$tableHeader : this.$header
  2342. header.find('th[data-field]').each((i, el) => {
  2343. if ($(el).data('field') === params.field) {
  2344. $($(el).find('.th-inner')[0]).text(params.title)
  2345. return false
  2346. }
  2347. })
  2348. }
  2349. }
  2350. updateFormatText (formatName, text) {
  2351. if (!/^format/.test(formatName) || !this.options[formatName]) {
  2352. return
  2353. }
  2354. if (typeof text === 'string') {
  2355. this.options[formatName] = () => text
  2356. } else if (typeof text === 'function') {
  2357. this.options[formatName] = text
  2358. }
  2359. this.initToolbar()
  2360. this.initPagination()
  2361. this.initBody()
  2362. }
  2363. }
  2364. BootstrapTable.VERSION = Constants.VERSION
  2365. BootstrapTable.DEFAULTS = Constants.DEFAULTS
  2366. BootstrapTable.LOCALES = Constants.LOCALES
  2367. BootstrapTable.COLUMN_DEFAULTS = Constants.COLUMN_DEFAULTS
  2368. BootstrapTable.METHODS = Constants.METHODS
  2369. BootstrapTable.EVENTS = Constants.EVENTS
  2370. // BOOTSTRAP TABLE PLUGIN DEFINITION
  2371. // =======================
  2372. $.BootstrapTable = BootstrapTable
  2373. $.fn.bootstrapTable = function (option, ...args) {
  2374. let value
  2375. this.each((i, el) => {
  2376. let data = $(el).data('bootstrap.table')
  2377. const options = $.extend({}, BootstrapTable.DEFAULTS, $(el).data(),
  2378. typeof option === 'object' && option)
  2379. if (typeof option === 'string') {
  2380. if (!Constants.METHODS.includes(option)) {
  2381. throw new Error(`Unknown method: ${option}`)
  2382. }
  2383. if (!data) {
  2384. return
  2385. }
  2386. value = data[option](...args)
  2387. if (option === 'destroy') {
  2388. $(el).removeData('bootstrap.table')
  2389. }
  2390. }
  2391. if (!data) {
  2392. $(el).data('bootstrap.table', (data = new $.BootstrapTable(el, options)))
  2393. }
  2394. })
  2395. return typeof value === 'undefined' ? this : value
  2396. }
  2397. $.fn.bootstrapTable.Constructor = BootstrapTable
  2398. $.fn.bootstrapTable.theme = Constants.THEME
  2399. $.fn.bootstrapTable.VERSION = Constants.VERSION
  2400. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS
  2401. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS
  2402. $.fn.bootstrapTable.events = BootstrapTable.EVENTS
  2403. $.fn.bootstrapTable.locales = BootstrapTable.LOCALES
  2404. $.fn.bootstrapTable.methods = BootstrapTable.METHODS
  2405. $.fn.bootstrapTable.utils = Utils
  2406. // BOOTSTRAP TABLE INIT
  2407. // =======================
  2408. $(() => {
  2409. $('[data-toggle="table"]').bootstrapTable()
  2410. })
  2411. export default BootstrapTable