bootstrap-table.js 100 KB

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