bootstrap-table.js 94 KB

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