bootstrap-table.js 88 KB

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