bootstrap-table.js 102 KB

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