bootstrap-table.js 105 KB

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