bootstrap-table.js 99 KB

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