bootstrap-table.js 92 KB

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