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