bootstrap-table.js 99 KB

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