bootstrap-table.js 107 KB

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