bootstrap-table.js 88 KB

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