bootstrap-table.js 103 KB

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