bootstrap-table.js 83 KB

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