bootstrap-table.js 97 KB

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