bootstrap-table.js 106 KB

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