bootstrap-table.js 95 KB

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