bootstrap-table.js 91 KB

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