bootstrap-table.js 107 KB

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