bootstrap-table.js 102 KB

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