bootstrap-table.js 87 KB

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