bootstrap-table.js 86 KB

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