bootstrap-table.js 91 KB

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