bootstrap-table.js 104 KB

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