bootstrap-table.js 86 KB

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