bootstrap-table.js 102 KB

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