bootstrap-table.js 106 KB

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