bootstrap-table.js 105 KB

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