bootstrap-table.js 82 KB

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