bootstrap-table.js 105 KB

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