bootstrap-table.js 106 KB

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