bootstrap-table.js 95 KB

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