bootstrap-table.js 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879
  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * version: 1.15.4
  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.toolbarDropdownSeparator)
  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,
  540. this.constants.buttonsClass,
  541. o.formatSearch(),
  542. o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.search) : '',
  543. o.showButtonText ? o.formatSearch() : ''
  544. )
  545. const showSearchClearButton = Utils.sprintf(this.constants.html.searchClearButton,
  546. this.constants.buttonsClass,
  547. o.formatClearSearch(),
  548. o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.clearSearch) : '',
  549. o.showButtonText ? o.formatClearSearch() : ''
  550. )
  551. const searchInputHtml = `<input class="${this.constants.classes.input}
  552. ${Utils.sprintf(' %s%s', this.constants.classes.inputPrefix, o.iconSize)}
  553. search-input" type="text" placeholder="${o.formatSearch()}">`
  554. let searchInputFinalHtml = searchInputHtml
  555. if (o.showSearchButton || o.showSearchClearButton) {
  556. const buttonsHtml = (o.showSearchButton ? showSearchButton : '') +
  557. (o.showSearchClearButton ? showSearchClearButton : '')
  558. searchInputFinalHtml = o.search ? Utils.sprintf(this.constants.html.inputGroup,
  559. searchInputHtml, buttonsHtml) : buttonsHtml
  560. }
  561. html.push(Utils.sprintf(`
  562. <div class="${this.constants.classes.pull}-${o.searchAlign} search ${this.constants.classes.inputGroup}">
  563. %s
  564. </div>
  565. `, searchInputFinalHtml))
  566. this.$toolbar.append(html.join(''))
  567. const $searchInput = this.$toolbar.find('.search input')
  568. const handleInputEvent = () => {
  569. const eventTriggers = Utils.isIEBrowser() ? 'mouseup' : 'keyup drop blur'
  570. $searchInput.off(eventTriggers).on(eventTriggers, event => {
  571. if (o.searchOnEnterKey && event.keyCode !== 13) {
  572. return
  573. }
  574. if ([37, 38, 39, 40].includes(event.keyCode)) {
  575. return
  576. }
  577. clearTimeout(timeoutId) // doesn't matter if it's 0
  578. timeoutId = setTimeout(() => {
  579. this.onSearch(event)
  580. }, o.searchTimeOut)
  581. })
  582. }
  583. if (o.showSearchButton) {
  584. this.$toolbar.find('.search button[name=search]').off('click').on('click', event => {
  585. clearTimeout(timeoutId) // doesn't matter if it's 0
  586. timeoutId = setTimeout(() => {
  587. this.onSearch({currentTarget: $searchInput})
  588. }, o.searchTimeOut)
  589. })
  590. if (o.searchOnEnterKey) {
  591. handleInputEvent()
  592. }
  593. } else {
  594. handleInputEvent()
  595. }
  596. if (o.showSearchClearButton) {
  597. this.$toolbar.find('.search button[name=clearSearch]').click(() => {
  598. this.resetSearch()
  599. })
  600. }
  601. }
  602. }
  603. onSearch ({currentTarget, firedByInitSearchText} = {}, overwriteSearchText = true) {
  604. if (currentTarget !== undefined && $(currentTarget).length && overwriteSearchText) {
  605. const text = $(currentTarget).val().trim()
  606. if (this.options.trimOnSearch && $(currentTarget).val() !== text) {
  607. $(currentTarget).val(text)
  608. }
  609. if (this.searchText === text) {
  610. return
  611. }
  612. if ($(currentTarget).hasClass('search-input')) {
  613. this.searchText = text
  614. this.options.searchText = text
  615. }
  616. }
  617. if (!firedByInitSearchText) {
  618. this.options.pageNumber = 1
  619. }
  620. this.initSearch()
  621. if (firedByInitSearchText) {
  622. if (this.options.sidePagination === 'client') {
  623. this.updatePagination()
  624. }
  625. } else {
  626. this.updatePagination()
  627. }
  628. this.trigger('search', this.searchText)
  629. }
  630. initSearch () {
  631. this.filterOptions = this.filterOptions || this.options.filterOptions
  632. if (this.options.sidePagination !== 'server') {
  633. if (this.options.customSearch) {
  634. this.data = Utils.calculateObjectValue(this.options, this.options.customSearch,
  635. [this.options.data, this.searchText, this.filterColumns])
  636. return
  637. }
  638. const s = this.searchText && (this.options.escape
  639. ? Utils.escapeHTML(this.searchText) : this.searchText).toLowerCase()
  640. const f = Utils.isEmptyObject(this.filterColumns) ? null : this.filterColumns
  641. // Check filter
  642. if (typeof this.filterOptions.filterAlgorithm === 'function') {
  643. this.data = this.options.data.filter((item, i) => this.filterOptions.filterAlgorithm.apply(null, [item, f]))
  644. } else if (typeof this.filterOptions.filterAlgorithm === 'string') {
  645. this.data = f ? this.options.data.filter((item, i) => {
  646. const filterAlgorithm = this.filterOptions.filterAlgorithm
  647. if (filterAlgorithm === 'and') {
  648. for (const key in f) {
  649. if (
  650. (Array.isArray(f[key]) &&
  651. !f[key].includes(item[key])) ||
  652. (!Array.isArray(f[key]) &&
  653. item[key] !== f[key])
  654. ) {
  655. return false
  656. }
  657. }
  658. } else if (filterAlgorithm === 'or') {
  659. let match = false
  660. for (const key in f) {
  661. if (
  662. (Array.isArray(f[key]) &&
  663. f[key].includes(item[key])) ||
  664. (!Array.isArray(f[key]) &&
  665. item[key] === f[key])
  666. ) {
  667. match = true
  668. }
  669. }
  670. return match
  671. }
  672. return true
  673. }) : this.options.data
  674. }
  675. const visibleFields = this.getVisibleFields()
  676. this.data = s ? this.data.filter((item, i) => {
  677. for (let j = 0; j < this.header.fields.length; j++) {
  678. if (!this.header.searchables[j] || (this.options.visibleSearch && visibleFields.indexOf(this.header.fields[j]) === -1)) {
  679. continue
  680. }
  681. const key = Utils.isNumeric(this.header.fields[j]) ? parseInt(this.header.fields[j], 10) : this.header.fields[j]
  682. const column = this.columns[this.fieldsColumnsIndex[key]]
  683. let value
  684. if (typeof key === 'string') {
  685. value = item
  686. const props = key.split('.')
  687. for (let i = 0; i < props.length; i++) {
  688. if (value[props[i]] !== null) {
  689. value = value[props[i]]
  690. }
  691. }
  692. } else {
  693. value = item[key]
  694. }
  695. // Fix #142: respect searchFormatter boolean
  696. if (column && column.searchFormatter) {
  697. value = Utils.calculateObjectValue(column,
  698. this.header.formatters[j], [value, item, i, column.field], value)
  699. }
  700. if (typeof value === 'string' || typeof value === 'number') {
  701. if (this.options.strictSearch) {
  702. if ((`${value}`).toLowerCase() === s) {
  703. return true
  704. }
  705. } else {
  706. const largerSmallerEqualsRegex = /(?:(<=|=>|=<|>=|>|<)(?:\s+)?(\d+)?|(\d+)?(\s+)?(<=|=>|=<|>=|>|<))/gm
  707. const matches = largerSmallerEqualsRegex.exec(s)
  708. let comparisonCheck = false
  709. if (matches) {
  710. const operator = matches[1] || `${matches[5]}l`
  711. const comparisonValue = matches[2] || matches[3]
  712. const int = parseInt(value, 10)
  713. const comparisonInt = parseInt(comparisonValue, 10)
  714. switch (operator) {
  715. case '>':
  716. case '<l':
  717. comparisonCheck = int > comparisonInt
  718. break
  719. case '<':
  720. case '>l':
  721. comparisonCheck = int < comparisonInt
  722. break
  723. case '<=':
  724. case '=<':
  725. case '>=l':
  726. case '=>l':
  727. comparisonCheck = int <= comparisonInt
  728. break
  729. case '>=':
  730. case '=>':
  731. case '<=l':
  732. case '=<l':
  733. comparisonCheck = int >= comparisonInt
  734. break
  735. default:
  736. break
  737. }
  738. }
  739. if (comparisonCheck || (`${value}`).toLowerCase().includes(s)) {
  740. return true
  741. }
  742. }
  743. }
  744. }
  745. return false
  746. }) : this.data
  747. }
  748. }
  749. initPagination () {
  750. const o = this.options
  751. if (!o.pagination) {
  752. this.$pagination.hide()
  753. return
  754. }
  755. this.$pagination.show()
  756. const html = []
  757. let $allSelected = false
  758. let i
  759. let from
  760. let to
  761. let $pageList
  762. let $pre
  763. let $next
  764. let $number
  765. const data = this.getData({includeHiddenRows: false})
  766. let pageList = o.pageList
  767. if (o.sidePagination !== 'server') {
  768. o.totalRows = data.length
  769. }
  770. this.totalPages = 0
  771. if (o.totalRows) {
  772. if (o.pageSize === o.formatAllRows()) {
  773. o.pageSize = o.totalRows
  774. $allSelected = true
  775. } else if (o.pageSize === o.totalRows) {
  776. // Fix #667 Table with pagination,
  777. // multiple pages and a search this matches to one page throws exception
  778. const pageLst = typeof o.pageList === 'string'
  779. ? o.pageList.replace('[', '').replace(']', '')
  780. .replace(/ /g, '').toLowerCase().split(',') : o.pageList
  781. if (pageLst.includes(o.formatAllRows().toLowerCase())) {
  782. $allSelected = true
  783. }
  784. }
  785. this.totalPages = ~~((o.totalRows - 1) / o.pageSize) + 1
  786. o.totalPages = this.totalPages
  787. }
  788. if (this.totalPages > 0 && o.pageNumber > this.totalPages) {
  789. o.pageNumber = this.totalPages
  790. }
  791. this.pageFrom = (o.pageNumber - 1) * o.pageSize + 1
  792. this.pageTo = o.pageNumber * o.pageSize
  793. if (this.pageTo > o.totalRows) {
  794. this.pageTo = o.totalRows
  795. }
  796. if (this.options.pagination && this.options.sidePagination !== 'server') {
  797. this.options.totalNotFiltered = this.options.data.length
  798. }
  799. if (!this.options.showExtendedPagination) {
  800. this.options.totalNotFiltered = undefined
  801. }
  802. const paginationInfo = o.onlyInfoPagination ?
  803. o.formatDetailPagination(o.totalRows) :
  804. o.formatShowingRows(this.pageFrom, this.pageTo, o.totalRows, o.totalNotFiltered)
  805. html.push(`<div class="${this.constants.classes.pull}-${o.paginationDetailHAlign} pagination-detail">
  806. <span class="pagination-info">
  807. ${paginationInfo}
  808. </span>`)
  809. if (!o.onlyInfoPagination) {
  810. html.push('<span class="page-list">')
  811. const pageNumber = [
  812. `<span class="${this.constants.classes.paginationDropdown}">
  813. <button class="${this.constants.buttonsClass} dropdown-toggle" type="button" data-toggle="dropdown">
  814. <span class="page-size">
  815. ${$allSelected ? o.formatAllRows() : o.pageSize}
  816. </span>
  817. ${this.constants.html.dropdownCaret}
  818. </button>
  819. ${this.constants.html.pageDropdown[0]}`]
  820. if (typeof o.pageList === 'string') {
  821. const list = o.pageList.replace('[', '').replace(']', '')
  822. .replace(/ /g, '').split(',')
  823. pageList = []
  824. for (const value of list) {
  825. pageList.push(
  826. (value.toLowerCase() === o.formatAllRows().toLowerCase() ||
  827. ['all', 'unlimited'].includes(value.toLowerCase()))
  828. ? o.formatAllRows() : +value)
  829. }
  830. }
  831. pageList.forEach((page, i) => {
  832. if (!o.smartDisplay || i === 0 || pageList[i - 1] < o.totalRows) {
  833. let active
  834. if ($allSelected) {
  835. active = page === o.formatAllRows() ? this.constants.classes.dropdownActive : ''
  836. } else {
  837. active = page === o.pageSize ? this.constants.classes.dropdownActive : ''
  838. }
  839. pageNumber.push(Utils.sprintf(this.constants.html.pageDropdownItem, active, page))
  840. }
  841. })
  842. pageNumber.push(`${this.constants.html.pageDropdown[1]}</span>`)
  843. html.push(o.formatRecordsPerPage(pageNumber.join('')))
  844. html.push('</span></div>')
  845. html.push(`<div class="${this.constants.classes.pull}-${o.paginationHAlign} pagination">`,
  846. Utils.sprintf(this.constants.html.pagination[0], Utils.sprintf(' pagination-%s', o.iconSize)),
  847. Utils.sprintf(this.constants.html.paginationItem, ' page-pre', o.formatSRPaginationPreText(), o.paginationPreText))
  848. if (this.totalPages < o.paginationSuccessivelySize) {
  849. from = 1
  850. to = this.totalPages
  851. } else {
  852. from = o.pageNumber - o.paginationPagesBySide
  853. to = from + (o.paginationPagesBySide * 2)
  854. }
  855. if (o.pageNumber < (o.paginationSuccessivelySize - 1)) {
  856. to = o.paginationSuccessivelySize
  857. }
  858. if (o.paginationSuccessivelySize > this.totalPages - from) {
  859. from = from - (o.paginationSuccessivelySize - (this.totalPages - from)) + 1
  860. }
  861. if (from < 1) {
  862. from = 1
  863. }
  864. if (to > this.totalPages) {
  865. to = this.totalPages
  866. }
  867. const middleSize = Math.round(o.paginationPagesBySide / 2)
  868. const pageItem = (i, classes = '') => Utils.sprintf(this.constants.html.paginationItem,
  869. classes + (i === o.pageNumber ? ` ${this.constants.classes.paginationActive}` : ''), o.formatSRPaginationPageText(i), i)
  870. if (from > 1) {
  871. let max = o.paginationPagesBySide
  872. if (max >= from) max = from - 1
  873. for (i = 1; i <= max; i++) {
  874. html.push(pageItem(i))
  875. }
  876. if ((from - 1) === max + 1) {
  877. i = from - 1
  878. html.push(pageItem(i))
  879. } else {
  880. if ((from - 1) > max) {
  881. if (
  882. (from - o.paginationPagesBySide * 2) > o.paginationPagesBySide &&
  883. o.paginationUseIntermediate
  884. ) {
  885. i = Math.round(((from - middleSize) / 2) + middleSize)
  886. html.push(pageItem(i, ' page-intermediate'))
  887. } else {
  888. html.push(Utils.sprintf(this.constants.html.paginationItem,
  889. ' page-first-separator disabled', '', '...'))
  890. }
  891. }
  892. }
  893. }
  894. for (i = from; i <= to; i++) {
  895. html.push(pageItem(i))
  896. }
  897. if (this.totalPages > to) {
  898. let min = this.totalPages - (o.paginationPagesBySide - 1)
  899. if (to >= min) min = to + 1
  900. if ((to + 1) === min - 1) {
  901. i = to + 1
  902. html.push(pageItem(i))
  903. } else {
  904. if (min > (to + 1)) {
  905. if (
  906. (this.totalPages - to) > o.paginationPagesBySide * 2 &&
  907. o.paginationUseIntermediate
  908. ) {
  909. i = Math.round(((this.totalPages - middleSize - to) / 2) + to)
  910. html.push(pageItem(i, ' page-intermediate'))
  911. } else {
  912. html.push(Utils.sprintf(this.constants.html.paginationItem,
  913. ' page-last-separator disabled', '', '...'))
  914. }
  915. }
  916. }
  917. for (i = min; i <= this.totalPages; i++) {
  918. html.push(pageItem(i))
  919. }
  920. }
  921. html.push(Utils.sprintf(this.constants.html.paginationItem, ' page-next', o.formatSRPaginationNextText(), o.paginationNextText))
  922. html.push(this.constants.html.pagination[1], '</div>')
  923. }
  924. this.$pagination.html(html.join(''))
  925. const dropupClass = ['bottom', 'both'].includes(o.paginationVAlign) ?
  926. ` ${this.constants.classes.dropup}` : ''
  927. this.$pagination.last().find('.page-list > span').addClass(dropupClass)
  928. if (!o.onlyInfoPagination) {
  929. $pageList = this.$pagination.find('.page-list a')
  930. $pre = this.$pagination.find('.page-pre')
  931. $next = this.$pagination.find('.page-next')
  932. $number = this.$pagination.find('.page-item').not('.page-next, .page-pre, .page-last-separator, .page-first-separator')
  933. if (this.totalPages <= 1) {
  934. this.$pagination.find('div.pagination').hide()
  935. }
  936. if (o.smartDisplay) {
  937. if (pageList.length < 2 || o.totalRows <= pageList[0]) {
  938. this.$pagination.find('span.page-list').hide()
  939. }
  940. }
  941. // when data is empty, hide the pagination
  942. this.$pagination[this.getData().length ? 'show' : 'hide']()
  943. if (!o.paginationLoop) {
  944. if (o.pageNumber === 1) {
  945. $pre.addClass('disabled')
  946. }
  947. if (o.pageNumber === this.totalPages) {
  948. $next.addClass('disabled')
  949. }
  950. }
  951. if ($allSelected) {
  952. o.pageSize = o.formatAllRows()
  953. }
  954. // removed the events for last and first, onPageNumber executeds the same logic
  955. $pageList.off('click').on('click', e => this.onPageListChange(e))
  956. $pre.off('click').on('click', e => this.onPagePre(e))
  957. $next.off('click').on('click', e => this.onPageNext(e))
  958. $number.off('click').on('click', e => this.onPageNumber(e))
  959. }
  960. }
  961. updatePagination (event) {
  962. // Fix #171: IE disabled button can be clicked bug.
  963. if (event && $(event.currentTarget).hasClass('disabled')) {
  964. return
  965. }
  966. if (!this.options.maintainMetaData) {
  967. this.resetRows()
  968. }
  969. this.initPagination()
  970. if (this.options.sidePagination === 'server') {
  971. this.initServer()
  972. } else {
  973. this.initBody()
  974. }
  975. this.trigger('page-change', this.options.pageNumber, this.options.pageSize)
  976. }
  977. onPageListChange (event) {
  978. event.preventDefault()
  979. const $this = $(event.currentTarget)
  980. $this.parent().addClass(this.constants.classes.dropdownActive)
  981. .siblings().removeClass(this.constants.classes.dropdownActive)
  982. this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase()
  983. ? this.options.formatAllRows() : +$this.text()
  984. this.$toolbar.find('.page-size').text(this.options.pageSize)
  985. this.updatePagination(event)
  986. return false
  987. }
  988. onPagePre (event) {
  989. event.preventDefault()
  990. if ((this.options.pageNumber - 1) === 0) {
  991. this.options.pageNumber = this.options.totalPages
  992. } else {
  993. this.options.pageNumber--
  994. }
  995. this.updatePagination(event)
  996. return false
  997. }
  998. onPageNext (event) {
  999. event.preventDefault()
  1000. if ((this.options.pageNumber + 1) > this.options.totalPages) {
  1001. this.options.pageNumber = 1
  1002. } else {
  1003. this.options.pageNumber++
  1004. }
  1005. this.updatePagination(event)
  1006. return false
  1007. }
  1008. onPageNumber (event) {
  1009. event.preventDefault()
  1010. if (this.options.pageNumber === +$(event.currentTarget).text()) {
  1011. return
  1012. }
  1013. this.options.pageNumber = +$(event.currentTarget).text()
  1014. this.updatePagination(event)
  1015. return false
  1016. }
  1017. initRow (item, i, data, trFragments) {
  1018. const html = []
  1019. let style = {}
  1020. const csses = []
  1021. let data_ = ''
  1022. let attributes = {}
  1023. const htmlAttributes = []
  1024. if (Utils.findIndex(this.hiddenRows, item) > -1) {
  1025. return
  1026. }
  1027. style = Utils.calculateObjectValue(this.options, this.options.rowStyle, [item, i], style)
  1028. if (style && style.css) {
  1029. for (const [key, value] of Object.entries(style.css)) {
  1030. csses.push(`${key}: ${value}`)
  1031. }
  1032. }
  1033. attributes = Utils.calculateObjectValue(this.options,
  1034. this.options.rowAttributes, [item, i], attributes)
  1035. if (attributes) {
  1036. for (const [key, value] of Object.entries(attributes)) {
  1037. htmlAttributes.push(`${key}="${Utils.escapeHTML(value)}"`)
  1038. }
  1039. }
  1040. if (item._data && !Utils.isEmptyObject(item._data)) {
  1041. for (const [k, v] of Object.entries(item._data)) {
  1042. // ignore data-index
  1043. if (k === 'index') {
  1044. return
  1045. }
  1046. data_ += ` data-${k}='${typeof v === 'object' ? JSON.stringify(v) : v}'`
  1047. }
  1048. }
  1049. html.push('<tr',
  1050. Utils.sprintf(' %s', htmlAttributes.length ? htmlAttributes.join(' ') : undefined),
  1051. Utils.sprintf(' id="%s"', Array.isArray(item) ? undefined : item._id),
  1052. Utils.sprintf(' class="%s"', style.classes || (Array.isArray(item) ? undefined : item._class)),
  1053. ` data-index="${i}"`,
  1054. Utils.sprintf(' data-uniqueid="%s"', Utils.getItemField(item, this.options.uniqueId, false)),
  1055. Utils.sprintf(' data-has-detail-view="%s"', (!this.options.cardView && this.options.detailView && Utils.calculateObjectValue(null, this.options.detailFilter, [i, item])) ? 'true' : undefined),
  1056. Utils.sprintf('%s', data_),
  1057. '>'
  1058. )
  1059. if (this.options.cardView) {
  1060. html.push(`<td colspan="${this.header.fields.length}"><div class="card-views">`)
  1061. }
  1062. if (!this.options.cardView && this.options.detailView && this.options.detailViewIcon) {
  1063. html.push('<td>')
  1064. if (Utils.calculateObjectValue(null, this.options.detailFilter, [i, item])) {
  1065. html.push(`
  1066. <a class="detail-icon" href="#">
  1067. ${Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailOpen)}
  1068. </a>
  1069. `)
  1070. }
  1071. html.push('</td>')
  1072. }
  1073. this.header.fields.forEach((field, j) => {
  1074. let text = ''
  1075. let value_ = Utils.getItemField(item, field, this.options.escape)
  1076. let value = ''
  1077. let type = ''
  1078. let cellStyle = {}
  1079. let id_ = ''
  1080. let class_ = this.header.classes[j]
  1081. let style_ = ''
  1082. let data_ = ''
  1083. let rowspan_ = ''
  1084. let colspan_ = ''
  1085. let title_ = ''
  1086. const column = this.columns[j]
  1087. if (this.fromHtml && typeof value_ === 'undefined') {
  1088. if ((!column.checkbox) && (!column.radio)) {
  1089. return
  1090. }
  1091. }
  1092. if (!column.visible) {
  1093. return
  1094. }
  1095. if (this.options.cardView && (!column.cardVisible)) {
  1096. return
  1097. }
  1098. if (column.escape) {
  1099. value_ = Utils.escapeHTML(value_)
  1100. }
  1101. if (csses.concat([this.header.styles[j]]).length) {
  1102. style_ = ` style="${csses.concat([this.header.styles[j]]).join('; ')}"`
  1103. }
  1104. // handle td's id and class
  1105. if (item[`_${field}_id`]) {
  1106. id_ = Utils.sprintf(' id="%s"', item[`_${field}_id`])
  1107. }
  1108. if (item[`_${field}_class`]) {
  1109. class_ = Utils.sprintf(' class="%s"', item[`_${field}_class`])
  1110. }
  1111. if (item[`_${field}_rowspan`]) {
  1112. rowspan_ = Utils.sprintf(' rowspan="%s"', item[`_${field}_rowspan`])
  1113. }
  1114. if (item[`_${field}_colspan`]) {
  1115. colspan_ = Utils.sprintf(' colspan="%s"', item[`_${field}_colspan`])
  1116. }
  1117. if (item[`_${field}_title`]) {
  1118. title_ = Utils.sprintf(' title="%s"', item[`_${field}_title`])
  1119. }
  1120. cellStyle = Utils.calculateObjectValue(this.header,
  1121. this.header.cellStyles[j], [value_, item, i, field], cellStyle)
  1122. if (cellStyle.classes) {
  1123. class_ = ` class="${cellStyle.classes}"`
  1124. }
  1125. if (cellStyle.css) {
  1126. const csses_ = []
  1127. for (const [key, value] of Object.entries(cellStyle.css)) {
  1128. csses_.push(`${key}: ${value}`)
  1129. }
  1130. style_ = ` style="${csses_.concat(this.header.styles[j]).join('; ')}"`
  1131. }
  1132. value = Utils.calculateObjectValue(column,
  1133. this.header.formatters[j], [value_, item, i, field], value_)
  1134. if (item[`_${field}_data`] && !Utils.isEmptyObject(item[`_${field}_data`])) {
  1135. for (const [k, v] of Object.entries(item[`_${field}_data`])) {
  1136. // ignore data-index
  1137. if (k === 'index') {
  1138. return
  1139. }
  1140. data_ += ` data-${k}="${v}"`
  1141. }
  1142. }
  1143. if (column.checkbox || column.radio) {
  1144. type = column.checkbox ? 'checkbox' : type
  1145. type = column.radio ? 'radio' : type
  1146. const c = column['class'] || ''
  1147. const isChecked = (value === true || value_ || (value && value.checked)) && value !== false
  1148. const isDisabled = !column.checkboxEnabled || (value && value.disabled)
  1149. text = [
  1150. this.options.cardView
  1151. ? `<div class="card-view ${c}">`
  1152. : `<td class="bs-checkbox ${c}"${class_}${style_}>`,
  1153. `<label>
  1154. <input
  1155. data-index="${i}"
  1156. name="${this.options.selectItemName}"
  1157. type="${type}"
  1158. ${Utils.sprintf('value="%s"', item[this.options.idField])}
  1159. ${Utils.sprintf('checked="%s"', isChecked ? 'checked' : undefined)}
  1160. ${Utils.sprintf('disabled="%s"', isDisabled ? 'disabled' : undefined)} />
  1161. <span></span>
  1162. </label>`,
  1163. this.header.formatters[j] && typeof value === 'string' ? value : '',
  1164. this.options.cardView ? '</div>' : '</td>'
  1165. ].join('')
  1166. item[this.header.stateField] = value === true || (!!value_ || (value && value.checked))
  1167. } else {
  1168. value = typeof value === 'undefined' || value === null
  1169. ? this.options.undefinedText : value
  1170. if (this.options.cardView) {
  1171. const cardTitle = this.options.showHeader
  1172. ? `<span class="card-view-title"${style_}>${Utils.getFieldTitle(this.columns, field)}</span>` : ''
  1173. text = `<div class="card-view">${cardTitle}<span class="card-view-value">${value}</span></div>`
  1174. if (this.options.smartDisplay && value === '') {
  1175. text = '<div class="card-view"></div>'
  1176. }
  1177. } else {
  1178. text = `<td${id_}${class_}${style_}${data_}${rowspan_}${colspan_}${title_}>${value}</td>`
  1179. }
  1180. }
  1181. html.push(text)
  1182. })
  1183. if (this.options.cardView) {
  1184. html.push('</div></td>')
  1185. }
  1186. html.push('</tr>')
  1187. return html.join('')
  1188. }
  1189. initBody (fixedScroll) {
  1190. const data = this.getData()
  1191. this.trigger('pre-body', data)
  1192. this.$body = this.$el.find('>tbody')
  1193. if (!this.$body.length) {
  1194. this.$body = $('<tbody></tbody>').appendTo(this.$el)
  1195. }
  1196. // Fix #389 Bootstrap-table-flatJSON is not working
  1197. if (!this.options.pagination || this.options.sidePagination === 'server') {
  1198. this.pageFrom = 1
  1199. this.pageTo = data.length
  1200. }
  1201. const rows = []
  1202. const trFragments = $(document.createDocumentFragment())
  1203. let hasTr = false
  1204. for (let i = this.pageFrom - 1; i < this.pageTo; i++) {
  1205. const item = data[i]
  1206. const tr = this.initRow(item, i, data, trFragments)
  1207. hasTr = hasTr || !!tr
  1208. if (tr && typeof tr === 'string') {
  1209. if (!this.options.virtualScroll) {
  1210. trFragments.append(tr)
  1211. } else {
  1212. rows.push(tr)
  1213. }
  1214. }
  1215. }
  1216. // show no records
  1217. if (!hasTr) {
  1218. this.$body.html(`<tr class="no-records-found">${Utils.sprintf('<td colspan="%s">%s</td>',
  1219. this.$header.find('th').length,
  1220. this.options.formatNoMatches())}</tr>`)
  1221. } else {
  1222. if (!this.options.virtualScroll) {
  1223. this.$body.html(trFragments)
  1224. } else {
  1225. if (this.virtualScroll) {
  1226. this.virtualScroll.destroy()
  1227. }
  1228. this.virtualScroll = new VirtualScroll({
  1229. rows,
  1230. fixedScroll,
  1231. scrollEl: this.$tableBody[0],
  1232. contentEl: this.$body[0],
  1233. itemHeight: this.options.virtualScrollItemHeight,
  1234. callback: () => {
  1235. this.fitHeader()
  1236. this.initBodyEvent()
  1237. }
  1238. })
  1239. }
  1240. }
  1241. if (!fixedScroll) {
  1242. this.scrollTo(0)
  1243. }
  1244. this.initBodyEvent()
  1245. this.updateSelected()
  1246. this.initFooter()
  1247. this.resetView()
  1248. if (this.options.sidePagination !== 'server') {
  1249. this.options.totalRows = data.length
  1250. }
  1251. this.trigger('post-body', data)
  1252. }
  1253. initBodyEvent () {
  1254. // click to select by column
  1255. this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', e => {
  1256. const $td = $(e.currentTarget)
  1257. const $tr = $td.parent()
  1258. const $cardViewArr = $(e.target).parents('.card-views').children()
  1259. const $cardViewTarget = $(e.target).parents('.card-view')
  1260. const rowIndex = $tr.data('index')
  1261. const item = this.data[rowIndex]
  1262. const index = this.options.cardView ? $cardViewArr.index($cardViewTarget) : $td[0].cellIndex
  1263. const fields = this.getVisibleFields()
  1264. const field = fields[this.options.detailView && this.options.detailViewIcon && !this.options.cardView ? index - 1 : index]
  1265. const column = this.columns[this.fieldsColumnsIndex[field]]
  1266. const value = Utils.getItemField(item, field, this.options.escape)
  1267. if ($td.find('.detail-icon').length) {
  1268. return
  1269. }
  1270. this.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td)
  1271. this.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr, field)
  1272. // if click to select - then trigger the checkbox/radio click
  1273. if (
  1274. e.type === 'click' &&
  1275. this.options.clickToSelect &&
  1276. column.clickToSelect &&
  1277. !Utils.calculateObjectValue(this.options, this.options.ignoreClickToSelectOn, [e.target])
  1278. ) {
  1279. const $selectItem = $tr.find(Utils.sprintf('[name="%s"]', this.options.selectItemName))
  1280. if ($selectItem.length) {
  1281. $selectItem[0].click()
  1282. }
  1283. }
  1284. if (e.type === 'click' && this.options.detailViewByClick) {
  1285. this.toggleDetailView(rowIndex, this.header.detailFormatters[this.fieldsColumnsIndex[field]])
  1286. }
  1287. }).off('mousedown').on('mousedown', e => {
  1288. // https://github.com/jquery/jquery/issues/1741
  1289. this.multipleSelectRowCtrlKey = e.ctrlKey || e.metaKey
  1290. this.multipleSelectRowShiftKey = e.shiftKey
  1291. })
  1292. this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', e => {
  1293. e.preventDefault()
  1294. this.toggleDetailView($(e.currentTarget).parent().parent().data('index'))
  1295. return false
  1296. })
  1297. this.$selectItem = this.$body.find(Utils.sprintf('[name="%s"]', this.options.selectItemName))
  1298. this.$selectItem.off('click').on('click', e => {
  1299. e.stopImmediatePropagation()
  1300. const $this = $(e.currentTarget)
  1301. this._toggleCheck($this.prop('checked'), $this.data('index'))
  1302. })
  1303. this.header.events.forEach((_events, i) => {
  1304. let events = _events
  1305. if (!events) {
  1306. return
  1307. }
  1308. // fix bug, if events is defined with namespace
  1309. if (typeof events === 'string') {
  1310. events = Utils.calculateObjectValue(null, events)
  1311. }
  1312. const field = this.header.fields[i]
  1313. let fieldIndex = this.getVisibleFields().indexOf(field)
  1314. if (fieldIndex === -1) {
  1315. return
  1316. }
  1317. if (this.options.detailView && !this.options.cardView) {
  1318. fieldIndex += 1
  1319. }
  1320. for (const key in events) {
  1321. if (!events.hasOwnProperty(key)) {
  1322. continue
  1323. }
  1324. const event = events[key]
  1325. this.$body.find('>tr:not(.no-records-found)').each((i, tr) => {
  1326. const $tr = $(tr)
  1327. const $td = $tr.find(this.options.cardView ? '.card-views>.card-view' : '>td').eq(fieldIndex)
  1328. const index = key.indexOf(' ')
  1329. const name = key.substring(0, index)
  1330. const el = key.substring(index + 1)
  1331. $td.find(el).off(name).on(name, e => {
  1332. const index = $tr.data('index')
  1333. const row = this.data[index]
  1334. const value = row[field]
  1335. event.apply(this, [e, value, row, index])
  1336. })
  1337. })
  1338. }
  1339. })
  1340. }
  1341. initServer (silent, query, url) {
  1342. let data = {}
  1343. const index = this.header.fields.indexOf(this.options.sortName)
  1344. let params = {
  1345. searchText: this.searchText,
  1346. sortName: this.options.sortName,
  1347. sortOrder: this.options.sortOrder
  1348. }
  1349. if (this.header.sortNames[index]) {
  1350. params.sortName = this.header.sortNames[index]
  1351. }
  1352. if (this.options.pagination && this.options.sidePagination === 'server') {
  1353. params.pageSize = this.options.pageSize === this.options.formatAllRows()
  1354. ? this.options.totalRows : this.options.pageSize
  1355. params.pageNumber = this.options.pageNumber
  1356. }
  1357. if (!(url || this.options.url) && !this.options.ajax) {
  1358. return
  1359. }
  1360. if (this.options.queryParamsType === 'limit') {
  1361. params = {
  1362. search: params.searchText,
  1363. sort: params.sortName,
  1364. order: params.sortOrder
  1365. }
  1366. if (this.options.pagination && this.options.sidePagination === 'server') {
  1367. params.offset = this.options.pageSize === this.options.formatAllRows()
  1368. ? 0 : this.options.pageSize * (this.options.pageNumber - 1)
  1369. params.limit = this.options.pageSize === this.options.formatAllRows()
  1370. ? this.options.totalRows : this.options.pageSize
  1371. if (params.limit === 0) {
  1372. delete params.limit
  1373. }
  1374. }
  1375. }
  1376. if (!(Utils.isEmptyObject(this.filterColumnsPartial))) {
  1377. params.filter = JSON.stringify(this.filterColumnsPartial, null)
  1378. }
  1379. $.extend(params, query || {})
  1380. data = Utils.calculateObjectValue(this.options, this.options.queryParams, [params], data)
  1381. // false to stop request
  1382. if (data === false) {
  1383. return
  1384. }
  1385. if (!silent) {
  1386. this.showLoading()
  1387. }
  1388. const request = $.extend({}, Utils.calculateObjectValue(null, this.options.ajaxOptions), {
  1389. type: this.options.method,
  1390. url: url || this.options.url,
  1391. data: this.options.contentType === 'application/json' && this.options.method === 'post'
  1392. ? JSON.stringify(data) : data,
  1393. cache: this.options.cache,
  1394. contentType: this.options.contentType,
  1395. dataType: this.options.dataType,
  1396. success: (_res, textStatus, jqXHR) => {
  1397. const res = Utils.calculateObjectValue(this.options,
  1398. this.options.responseHandler, [_res, jqXHR], _res)
  1399. this.load(res)
  1400. this.trigger('load-success', res, jqXHR.status, jqXHR)
  1401. if (!silent) {
  1402. this.hideLoading()
  1403. }
  1404. },
  1405. error: jqXHR => {
  1406. let data = []
  1407. if (this.options.sidePagination === 'server') {
  1408. data = {}
  1409. data[this.options.totalField] = 0
  1410. data[this.options.dataField] = []
  1411. }
  1412. this.load(data)
  1413. this.trigger('load-error', jqXHR.status, jqXHR)
  1414. if (!silent) this.$tableLoading.hide()
  1415. }
  1416. })
  1417. if (this.options.ajax) {
  1418. Utils.calculateObjectValue(this, this.options.ajax, [request], null)
  1419. } else {
  1420. if (this._xhr && this._xhr.readyState !== 4) {
  1421. this._xhr.abort()
  1422. }
  1423. this._xhr = $.ajax(request)
  1424. }
  1425. return data
  1426. }
  1427. initSearchText () {
  1428. if (this.options.search) {
  1429. this.searchText = ''
  1430. if (this.options.searchText !== '') {
  1431. const $search = this.$toolbar.find('.search input')
  1432. $search.val(this.options.searchText)
  1433. this.onSearch({currentTarget: $search, firedByInitSearchText: true})
  1434. }
  1435. }
  1436. }
  1437. getCaret () {
  1438. this.$header.find('th').each((i, th) => {
  1439. $(th).find('.sortable').removeClass('desc asc')
  1440. .addClass($(th).data('field') === this.options.sortName
  1441. ? this.options.sortOrder : 'both')
  1442. })
  1443. }
  1444. updateSelected () {
  1445. const checkAll = this.$selectItem.filter(':enabled').length &&
  1446. this.$selectItem.filter(':enabled').length ===
  1447. this.$selectItem.filter(':enabled').filter(':checked').length
  1448. this.$selectAll.add(this.$selectAll_).prop('checked', checkAll)
  1449. this.$selectItem.each((i, el) => {
  1450. $(el).closest('tr')[$(el).prop('checked') ? 'addClass' : 'removeClass']('selected')
  1451. })
  1452. }
  1453. updateRows () {
  1454. this.$selectItem.each((i, el) => {
  1455. this.data[$(el).data('index')][this.header.stateField] = $(el).prop('checked')
  1456. })
  1457. }
  1458. resetRows () {
  1459. for (const row of this.data) {
  1460. this.$selectAll.prop('checked', false)
  1461. this.$selectItem.prop('checked', false)
  1462. if (this.header.stateField) {
  1463. row[this.header.stateField] = false
  1464. }
  1465. }
  1466. this.initHiddenRows()
  1467. }
  1468. trigger (_name, ...args) {
  1469. const name = `${_name}.bs.table`
  1470. this.options[BootstrapTable.EVENTS[name]](...args)
  1471. this.$el.trigger($.Event(name), args)
  1472. this.options.onAll(name, args)
  1473. this.$el.trigger($.Event('all.bs.table'), [name, args])
  1474. }
  1475. resetHeader () {
  1476. // fix #61: the hidden table reset header bug.
  1477. // fix bug: get $el.css('width') error sometime (height = 500)
  1478. clearTimeout(this.timeoutId_)
  1479. this.timeoutId_ = setTimeout(() => this.fitHeader(), this.$el.is(':hidden') ? 100 : 0)
  1480. }
  1481. fitHeader () {
  1482. if (this.$el.is(':hidden')) {
  1483. this.timeoutId_ = setTimeout(() => this.fitHeader(), 100)
  1484. return
  1485. }
  1486. const fixedBody = this.$tableBody.get(0)
  1487. const scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
  1488. fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight()
  1489. ? Utils.getScrollBarWidth() : 0
  1490. this.$el.css('margin-top', -this.$header.outerHeight())
  1491. const focused = $(':focus')
  1492. if (focused.length > 0) {
  1493. const $th = focused.parents('th')
  1494. if ($th.length > 0) {
  1495. const dataField = $th.attr('data-field')
  1496. if (dataField !== undefined) {
  1497. const $headerTh = this.$header.find(`[data-field='${dataField}']`)
  1498. if ($headerTh.length > 0) {
  1499. $headerTh.find(':input').addClass('focus-temp')
  1500. }
  1501. }
  1502. }
  1503. }
  1504. this.$header_ = this.$header.clone(true, true)
  1505. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]')
  1506. this.$tableHeader
  1507. .css('margin-right', scrollWidth)
  1508. .find('table').css('width', this.$el.outerWidth())
  1509. .html('').attr('class', this.$el.attr('class'))
  1510. .append(this.$header_)
  1511. this.$tableLoading.css('width', this.$el.outerWidth())
  1512. const focusedTemp = $('.focus-temp:visible:eq(0)')
  1513. if (focusedTemp.length > 0) {
  1514. focusedTemp.focus()
  1515. this.$header.find('.focus-temp').removeClass('focus-temp')
  1516. }
  1517. // fix bug: $.data() is not working as expected after $.append()
  1518. this.$header.find('th[data-field]').each((i, el) => {
  1519. this.$header_.find(Utils.sprintf('th[data-field="%s"]', $(el).data('field'))).data($(el).data())
  1520. })
  1521. const visibleFields = this.getVisibleFields()
  1522. const $ths = this.$header_.find('th')
  1523. let $tr = this.$body.find('>tr:not(.no-records-found,.virtual-scroll-top)').eq(0)
  1524. while ($tr.length && $tr.find('>td[colspan]:not([colspan="1"])').length) {
  1525. $tr = $tr.next()
  1526. }
  1527. $tr.find('> *').each((i, el) => {
  1528. const $this = $(el)
  1529. let index = i
  1530. if (this.options.detailView && this.options.detailViewIcon && !this.options.cardView) {
  1531. if (i === 0) {
  1532. const $thDetail = $ths.filter('.detail')
  1533. const zoomWidth = $thDetail.innerWidth() - $thDetail.find('.fht-cell').width()
  1534. $thDetail.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1535. }
  1536. index = i - 1
  1537. }
  1538. if (index === -1) {
  1539. return
  1540. }
  1541. let $th = this.$header_.find(Utils.sprintf('th[data-field="%s"]', visibleFields[index]))
  1542. if ($th.length > 1) {
  1543. $th = $($ths[$this[0].cellIndex])
  1544. }
  1545. const zoomWidth = $th.innerWidth() - $th.find('.fht-cell').width()
  1546. $th.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1547. })
  1548. this.horizontalScroll()
  1549. this.trigger('post-header')
  1550. }
  1551. initFooter () {
  1552. if (!this.options.showFooter || this.options.cardView) { // do nothing
  1553. return
  1554. }
  1555. const data = this.getData()
  1556. const html = []
  1557. if (!this.options.cardView && this.options.detailView && this.options.detailViewIcon) {
  1558. html.push('<th class="detail"><div class="th-inner"></div><div class="fht-cell"></div></th>')
  1559. }
  1560. for (const column of this.columns) {
  1561. let falign = ''
  1562. let valign = ''
  1563. const csses = []
  1564. let style = {}
  1565. let class_ = Utils.sprintf(' class="%s"', column['class'])
  1566. if (!column.visible) {
  1567. continue
  1568. }
  1569. if (this.options.cardView && (!column.cardVisible)) {
  1570. return
  1571. }
  1572. falign = Utils.sprintf('text-align: %s; ', column.falign ? column.falign : column.align)
  1573. valign = Utils.sprintf('vertical-align: %s; ', column.valign)
  1574. style = Utils.calculateObjectValue(null, this.options.footerStyle, [column])
  1575. if (style && style.css) {
  1576. for (const [key, value] of Object.entries(style.css)) {
  1577. csses.push(`${key}: ${value}`)
  1578. }
  1579. }
  1580. if (style && style.classes) {
  1581. class_ = Utils.sprintf(' class="%s"', column['class'] ?
  1582. [column['class'], style.classes].join(' ') : style.classes)
  1583. }
  1584. html.push('<th', class_, Utils.sprintf(' style="%s"', falign + valign + csses.concat().join('; ')), '>')
  1585. html.push('<div class="th-inner">')
  1586. html.push(Utils.calculateObjectValue(column, column.footerFormatter,
  1587. [data], this.footerData[0] && this.footerData[0][column.field] || ''))
  1588. html.push('</div>')
  1589. html.push('<div class="fht-cell"></div>')
  1590. html.push('</div>')
  1591. html.push('</th>')
  1592. }
  1593. this.$tableFooter.find('tr').html(html.join(''))
  1594. this.trigger('post-footer', this.$tableFooter)
  1595. }
  1596. fitFooter () {
  1597. if (this.$el.is(':hidden')) {
  1598. setTimeout(() => this.fitFooter(), 100)
  1599. return
  1600. }
  1601. const fixedBody = this.$tableBody.get(0)
  1602. const scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
  1603. fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight()
  1604. ? Utils.getScrollBarWidth() : 0
  1605. this.$tableFooter
  1606. .css('margin-right', scrollWidth)
  1607. .find('table').css('width', this.$el.outerWidth())
  1608. .attr('class', this.$el.attr('class'))
  1609. const visibleFields = this.getVisibleFields()
  1610. const $ths = this.$tableFooter.find('th')
  1611. let $tr = this.$body.find('>tr:first-child:not(.no-records-found)')
  1612. while ($tr.length && $tr.find('>td[colspan]:not([colspan="1"])').length) {
  1613. $tr = $tr.next()
  1614. }
  1615. $tr.find('> *').each((i, el) => {
  1616. const $this = $(el)
  1617. let index = i
  1618. if (this.options.detailView && !this.options.cardView) {
  1619. if (i === 0) {
  1620. const $thDetail = $ths.filter('.detail')
  1621. const zoomWidth = $thDetail.innerWidth() - $thDetail.find('.fht-cell').width()
  1622. $thDetail.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1623. }
  1624. index = i - 1
  1625. }
  1626. if (index === -1) {
  1627. return
  1628. }
  1629. const $th = $ths.eq(i)
  1630. const zoomWidth = $th.innerWidth() - $th.find('.fht-cell').width()
  1631. $th.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1632. })
  1633. this.horizontalScroll()
  1634. }
  1635. horizontalScroll () {
  1636. // horizontal scroll event
  1637. // TODO: it's probably better improving the layout than binding to scroll event
  1638. this.$tableBody.off('scroll').on('scroll', ({currentTarget}) => {
  1639. if (this.options.showHeader && this.options.height) {
  1640. this.$tableHeader.scrollLeft($(currentTarget).scrollLeft())
  1641. }
  1642. if (this.options.showFooter && !this.options.cardView) {
  1643. this.$tableFooter.scrollLeft($(currentTarget).scrollLeft())
  1644. }
  1645. this.trigger('scroll-body', $(currentTarget))
  1646. })
  1647. }
  1648. getVisibleFields () {
  1649. const visibleFields = []
  1650. for (const field of this.header.fields) {
  1651. const column = this.columns[this.fieldsColumnsIndex[field]]
  1652. if (!column || !column.visible) {
  1653. continue
  1654. }
  1655. visibleFields.push(field)
  1656. }
  1657. return visibleFields
  1658. }
  1659. initHiddenRows () {
  1660. this.hiddenRows = []
  1661. }
  1662. // PUBLIC FUNCTION DEFINITION
  1663. // =======================
  1664. getOptions () {
  1665. // deep copy and remove data
  1666. const options = $.extend({}, this.options)
  1667. delete options.data
  1668. return $.extend(true, {}, options)
  1669. }
  1670. refreshOptions (options) {
  1671. // If the objects are equivalent then avoid the call of destroy / init methods
  1672. if (Utils.compareObjects(this.options, options, true)) {
  1673. return
  1674. }
  1675. this.options = $.extend(this.options, options)
  1676. this.trigger('refresh-options', this.options)
  1677. this.destroy()
  1678. this.init()
  1679. }
  1680. getData (params) {
  1681. let data = this.options.data
  1682. if (this.searchText || this.options.sortName || !Utils.isEmptyObject(this.filterColumns) || !Utils.isEmptyObject(this.filterColumnsPartial)) {
  1683. data = this.data
  1684. }
  1685. if (params && params.useCurrentPage) {
  1686. data = data.slice(this.pageFrom - 1, this.pageTo)
  1687. }
  1688. if (params && !params.includeHiddenRows) {
  1689. const hiddenRows = this.getHiddenRows()
  1690. data = data.filter(function (row) {
  1691. return Utils.findIndex(hiddenRows, row) === -1
  1692. })
  1693. }
  1694. return data
  1695. }
  1696. getSelections () {
  1697. // fix #2424: from html with checkbox
  1698. return this.data.filter(row => row[this.header.stateField] === true)
  1699. }
  1700. getAllSelections () {
  1701. return this.options.data.filter(row => row[this.header.stateField] === true)
  1702. }
  1703. load (_data) {
  1704. let fixedScroll = false
  1705. let data = _data
  1706. // #431: support pagination
  1707. if (this.options.pagination && this.options.sidePagination === 'server') {
  1708. this.options.totalRows = data[this.options.totalField]
  1709. }
  1710. if (this.options.pagination && this.options.sidePagination === 'server') {
  1711. this.options.totalNotFiltered = data[this.options.totalNotFilteredField]
  1712. }
  1713. fixedScroll = data.fixedScroll
  1714. data = Array.isArray(data) ? data : data[this.options.dataField]
  1715. this.initData(data)
  1716. this.initSearch()
  1717. this.initPagination()
  1718. this.initBody(fixedScroll)
  1719. }
  1720. append (data) {
  1721. this.initData(data, 'append')
  1722. this.initSearch()
  1723. this.initPagination()
  1724. this.initSort()
  1725. this.initBody(true)
  1726. }
  1727. prepend (data) {
  1728. this.initData(data, 'prepend')
  1729. this.initSearch()
  1730. this.initPagination()
  1731. this.initSort()
  1732. this.initBody(true)
  1733. }
  1734. remove (params) {
  1735. const len = this.options.data.length
  1736. let i
  1737. let row
  1738. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
  1739. return
  1740. }
  1741. for (i = len - 1; i >= 0; i--) {
  1742. row = this.options.data[i]
  1743. if (!row.hasOwnProperty(params.field)) {
  1744. continue
  1745. }
  1746. if (params.values.includes(row[params.field])) {
  1747. this.options.data.splice(i, 1)
  1748. if (this.options.sidePagination === 'server') {
  1749. this.options.totalRows -= 1
  1750. }
  1751. }
  1752. }
  1753. if (len === this.options.data.length) {
  1754. return
  1755. }
  1756. this.initSearch()
  1757. this.initPagination()
  1758. this.initSort()
  1759. this.initBody(true)
  1760. }
  1761. removeAll () {
  1762. if (this.options.data.length > 0) {
  1763. this.options.data.splice(0, this.options.data.length)
  1764. this.initSearch()
  1765. this.initPagination()
  1766. this.initBody(true)
  1767. }
  1768. }
  1769. insertRow (params) {
  1770. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1771. return
  1772. }
  1773. this.options.data.splice(params.index, 0, params.row)
  1774. this.initSearch()
  1775. this.initPagination()
  1776. this.initSort()
  1777. this.initBody(true)
  1778. }
  1779. updateRow (params) {
  1780. const allParams = Array.isArray(params) ? params : [params]
  1781. for (const params of allParams) {
  1782. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1783. continue
  1784. }
  1785. $.extend(this.options.data[params.index], params.row)
  1786. if (params.hasOwnProperty('replace') && params.replace) {
  1787. this.options.data[params.index] = params.row
  1788. } else {
  1789. $.extend(this.options.data[params.index], params.row)
  1790. }
  1791. }
  1792. this.initSearch()
  1793. this.initPagination()
  1794. this.initSort()
  1795. this.initBody(true)
  1796. }
  1797. getRowByUniqueId (_id) {
  1798. const uniqueId = this.options.uniqueId
  1799. const len = this.options.data.length
  1800. let id = _id
  1801. let dataRow = null
  1802. let i
  1803. let row
  1804. let rowUniqueId
  1805. for (i = len - 1; i >= 0; i--) {
  1806. row = this.options.data[i]
  1807. if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column
  1808. rowUniqueId = row[uniqueId]
  1809. } else if (row._data && row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property
  1810. rowUniqueId = row._data[uniqueId]
  1811. } else {
  1812. continue
  1813. }
  1814. if (typeof rowUniqueId === 'string') {
  1815. id = id.toString()
  1816. } else if (typeof rowUniqueId === 'number') {
  1817. if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) {
  1818. id = parseInt(id)
  1819. } else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) {
  1820. id = parseFloat(id)
  1821. }
  1822. }
  1823. if (rowUniqueId === id) {
  1824. dataRow = row
  1825. break
  1826. }
  1827. }
  1828. return dataRow
  1829. }
  1830. updateByUniqueId (params) {
  1831. const allParams = Array.isArray(params) ? params : [params]
  1832. for (const params of allParams) {
  1833. if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
  1834. continue
  1835. }
  1836. const rowId = this.options.data.indexOf(this.getRowByUniqueId(params.id))
  1837. if (rowId === -1) {
  1838. continue
  1839. }
  1840. if (params.hasOwnProperty('replace') && params.replace) {
  1841. this.options.data[rowId] = params.row
  1842. } else {
  1843. $.extend(this.options.data[rowId], params.row)
  1844. }
  1845. }
  1846. this.initSearch()
  1847. this.initPagination()
  1848. this.initSort()
  1849. this.initBody(true)
  1850. }
  1851. removeByUniqueId (id) {
  1852. const len = this.options.data.length
  1853. const row = this.getRowByUniqueId(id)
  1854. if (row) {
  1855. this.options.data.splice(this.options.data.indexOf(row), 1)
  1856. }
  1857. if (len === this.options.data.length) {
  1858. return
  1859. }
  1860. this.initSearch()
  1861. this.initPagination()
  1862. this.initBody(true)
  1863. }
  1864. updateCell (params) {
  1865. if (!params.hasOwnProperty('index') ||
  1866. !params.hasOwnProperty('field') ||
  1867. !params.hasOwnProperty('value')) {
  1868. return
  1869. }
  1870. this.data[params.index][params.field] = params.value
  1871. if (params.reinit === false) {
  1872. return
  1873. }
  1874. this.initSort()
  1875. this.initBody(true)
  1876. }
  1877. updateCellByUniqueId (params) {
  1878. if (!params.hasOwnProperty('id') ||
  1879. !params.hasOwnProperty('field') ||
  1880. !params.hasOwnProperty('value')) {
  1881. return
  1882. }
  1883. const allParams = Array.isArray(params) ? params : [params]
  1884. allParams.forEach(({id, field, value}) => {
  1885. const rowId = this.options.data.indexOf(this.getRowByUniqueId(id))
  1886. if (rowId === -1) {
  1887. return
  1888. }
  1889. this.options.data[rowId][field] = value
  1890. })
  1891. if (params.reinit === false) {
  1892. return
  1893. }
  1894. this.initSort()
  1895. this.initBody(true)
  1896. }
  1897. showRow (params) {
  1898. this._toggleRow(params, true)
  1899. }
  1900. hideRow (params) {
  1901. this._toggleRow(params, false)
  1902. }
  1903. _toggleRow (params, visible) {
  1904. let row
  1905. if (params.hasOwnProperty('index')) {
  1906. row = this.getData()[params.index]
  1907. } else if (params.hasOwnProperty('uniqueId')) {
  1908. row = this.getRowByUniqueId(params.uniqueId)
  1909. }
  1910. if (!row) {
  1911. return
  1912. }
  1913. const index = Utils.findIndex(this.hiddenRows, row)
  1914. if (!visible && index === -1) {
  1915. this.hiddenRows.push(row)
  1916. } else if (visible && index > -1) {
  1917. this.hiddenRows.splice(index, 1)
  1918. }
  1919. if (visible) {
  1920. this.updatePagination()
  1921. } else {
  1922. this.initBody(true)
  1923. this.initPagination()
  1924. }
  1925. }
  1926. getHiddenRows (show) {
  1927. if (show) {
  1928. this.initHiddenRows()
  1929. this.initBody(true)
  1930. return
  1931. }
  1932. const data = this.getData()
  1933. const rows = []
  1934. for (const row of data) {
  1935. if (this.hiddenRows.includes(row)) {
  1936. rows.push(row)
  1937. }
  1938. }
  1939. this.hiddenRows = rows
  1940. return rows
  1941. }
  1942. showColumn (field) {
  1943. const fields = Array.isArray(field) ? field : [field]
  1944. fields.forEach(field => {
  1945. this._toggleColumn(this.fieldsColumnsIndex[field], true, true)
  1946. })
  1947. }
  1948. hideColumn (field) {
  1949. const fields = Array.isArray(field) ? field : [field]
  1950. fields.forEach(field => {
  1951. this._toggleColumn(this.fieldsColumnsIndex[field], false, true)
  1952. })
  1953. }
  1954. _toggleColumn (index, checked, needUpdate) {
  1955. if (index === -1 || this.columns[index].visible === checked) {
  1956. return
  1957. }
  1958. this.columns[index].visible = checked
  1959. this.initHeader()
  1960. this.initSearch()
  1961. this.initPagination()
  1962. this.initBody()
  1963. if (this.options.showColumns) {
  1964. const $items = this.$toolbar.find('.keep-open input').prop('disabled', false)
  1965. if (needUpdate) {
  1966. $items.filter(Utils.sprintf('[value="%s"]', index)).prop('checked', checked)
  1967. }
  1968. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  1969. $items.filter(':checked').prop('disabled', true)
  1970. }
  1971. }
  1972. }
  1973. getVisibleColumns () {
  1974. return this.columns.filter(({visible}) => visible)
  1975. }
  1976. getHiddenColumns () {
  1977. return this.columns.filter(({visible}) => !visible)
  1978. }
  1979. showAllColumns () {
  1980. this._toggleAllColumns(true)
  1981. }
  1982. hideAllColumns () {
  1983. this._toggleAllColumns(false)
  1984. }
  1985. _toggleAllColumns (visible) {
  1986. for (const column of this.columns.slice().reverse()) {
  1987. if (column.switchable) {
  1988. if (!visible && this.options.showColumns && this.getVisibleColumns().length === this.options.minimumCountColumns) {
  1989. continue
  1990. }
  1991. column.visible = visible
  1992. }
  1993. }
  1994. this.initHeader()
  1995. this.initSearch()
  1996. this.initPagination()
  1997. this.initBody()
  1998. if (this.options.showColumns) {
  1999. const $items = this.$toolbar.find('.keep-open input:not(".toggle-all")').prop('disabled', false)
  2000. if (visible) {
  2001. $items.prop('checked', visible)
  2002. } else {
  2003. $items.get().reverse().forEach((item) => {
  2004. if ($items.filter(':checked').length > this.options.minimumCountColumns) {
  2005. $(item).prop('checked', visible)
  2006. }
  2007. })
  2008. }
  2009. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  2010. $items.filter(':checked').prop('disabled', true)
  2011. }
  2012. }
  2013. }
  2014. mergeCells (options) {
  2015. const row = options.index
  2016. let col = this.getVisibleFields().indexOf(options.field)
  2017. const rowspan = options.rowspan || 1
  2018. const colspan = options.colspan || 1
  2019. let i
  2020. let j
  2021. const $tr = this.$body.find('>tr')
  2022. if (this.options.detailView && !this.options.cardView) {
  2023. col += 1
  2024. }
  2025. const $td = $tr.eq(row).find('>td').eq(col)
  2026. if (row < 0 || col < 0 || row >= this.data.length) {
  2027. return
  2028. }
  2029. for (i = row; i < row + rowspan; i++) {
  2030. for (j = col; j < col + colspan; j++) {
  2031. $tr.eq(i).find('>td').eq(j).hide()
  2032. }
  2033. }
  2034. $td.attr('rowspan', rowspan).attr('colspan', colspan).show()
  2035. }
  2036. checkAll () {
  2037. this._toggleCheckAll(true)
  2038. }
  2039. uncheckAll () {
  2040. this._toggleCheckAll(false)
  2041. }
  2042. _toggleCheckAll (checked) {
  2043. const rowsBefore = this.getSelections()
  2044. this.$selectAll.add(this.$selectAll_).prop('checked', checked)
  2045. this.$selectItem.filter(':enabled').prop('checked', checked)
  2046. this.updateRows()
  2047. const rowsAfter = this.getSelections()
  2048. if (checked) {
  2049. this.trigger('check-all', rowsAfter, rowsBefore)
  2050. return
  2051. }
  2052. this.trigger('uncheck-all', rowsAfter, rowsBefore)
  2053. }
  2054. checkInvert () {
  2055. const $items = this.$selectItem.filter(':enabled')
  2056. let checked = $items.filter(':checked')
  2057. $items.each((i, el) => {
  2058. $(el).prop('checked', !$(el).prop('checked'))
  2059. })
  2060. this.updateRows()
  2061. this.updateSelected()
  2062. this.trigger('uncheck-some', checked)
  2063. checked = this.getSelections()
  2064. this.trigger('check-some', checked)
  2065. }
  2066. check (index) {
  2067. this._toggleCheck(true, index)
  2068. }
  2069. uncheck (index) {
  2070. this._toggleCheck(false, index)
  2071. }
  2072. _toggleCheck (checked, index) {
  2073. const $el = this.$selectItem.filter(`[data-index="${index}"]`)
  2074. const row = this.data[index]
  2075. if (
  2076. $el.is(':radio') ||
  2077. this.options.singleSelect ||
  2078. this.options.multipleSelectRow &&
  2079. !this.multipleSelectRowCtrlKey &&
  2080. !this.multipleSelectRowShiftKey
  2081. ) {
  2082. for (const r of this.options.data) {
  2083. r[this.header.stateField] = false
  2084. }
  2085. this.$selectItem.filter(':checked').not($el).prop('checked', false)
  2086. }
  2087. row[this.header.stateField] = checked
  2088. if (this.options.multipleSelectRow) {
  2089. if (this.multipleSelectRowShiftKey && this.multipleSelectRowLastSelectedIndex >= 0) {
  2090. const indexes = [this.multipleSelectRowLastSelectedIndex, index].sort()
  2091. for (let i = indexes[0] + 1; i < indexes[1]; i++) {
  2092. this.data[i][this.header.stateField] = true
  2093. this.$selectItem.filter(`[data-index="${i}"]`).prop('checked', true)
  2094. }
  2095. }
  2096. this.multipleSelectRowCtrlKey = false
  2097. this.multipleSelectRowShiftKey = false
  2098. this.multipleSelectRowLastSelectedIndex = checked ? index : -1
  2099. }
  2100. $el.prop('checked', checked)
  2101. this.updateSelected()
  2102. this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el)
  2103. }
  2104. checkBy (obj) {
  2105. this._toggleCheckBy(true, obj)
  2106. }
  2107. uncheckBy (obj) {
  2108. this._toggleCheckBy(false, obj)
  2109. }
  2110. _toggleCheckBy (checked, obj) {
  2111. if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
  2112. return
  2113. }
  2114. const rows = []
  2115. this.data.forEach((row, i) => {
  2116. if (!row.hasOwnProperty(obj.field)) {
  2117. return false
  2118. }
  2119. if (obj.values.includes(row[obj.field])) {
  2120. let $el = this.$selectItem.filter(':enabled')
  2121. .filter(Utils.sprintf('[data-index="%s"]', i))
  2122. $el = checked ? $el.not(':checked') : $el.filter(':checked')
  2123. if (!$el.length) {
  2124. return
  2125. }
  2126. $el.prop('checked', checked)
  2127. row[this.header.stateField] = checked
  2128. rows.push(row)
  2129. this.trigger(checked ? 'check' : 'uncheck', row, $el)
  2130. }
  2131. })
  2132. this.updateSelected()
  2133. this.trigger(checked ? 'check-some' : 'uncheck-some', rows)
  2134. }
  2135. refresh (params) {
  2136. if (params && params.url) {
  2137. this.options.url = params.url
  2138. }
  2139. if (params && params.pageNumber) {
  2140. this.options.pageNumber = params.pageNumber
  2141. }
  2142. if (params && params.pageSize) {
  2143. this.options.pageSize = params.pageSize
  2144. }
  2145. this.trigger('refresh', this.initServer(params && params.silent,
  2146. params && params.query, params && params.url))
  2147. }
  2148. destroy () {
  2149. this.$el.insertBefore(this.$container)
  2150. $(this.options.toolbar).insertBefore(this.$el)
  2151. this.$container.next().remove()
  2152. this.$container.remove()
  2153. this.$el.html(this.$el_.html())
  2154. .css('margin-top', '0')
  2155. .attr('class', this.$el_.attr('class') || '') // reset the class
  2156. }
  2157. resetView (params) {
  2158. let padding = 0
  2159. if (params && params.height) {
  2160. this.options.height = params.height
  2161. }
  2162. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  2163. this.$selectItem.length === this.$selectItem.filter(':checked').length)
  2164. this.$tableContainer.toggleClass('has-card-view', this.options.cardView)
  2165. if (!this.options.cardView && this.options.showHeader && this.options.height) {
  2166. this.$tableHeader.show()
  2167. this.resetHeader()
  2168. padding += this.$header.outerHeight(true)
  2169. } else {
  2170. this.$tableHeader.hide()
  2171. this.trigger('post-header')
  2172. }
  2173. if (!this.options.cardView && this.options.showFooter) {
  2174. this.$tableFooter.show()
  2175. this.fitFooter()
  2176. if (this.options.height) {
  2177. padding += this.$tableFooter.outerHeight(true)
  2178. }
  2179. }
  2180. if (this.options.height) {
  2181. const toolbarHeight = this.$toolbar.outerHeight(true)
  2182. const paginationHeight = this.$pagination.outerHeight(true)
  2183. const height = this.options.height - toolbarHeight - paginationHeight
  2184. const tableHeight = this.$tableBody.find('table').outerHeight(true)
  2185. this.$tableContainer.css('height', `${height}px`)
  2186. this.$tableBorder && this.$tableBorder.css('height', `${height - tableHeight - padding - 1}px`)
  2187. }
  2188. if (this.options.cardView) {
  2189. // remove the element css
  2190. this.$el.css('margin-top', '0')
  2191. this.$tableContainer.css('padding-bottom', '0')
  2192. this.$tableFooter.hide()
  2193. } else {
  2194. // Assign the correct sortable arrow
  2195. this.getCaret()
  2196. this.$tableContainer.css('padding-bottom', `${padding}px`)
  2197. }
  2198. this.trigger('reset-view')
  2199. }
  2200. resetWidth () {
  2201. if (this.options.showHeader && this.options.height) {
  2202. this.fitHeader()
  2203. }
  2204. if (this.options.showFooter && !this.options.cardView) {
  2205. this.fitFooter()
  2206. }
  2207. }
  2208. showLoading () {
  2209. this.$tableLoading.css('display', 'flex')
  2210. }
  2211. hideLoading () {
  2212. this.$tableLoading.css('display', 'none')
  2213. }
  2214. togglePagination () {
  2215. this.options.pagination = !this.options.pagination
  2216. const icon = this.options.showButtonIcons ? this.options.pagination ? this.options.icons.paginationSwitchDown : this.options.icons.paginationSwitchUp : ''
  2217. const text = this.options.showButtonText ? this.options.pagination ? this.options.formatPaginationSwitchUp() : this.options.formatPaginationSwitchDown() : ''
  2218. this.$toolbar.find('button[name="paginationSwitch"]')
  2219. .html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, icon) + ' ' + text)
  2220. this.updatePagination()
  2221. }
  2222. toggleFullscreen () {
  2223. this.$el.closest('.bootstrap-table').toggleClass('fullscreen')
  2224. this.resetView()
  2225. }
  2226. toggleView () {
  2227. this.options.cardView = !this.options.cardView
  2228. this.initHeader()
  2229. const icon = this.options.showButtonIcons ? this.options.cardView ? this.options.icons.toggleOn : this.options.icons.toggleOff : ''
  2230. const text = this.options.showButtonText ? this.options.cardView ? this.options.formatToggleOff() : this.options.formatToggleOn() : ''
  2231. this.$toolbar.find('button[name="toggle"]')
  2232. .html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, icon) + ' ' + text)
  2233. this.initBody()
  2234. this.trigger('toggle', this.options.cardView)
  2235. }
  2236. resetSearch (text) {
  2237. const $search = this.$toolbar.find('.search input')
  2238. $search.val(text || '')
  2239. this.onSearch({currentTarget: $search})
  2240. }
  2241. filterBy (columns, options) {
  2242. this.filterOptions = Utils.isEmptyObject(options) ? this.options.filterOptions : $.extend(this.options.filterOptions, options)
  2243. this.filterColumns = Utils.isEmptyObject(columns) ? {} : columns
  2244. this.options.pageNumber = 1
  2245. this.initSearch()
  2246. this.updatePagination()
  2247. }
  2248. scrollTo (params) {
  2249. if (typeof params === 'undefined') {
  2250. return this.$tableBody.scrollTop()
  2251. }
  2252. let options = {unit: 'px', value: 0}
  2253. if (typeof params === 'object') {
  2254. options = Object.assign(options, params)
  2255. } else if (typeof params === 'string' && params === 'bottom') {
  2256. options.value = this.$tableBody[0].scrollHeight
  2257. } else if (typeof params === 'string') {
  2258. options.value = params
  2259. }
  2260. let scrollTo = options.value
  2261. if (options.unit === 'rows') {
  2262. scrollTo = 0
  2263. this.$body.find(`> tr:lt(${options.value})`).each((i, el) => {
  2264. scrollTo += $(el).outerHeight(true)
  2265. })
  2266. }
  2267. this.$tableBody.scrollTop(scrollTo)
  2268. }
  2269. getScrollPosition () {
  2270. return this.scrollTo()
  2271. }
  2272. selectPage (page) {
  2273. if (page > 0 && page <= this.options.totalPages) {
  2274. this.options.pageNumber = page
  2275. this.updatePagination()
  2276. }
  2277. }
  2278. prevPage () {
  2279. if (this.options.pageNumber > 1) {
  2280. this.options.pageNumber--
  2281. this.updatePagination()
  2282. }
  2283. }
  2284. nextPage () {
  2285. if (this.options.pageNumber < this.options.totalPages) {
  2286. this.options.pageNumber++
  2287. this.updatePagination()
  2288. }
  2289. }
  2290. toggleDetailView (index, _columnDetailFormatter) {
  2291. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"]', index))
  2292. if ($tr.next().is('tr.detail-view')) {
  2293. this.collapseRow(index)
  2294. } else {
  2295. this.expandRow(index, _columnDetailFormatter)
  2296. }
  2297. this.resetView()
  2298. }
  2299. expandRow (index, _columnDetailFormatter) {
  2300. const row = this.data[index]
  2301. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"][data-has-detail-view]', index))
  2302. if ($tr.next().is('tr.detail-view')) {
  2303. return
  2304. }
  2305. if (this.options.detailViewIcon) {
  2306. $tr.find('a.detail-icon').html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailClose))
  2307. }
  2308. $tr.after(Utils.sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.children('td').length))
  2309. const $element = $tr.next().find('td')
  2310. const detailFormatter = _columnDetailFormatter || this.options.detailFormatter
  2311. const content = Utils.calculateObjectValue(this.options, detailFormatter, [index, row, $element], '')
  2312. if ($element.length === 1) {
  2313. $element.append(content)
  2314. }
  2315. this.trigger('expand-row', index, row, $element)
  2316. }
  2317. collapseRow (index) {
  2318. const row = this.data[index]
  2319. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"][data-has-detail-view]', index))
  2320. if (!$tr.next().is('tr.detail-view')) {
  2321. return
  2322. }
  2323. if (this.options.detailViewIcon) {
  2324. $tr.find('a.detail-icon').html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailOpen))
  2325. }
  2326. this.trigger('collapse-row', index, row, $tr.next())
  2327. $tr.next().remove()
  2328. }
  2329. expandAllRows () {
  2330. const trs = this.$body.find('> tr[data-index][data-has-detail-view]')
  2331. for (let i = 0; i < trs.length; i++) {
  2332. this.expandRow($(trs[i]).data('index'))
  2333. }
  2334. }
  2335. collapseAllRows () {
  2336. const trs = this.$body.find('> tr[data-index][data-has-detail-view]')
  2337. for (let i = 0; i < trs.length; i++) {
  2338. this.collapseRow($(trs[i]).data('index'))
  2339. }
  2340. }
  2341. updateColumnTitle (params) {
  2342. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('title')) {
  2343. return
  2344. }
  2345. this.columns[this.fieldsColumnsIndex[params.field]].title =
  2346. this.options.escape ? Utils.escapeHTML(params.title) : params.title
  2347. if (this.columns[this.fieldsColumnsIndex[params.field]].visible) {
  2348. const header = this.options.height !== undefined ? this.$tableHeader : this.$header
  2349. header.find('th[data-field]').each((i, el) => {
  2350. if ($(el).data('field') === params.field) {
  2351. $($(el).find('.th-inner')[0]).text(params.title)
  2352. return false
  2353. }
  2354. })
  2355. }
  2356. }
  2357. updateFormatText (formatName, text) {
  2358. if (!/^format/.test(formatName) || !this.options[formatName]) {
  2359. return
  2360. }
  2361. if (typeof text === 'string') {
  2362. this.options[formatName] = () => text
  2363. } else if (typeof text === 'function') {
  2364. this.options[formatName] = text
  2365. }
  2366. this.initToolbar()
  2367. this.initPagination()
  2368. this.initBody()
  2369. }
  2370. }
  2371. BootstrapTable.VERSION = Constants.VERSION
  2372. BootstrapTable.DEFAULTS = Constants.DEFAULTS
  2373. BootstrapTable.LOCALES = Constants.LOCALES
  2374. BootstrapTable.COLUMN_DEFAULTS = Constants.COLUMN_DEFAULTS
  2375. BootstrapTable.METHODS = Constants.METHODS
  2376. BootstrapTable.EVENTS = Constants.EVENTS
  2377. // BOOTSTRAP TABLE PLUGIN DEFINITION
  2378. // =======================
  2379. $.BootstrapTable = BootstrapTable
  2380. $.fn.bootstrapTable = function (option, ...args) {
  2381. let value
  2382. this.each((i, el) => {
  2383. let data = $(el).data('bootstrap.table')
  2384. const options = $.extend({}, BootstrapTable.DEFAULTS, $(el).data(),
  2385. typeof option === 'object' && option)
  2386. if (typeof option === 'string') {
  2387. if (!Constants.METHODS.includes(option)) {
  2388. throw new Error(`Unknown method: ${option}`)
  2389. }
  2390. if (!data) {
  2391. return
  2392. }
  2393. value = data[option](...args)
  2394. if (option === 'destroy') {
  2395. $(el).removeData('bootstrap.table')
  2396. }
  2397. }
  2398. if (!data) {
  2399. $(el).data('bootstrap.table', (data = new $.BootstrapTable(el, options)))
  2400. }
  2401. })
  2402. return typeof value === 'undefined' ? this : value
  2403. }
  2404. $.fn.bootstrapTable.Constructor = BootstrapTable
  2405. $.fn.bootstrapTable.theme = Constants.THEME
  2406. $.fn.bootstrapTable.VERSION = Constants.VERSION
  2407. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS
  2408. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS
  2409. $.fn.bootstrapTable.events = BootstrapTable.EVENTS
  2410. $.fn.bootstrapTable.locales = BootstrapTable.LOCALES
  2411. $.fn.bootstrapTable.methods = BootstrapTable.METHODS
  2412. $.fn.bootstrapTable.utils = Utils
  2413. // BOOTSTRAP TABLE INIT
  2414. // =======================
  2415. $(() => {
  2416. $('[data-toggle="table"]').bootstrapTable()
  2417. })
  2418. export default BootstrapTable