bootstrap-table.js 83 KB

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