bootstrap-table.js 87 KB

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