bootstrap-table.js 107 KB

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