bootstrap-table.js 96 KB

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