bootstrap-table.js 87 KB

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