bootstrap-table.js 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534
  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * version: 1.23.2
  4. * https://github.com/wenzhixin/bootstrap-table/
  5. */
  6. import Constants from './constants/index.js'
  7. import Utils from './utils/index.js'
  8. import VirtualScroll from './virtual-scroll/index.js'
  9. class BootstrapTable {
  10. constructor (el, options) {
  11. this.options = options
  12. this.$el = $(el)
  13. this.$el_ = this.$el.clone()
  14. this.timeoutId_ = 0
  15. this.timeoutFooter_ = 0
  16. }
  17. init () {
  18. this.initConstants()
  19. this.initLocale()
  20. this.initContainer()
  21. this.initTable()
  22. this.initHeader()
  23. this.initData()
  24. this.initHiddenRows()
  25. this.initToolbar()
  26. this.initPagination()
  27. this.initBody()
  28. this.initSearchText()
  29. this.initServer()
  30. }
  31. initConstants () {
  32. const opts = this.options
  33. this.constants = Constants.CONSTANTS
  34. this.constants.theme = $.fn.bootstrapTable.theme
  35. this.constants.dataToggle = this.constants.html.dataToggle || 'data-toggle'
  36. // init iconsPrefix and icons
  37. const iconsPrefix = Utils.getIconsPrefix($.fn.bootstrapTable.theme)
  38. 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] = 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. }
  923. if (typeof value === 'string' || typeof value === 'number') {
  924. if (
  925. this.options.strictSearch && `${value}`.toLowerCase() === searchText ||
  926. this.options.regexSearch && Utils.regexCompare(value, rawSearchText)
  927. ) {
  928. return true
  929. }
  930. const largerSmallerEqualsRegex = /(?:(<=|=>|=<|>=|>|<)(?:\s+)?(-?\d+)?|(-?\d+)?(\s+)?(<=|=>|=<|>=|>|<))/gm
  931. const matches = largerSmallerEqualsRegex.exec(this.searchText)
  932. let comparisonCheck = false
  933. if (matches) {
  934. const operator = matches[1] || `${matches[5]}l`
  935. const comparisonValue = matches[2] || matches[3]
  936. const int = parseInt(value, 10)
  937. const comparisonInt = parseInt(comparisonValue, 10)
  938. switch (operator) {
  939. case '>':
  940. case '<l':
  941. comparisonCheck = int > comparisonInt
  942. break
  943. case '<':
  944. case '>l':
  945. comparisonCheck = int < comparisonInt
  946. break
  947. case '<=':
  948. case '=<':
  949. case '>=l':
  950. case '=>l':
  951. comparisonCheck = int <= comparisonInt
  952. break
  953. case '>=':
  954. case '=>':
  955. case '<=l':
  956. case '=<l':
  957. comparisonCheck = int >= comparisonInt
  958. break
  959. default:
  960. break
  961. }
  962. }
  963. if (comparisonCheck || `${value}`.toLowerCase().includes(searchText)) {
  964. return true
  965. }
  966. }
  967. }
  968. return false
  969. }) : this.data
  970. if (this.options.sortReset) {
  971. this.unsortedData = [...this.data]
  972. }
  973. this.initSort()
  974. }
  975. }
  976. initPagination () {
  977. const opts = this.options
  978. if (!opts.pagination) {
  979. this.$pagination.hide()
  980. return
  981. }
  982. this.$pagination.show()
  983. const html = []
  984. let allSelected = false
  985. let i
  986. let from
  987. let to
  988. let $pageList
  989. let $pre
  990. let $next
  991. let $number
  992. const data = this.getData({ includeHiddenRows: false })
  993. let pageList = opts.pageList
  994. if (typeof pageList === 'string') {
  995. pageList = pageList.replace(/\[|\]| /g, '').toLowerCase().split(',')
  996. }
  997. pageList = pageList.map(value => {
  998. if (typeof value === 'string') {
  999. return value.toLowerCase() === opts.formatAllRows().toLowerCase() ||
  1000. ['all', 'unlimited'].includes(value.toLowerCase()) ? opts.formatAllRows() : +value
  1001. }
  1002. return value
  1003. })
  1004. this.paginationParts = opts.paginationParts
  1005. if (typeof this.paginationParts === 'string') {
  1006. this.paginationParts = this.paginationParts.replace(/\[|\]| |'/g, '').split(',')
  1007. }
  1008. if (opts.sidePagination !== 'server') {
  1009. opts.totalRows = data.length
  1010. }
  1011. this.totalPages = 0
  1012. if (opts.totalRows) {
  1013. if (opts.pageSize === opts.formatAllRows()) {
  1014. opts.pageSize = opts.totalRows
  1015. allSelected = true
  1016. }
  1017. this.totalPages = ~~((opts.totalRows - 1) / opts.pageSize) + 1
  1018. opts.totalPages = this.totalPages
  1019. }
  1020. if (this.totalPages > 0 && opts.pageNumber > this.totalPages) {
  1021. opts.pageNumber = this.totalPages
  1022. }
  1023. this.pageFrom = (opts.pageNumber - 1) * opts.pageSize + 1
  1024. this.pageTo = opts.pageNumber * opts.pageSize
  1025. if (this.pageTo > opts.totalRows) {
  1026. this.pageTo = opts.totalRows
  1027. }
  1028. if (this.options.pagination && this.options.sidePagination !== 'server') {
  1029. this.options.totalNotFiltered = this.options.data.length
  1030. }
  1031. if (!this.options.showExtendedPagination) {
  1032. this.options.totalNotFiltered = undefined
  1033. }
  1034. if (this.paginationParts.includes('pageInfo') || this.paginationParts.includes('pageInfoShort') || this.paginationParts.includes('pageSize')) {
  1035. html.push(`<div class="${this.constants.classes.pull}-${opts.paginationDetailHAlign} pagination-detail">`)
  1036. }
  1037. if (this.paginationParts.includes('pageInfo') || this.paginationParts.includes('pageInfoShort')) {
  1038. const totalRows = this.options.totalRows +
  1039. (this.options.sidePagination === 'client' &&
  1040. this.options.paginationLoadMore &&
  1041. !this._paginationLoaded ? ' +' : '')
  1042. const paginationInfo = this.paginationParts.includes('pageInfoShort') ?
  1043. opts.formatDetailPagination(totalRows) :
  1044. opts.formatShowingRows(this.pageFrom, this.pageTo, totalRows, opts.totalNotFiltered)
  1045. html.push(`<span class="pagination-info">
  1046. ${paginationInfo}
  1047. </span>`)
  1048. }
  1049. if (this.paginationParts.includes('pageSize')) {
  1050. html.push('<div class="page-list">')
  1051. const pageNumber = [
  1052. `<div class="${this.constants.classes.paginationDropdown}">
  1053. <button class="${this.constants.buttonsClass} dropdown-toggle" type="button" ${this.constants.dataToggle}="dropdown">
  1054. <span class="page-size">
  1055. ${allSelected ? opts.formatAllRows() : opts.pageSize}
  1056. </span>
  1057. ${this.constants.html.dropdownCaret}
  1058. </button>
  1059. ${this.constants.html.pageDropdown[0]}`
  1060. ]
  1061. pageList.forEach((page, i) => {
  1062. if (!opts.smartDisplay || i === 0 || pageList[i - 1] < opts.totalRows || page === opts.formatAllRows()) {
  1063. let active
  1064. if (allSelected) {
  1065. active = page === opts.formatAllRows() ? this.constants.classes.dropdownActive : ''
  1066. } else {
  1067. active = page === opts.pageSize ? this.constants.classes.dropdownActive : ''
  1068. }
  1069. pageNumber.push(Utils.sprintf(this.constants.html.pageDropdownItem, active, page))
  1070. }
  1071. })
  1072. pageNumber.push(`${this.constants.html.pageDropdown[1]}</div>`)
  1073. html.push(opts.formatRecordsPerPage(pageNumber.join('')))
  1074. }
  1075. if (this.paginationParts.includes('pageInfo') || this.paginationParts.includes('pageInfoShort') || this.paginationParts.includes('pageSize')) {
  1076. html.push('</div></div>')
  1077. }
  1078. if (this.paginationParts.includes('pageList')) {
  1079. html.push(`<div class="${this.constants.classes.pull}-${opts.paginationHAlign} pagination">`,
  1080. Utils.sprintf(this.constants.html.pagination[0], Utils.sprintf(' pagination-%s', opts.iconSize)),
  1081. Utils.sprintf(this.constants.html.paginationItem, ' page-pre', opts.formatSRPaginationPreText(), opts.paginationPreText))
  1082. if (this.totalPages < opts.paginationSuccessivelySize) {
  1083. from = 1
  1084. to = this.totalPages
  1085. } else {
  1086. from = opts.pageNumber - opts.paginationPagesBySide
  1087. to = from + opts.paginationPagesBySide * 2
  1088. }
  1089. if (opts.pageNumber < opts.paginationSuccessivelySize - 1) {
  1090. to = opts.paginationSuccessivelySize
  1091. }
  1092. if (opts.paginationSuccessivelySize > this.totalPages - from) {
  1093. from = from - (opts.paginationSuccessivelySize - (this.totalPages - from)) + 1
  1094. }
  1095. if (from < 1) {
  1096. from = 1
  1097. }
  1098. if (to > this.totalPages) {
  1099. to = this.totalPages
  1100. }
  1101. const middleSize = Math.round(opts.paginationPagesBySide / 2)
  1102. const pageItem = (i, classes = '') => Utils.sprintf(this.constants.html.paginationItem,
  1103. classes + (i === opts.pageNumber ? ` ${this.constants.classes.paginationActive}` : ''), opts.formatSRPaginationPageText(i), i)
  1104. if (from > 1) {
  1105. let max = opts.paginationPagesBySide
  1106. if (max >= from) max = from - 1
  1107. for (i = 1; i <= max; i++) {
  1108. html.push(pageItem(i))
  1109. }
  1110. if (from - 1 === max + 1) {
  1111. i = from - 1
  1112. html.push(pageItem(i))
  1113. } else if (from - 1 > max) {
  1114. if (
  1115. from - opts.paginationPagesBySide * 2 > opts.paginationPagesBySide &&
  1116. opts.paginationUseIntermediate
  1117. ) {
  1118. i = Math.round((from - middleSize) / 2 + middleSize)
  1119. html.push(pageItem(i, ' page-intermediate'))
  1120. } else {
  1121. html.push(Utils.sprintf(this.constants.html.paginationItem,
  1122. ' page-first-separator disabled', '', '...'))
  1123. }
  1124. }
  1125. }
  1126. for (i = from; i <= to; i++) {
  1127. html.push(pageItem(i))
  1128. }
  1129. if (this.totalPages > to) {
  1130. let min = this.totalPages - (opts.paginationPagesBySide - 1)
  1131. if (to >= min) min = to + 1
  1132. if (to + 1 === min - 1) {
  1133. i = to + 1
  1134. html.push(pageItem(i))
  1135. } else if (min > to + 1) {
  1136. if (
  1137. this.totalPages - to > opts.paginationPagesBySide * 2 &&
  1138. opts.paginationUseIntermediate
  1139. ) {
  1140. i = Math.round((this.totalPages - middleSize - to) / 2 + to)
  1141. html.push(pageItem(i, ' page-intermediate'))
  1142. } else {
  1143. html.push(Utils.sprintf(this.constants.html.paginationItem,
  1144. ' page-last-separator disabled', '', '...'))
  1145. }
  1146. }
  1147. for (i = min; i <= this.totalPages; i++) {
  1148. html.push(pageItem(i))
  1149. }
  1150. }
  1151. html.push(Utils.sprintf(this.constants.html.paginationItem, ' page-next', opts.formatSRPaginationNextText(), opts.paginationNextText))
  1152. html.push(this.constants.html.pagination[1], '</div>')
  1153. }
  1154. this.$pagination.html(html.join(''))
  1155. const dropupClass = ['bottom', 'both'].includes(opts.paginationVAlign) ?
  1156. ` ${this.constants.classes.dropup}` : ''
  1157. this.$pagination.last().find('.page-list > div').addClass(dropupClass)
  1158. if (!opts.onlyInfoPagination) {
  1159. $pageList = this.$pagination.find('.page-list a')
  1160. $pre = this.$pagination.find('.page-pre')
  1161. $next = this.$pagination.find('.page-next')
  1162. $number = this.$pagination.find('.page-item').not('.page-next, .page-pre, .page-last-separator, .page-first-separator')
  1163. if (this.totalPages <= 1) {
  1164. this.$pagination.find('div.pagination').hide()
  1165. }
  1166. if (opts.smartDisplay) {
  1167. if (pageList.length < 2 || opts.totalRows <= pageList[0]) {
  1168. this.$pagination.find('div.page-list').hide()
  1169. }
  1170. }
  1171. // when data is empty, hide the pagination
  1172. this.$pagination[this.getData().length ? 'show' : 'hide']()
  1173. if (!opts.paginationLoop) {
  1174. if (opts.pageNumber === 1) {
  1175. $pre.addClass('disabled')
  1176. }
  1177. if (opts.pageNumber === this.totalPages) {
  1178. $next.addClass('disabled')
  1179. }
  1180. }
  1181. if (allSelected) {
  1182. opts.pageSize = opts.formatAllRows()
  1183. }
  1184. $pageList.off('click').on('click', e => this.onPageListChange(e))
  1185. $pre.off('click').on('click', e => this.onPagePre(e))
  1186. $next.off('click').on('click', e => this.onPageNext(e))
  1187. $number.off('click').on('click', e => this.onPageNumber(e))
  1188. }
  1189. }
  1190. updatePagination (event) {
  1191. // Fix #171: IE disabled button can be clicked bug.
  1192. if (event && $(event.currentTarget).hasClass('disabled')) {
  1193. return
  1194. }
  1195. if (!this.options.maintainMetaData) {
  1196. this.resetRows()
  1197. }
  1198. this.initPagination()
  1199. this.trigger('page-change', this.options.pageNumber, this.options.pageSize)
  1200. if (
  1201. this.options.sidePagination === 'server' ||
  1202. this.options.sidePagination === 'client' &&
  1203. this.options.paginationLoadMore &&
  1204. !this._paginationLoaded &&
  1205. this.options.pageNumber === this.totalPages
  1206. ) {
  1207. this.initServer()
  1208. } else {
  1209. this.initBody()
  1210. }
  1211. }
  1212. onPageListChange (event) {
  1213. event.preventDefault()
  1214. const $this = $(event.currentTarget)
  1215. $this.parent().addClass(this.constants.classes.dropdownActive)
  1216. .siblings().removeClass(this.constants.classes.dropdownActive)
  1217. this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase() ?
  1218. this.options.formatAllRows() : +$this.text()
  1219. this.$toolbar.find('.page-size').text(this.options.pageSize)
  1220. this.updatePagination(event)
  1221. return false
  1222. }
  1223. onPagePre (event) {
  1224. if ($(event.target).hasClass('disabled')) {
  1225. return
  1226. }
  1227. event.preventDefault()
  1228. if (this.options.pageNumber - 1 === 0) {
  1229. this.options.pageNumber = this.options.totalPages
  1230. } else {
  1231. this.options.pageNumber--
  1232. }
  1233. this.updatePagination(event)
  1234. return false
  1235. }
  1236. onPageNext (event) {
  1237. if ($(event.target).hasClass('disabled')) {
  1238. return
  1239. }
  1240. event.preventDefault()
  1241. if (this.options.pageNumber + 1 > this.options.totalPages) {
  1242. this.options.pageNumber = 1
  1243. } else {
  1244. this.options.pageNumber++
  1245. }
  1246. this.updatePagination(event)
  1247. return false
  1248. }
  1249. onPageNumber (event) {
  1250. event.preventDefault()
  1251. if (this.options.pageNumber === +$(event.currentTarget).text()) {
  1252. return
  1253. }
  1254. this.options.pageNumber = +$(event.currentTarget).text()
  1255. this.updatePagination(event)
  1256. return false
  1257. }
  1258. // eslint-disable-next-line no-unused-vars
  1259. initRow (item, i, data, trFragments) {
  1260. const html = []
  1261. let style = {}
  1262. const csses = []
  1263. let data_ = ''
  1264. let attributes = {}
  1265. const htmlAttributes = []
  1266. if (Utils.findIndex(this.hiddenRows, item) > -1) {
  1267. return
  1268. }
  1269. style = Utils.calculateObjectValue(this.options, this.options.rowStyle, [item, i], style)
  1270. if (style && style.css) {
  1271. for (const [key, value] of Object.entries(style.css)) {
  1272. csses.push(`${key}: ${value}`)
  1273. }
  1274. }
  1275. attributes = Utils.calculateObjectValue(this.options,
  1276. this.options.rowAttributes, [item, i], attributes)
  1277. if (attributes) {
  1278. for (const [key, value] of Object.entries(attributes)) {
  1279. htmlAttributes.push(`${key}="${Utils.escapeHTML(value)}"`)
  1280. }
  1281. }
  1282. if (item._data && !Utils.isEmptyObject(item._data)) {
  1283. for (const [k, v] of Object.entries(item._data)) {
  1284. // ignore data-index
  1285. if (k === 'index') {
  1286. return
  1287. }
  1288. data_ += ` data-${k}='${typeof v === 'object' ? JSON.stringify(v) : v}'`
  1289. }
  1290. }
  1291. html.push('<tr',
  1292. Utils.sprintf(' %s', htmlAttributes.length ? htmlAttributes.join(' ') : undefined),
  1293. Utils.sprintf(' id="%s"', Array.isArray(item) ? undefined : item._id),
  1294. Utils.sprintf(' class="%s"', style.classes || (Array.isArray(item) ? undefined : item._class)),
  1295. Utils.sprintf(' style="%s"', Array.isArray(item) ? undefined : item._style),
  1296. ` data-index="${i}"`,
  1297. Utils.sprintf(' data-uniqueid="%s"', Utils.getItemField(item, this.options.uniqueId, false)),
  1298. Utils.sprintf(' data-has-detail-view="%s"', this.options.detailView && Utils.calculateObjectValue(null, this.options.detailFilter, [i, item]) ? 'true' : undefined),
  1299. Utils.sprintf('%s', data_),
  1300. '>'
  1301. )
  1302. if (this.options.cardView) {
  1303. html.push(`<td colspan="${this.header.fields.length}"><div class="card-views">`)
  1304. }
  1305. let detailViewTemplate = ''
  1306. if (Utils.hasDetailViewIcon(this.options)) {
  1307. detailViewTemplate = '<td>'
  1308. if (Utils.calculateObjectValue(null, this.options.detailFilter, [i, item])) {
  1309. detailViewTemplate += `
  1310. <a class="detail-icon" href="#">
  1311. ${Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailOpen)}
  1312. </a>
  1313. `
  1314. }
  1315. detailViewTemplate += '</td>'
  1316. }
  1317. if (detailViewTemplate && this.options.detailViewAlign !== 'right') {
  1318. html.push(detailViewTemplate)
  1319. }
  1320. this.header.fields.forEach((field, j) => {
  1321. const column = this.columns[j]
  1322. let text = ''
  1323. const value_ = Utils.getItemField(item, field, this.options.escape, column.escape)
  1324. let value = ''
  1325. let type = ''
  1326. let cellStyle = {}
  1327. let id_ = ''
  1328. let class_ = this.header.classes[j]
  1329. let style_ = ''
  1330. let styleToAdd_ = ''
  1331. let data_ = ''
  1332. let rowspan_ = ''
  1333. let colspan_ = ''
  1334. let title_ = ''
  1335. if ((this.fromHtml || this.autoMergeCells) && typeof value_ === 'undefined') {
  1336. if (!column.checkbox && !column.radio) {
  1337. return
  1338. }
  1339. }
  1340. if (!column.visible) {
  1341. return
  1342. }
  1343. if (this.options.cardView && !column.cardVisible) {
  1344. return
  1345. }
  1346. // Style concat
  1347. if (csses.concat([this.header.styles[j]]).length) {
  1348. styleToAdd_ += `${csses.concat([this.header.styles[j]]).join('; ')}`
  1349. }
  1350. if (item[`_${field}_style`]) {
  1351. styleToAdd_ += `${item[`_${field}_style`]}`
  1352. }
  1353. if (styleToAdd_) {
  1354. style_ = ` style="${styleToAdd_}"`
  1355. }
  1356. // Style concat
  1357. // handle id and class of td
  1358. if (item[`_${field}_id`]) {
  1359. id_ = Utils.sprintf(' id="%s"', item[`_${field}_id`])
  1360. }
  1361. if (item[`_${field}_class`]) {
  1362. class_ = Utils.sprintf(' class="%s"', item[`_${field}_class`])
  1363. }
  1364. if (item[`_${field}_rowspan`]) {
  1365. rowspan_ = Utils.sprintf(' rowspan="%s"', item[`_${field}_rowspan`])
  1366. }
  1367. if (item[`_${field}_colspan`]) {
  1368. colspan_ = Utils.sprintf(' colspan="%s"', item[`_${field}_colspan`])
  1369. }
  1370. if (item[`_${field}_title`]) {
  1371. title_ = Utils.sprintf(' title="%s"', item[`_${field}_title`])
  1372. }
  1373. cellStyle = Utils.calculateObjectValue(this.header,
  1374. this.header.cellStyles[j], [value_, item, i, field], cellStyle)
  1375. if (cellStyle.classes) {
  1376. class_ = ` class="${cellStyle.classes}"`
  1377. }
  1378. if (cellStyle.css) {
  1379. const csses_ = []
  1380. for (const [key, value] of Object.entries(cellStyle.css)) {
  1381. csses_.push(`${key}: ${value}`)
  1382. }
  1383. style_ = ` style="${csses_.concat(this.header.styles[j]).join('; ')}"`
  1384. }
  1385. value = Utils.calculateObjectValue(column,
  1386. this.header.formatters[j], [value_, item, i, field], value_)
  1387. if (!(column.checkbox || column.radio)) {
  1388. value = typeof value === 'undefined' || value === null ?
  1389. this.options.undefinedText : value
  1390. }
  1391. if (
  1392. column.searchable &&
  1393. this.searchText &&
  1394. this.options.searchHighlight &&
  1395. !(column.checkbox || column.radio)
  1396. ) {
  1397. let searchText = this.searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  1398. if (this.options.searchAccentNeutralise) {
  1399. const indexRegex = new RegExp(`${Utils.normalizeAccent(searchText)}`, 'gmi')
  1400. const match = indexRegex.exec(Utils.normalizeAccent(value))
  1401. if (match) {
  1402. searchText = value.substring(match.index, match.index + searchText.length)
  1403. }
  1404. }
  1405. const defValue = Utils.replaceSearchMark(value, searchText)
  1406. value = Utils.calculateObjectValue(column, column.searchHighlightFormatter,
  1407. [value, this.searchText], defValue)
  1408. }
  1409. if (item[`_${field}_data`] && !Utils.isEmptyObject(item[`_${field}_data`])) {
  1410. for (const [k, v] of Object.entries(item[`_${field}_data`])) {
  1411. // ignore data-index
  1412. if (k === 'index') {
  1413. return
  1414. }
  1415. data_ += ` data-${k}="${v}"`
  1416. }
  1417. }
  1418. if (column.checkbox || column.radio) {
  1419. type = column.checkbox ? 'checkbox' : type
  1420. type = column.radio ? 'radio' : type
  1421. const c = column['class'] || ''
  1422. const isChecked = Utils.isObject(value) && value.hasOwnProperty('checked') ?
  1423. value.checked : (value === true || value_) && value !== false
  1424. const isDisabled = !column.checkboxEnabled || value && value.disabled
  1425. text = [
  1426. this.options.cardView ?
  1427. `<div class="card-view ${c}">` :
  1428. `<td class="bs-checkbox ${c}"${class_}${style_}>`,
  1429. `<label>
  1430. <input
  1431. data-index="${i}"
  1432. name="${this.options.selectItemName}"
  1433. type="${type}"
  1434. ${Utils.sprintf('value="%s"', item[this.options.idField])}
  1435. ${Utils.sprintf('checked="%s"', isChecked ? 'checked' : undefined)}
  1436. ${Utils.sprintf('disabled="%s"', isDisabled ? 'disabled' : undefined)} />
  1437. <span></span>
  1438. </label>`,
  1439. this.header.formatters[j] && typeof value === 'string' ? value : '',
  1440. this.options.cardView ? '</div>' : '</td>'
  1441. ].join('')
  1442. item[this.header.stateField] = value === true || (!!value_ || value && value.checked)
  1443. } else if (this.options.cardView) {
  1444. const cardTitle = this.options.showHeader ?
  1445. `<span class="card-view-title ${cellStyle.classes || ''}"${style_}>${Utils.getFieldTitle(this.columns, field)}</span>` : ''
  1446. text = `<div class="card-view">${cardTitle}<span class="card-view-value ${cellStyle.classes || ''}"${style_}>${value}</span></div>`
  1447. if (this.options.smartDisplay && value === '') {
  1448. text = '<div class="card-view"></div>'
  1449. }
  1450. } else {
  1451. text = `<td${id_}${class_}${style_}${data_}${rowspan_}${colspan_}${title_}>${value}</td>`
  1452. }
  1453. html.push(text)
  1454. })
  1455. if (detailViewTemplate && this.options.detailViewAlign === 'right') {
  1456. html.push(detailViewTemplate)
  1457. }
  1458. if (this.options.cardView) {
  1459. html.push('</div></td>')
  1460. }
  1461. html.push('</tr>')
  1462. return html.join('')
  1463. }
  1464. initBody (fixedScroll, updatedUid) {
  1465. const data = this.getData()
  1466. this.trigger('pre-body', data)
  1467. this.$body = this.$el.find('>tbody')
  1468. if (!this.$body.length) {
  1469. this.$body = $('<tbody></tbody>').appendTo(this.$el)
  1470. }
  1471. // Fix #389 Bootstrap-table-flatJSON is not working
  1472. if (!this.options.pagination || this.options.sidePagination === 'server') {
  1473. this.pageFrom = 1
  1474. this.pageTo = data.length
  1475. }
  1476. const rows = []
  1477. const trFragments = $(document.createDocumentFragment())
  1478. let hasTr = false
  1479. const toExpand = []
  1480. this.autoMergeCells = Utils.checkAutoMergeCells(data.slice(this.pageFrom - 1, this.pageTo))
  1481. for (let i = this.pageFrom - 1; i < this.pageTo; i++) {
  1482. const item = data[i]
  1483. let tr = this.initRow(item, i, data, trFragments)
  1484. hasTr = hasTr || !!tr
  1485. if (tr && typeof tr === 'string') {
  1486. const uniqueId = this.options.uniqueId
  1487. if (uniqueId && item.hasOwnProperty(uniqueId)) {
  1488. const itemUniqueId = item[uniqueId]
  1489. const oldTr = this.$body.find(Utils.sprintf('> tr[data-uniqueid="%s"][data-has-detail-view]', itemUniqueId))
  1490. const oldTrNext = oldTr.next()
  1491. if (oldTrNext.is('tr.detail-view')) {
  1492. toExpand.push(i)
  1493. if (!updatedUid || itemUniqueId !== updatedUid) {
  1494. tr += oldTrNext[0].outerHTML
  1495. }
  1496. }
  1497. }
  1498. if (!this.options.virtualScroll) {
  1499. trFragments.append(tr)
  1500. } else {
  1501. rows.push(tr)
  1502. }
  1503. }
  1504. }
  1505. this.$el.removeAttr('role')
  1506. // show no records
  1507. if (!hasTr) {
  1508. this.$body.html(`<tr class="no-records-found">${Utils.sprintf('<td colspan="%s">%s</td>',
  1509. this.getVisibleFields().length + Utils.getDetailViewIndexOffset(this.options),
  1510. this.options.formatNoMatches())}</tr>`)
  1511. this.$el.attr('role', 'presentation')
  1512. } else if (!this.options.virtualScroll) {
  1513. this.$body.html(trFragments)
  1514. } else {
  1515. if (this.virtualScroll) {
  1516. this.virtualScroll.destroy()
  1517. }
  1518. this.virtualScroll = new VirtualScroll({
  1519. rows,
  1520. fixedScroll,
  1521. scrollEl: this.$tableBody[0],
  1522. contentEl: this.$body[0],
  1523. itemHeight: this.options.virtualScrollItemHeight,
  1524. callback: (startIndex, endIndex) => {
  1525. this.fitHeader()
  1526. this.initBodyEvent()
  1527. this.trigger('virtual-scroll', startIndex, endIndex)
  1528. }
  1529. })
  1530. }
  1531. toExpand.forEach(index => {
  1532. this.expandRow(index)
  1533. })
  1534. if (!fixedScroll) {
  1535. this.scrollTo(0)
  1536. }
  1537. this.initBodyEvent()
  1538. this.initFooter()
  1539. this.resetView()
  1540. this.updateSelected()
  1541. if (this.options.sidePagination !== 'server') {
  1542. this.options.totalRows = data.length
  1543. }
  1544. this.trigger('post-body', data)
  1545. }
  1546. initBodyEvent () {
  1547. // click to select by column
  1548. this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', e => {
  1549. const $td = $(e.currentTarget)
  1550. if (
  1551. $td.find('.detail-icon').length ||
  1552. $td.index() - Utils.getDetailViewIndexOffset(this.options) < 0
  1553. ) {
  1554. return
  1555. }
  1556. const $tr = $td.parent()
  1557. const $cardViewArr = $(e.target).parents('.card-views').children()
  1558. const $cardViewTarget = $(e.target).parents('.card-view')
  1559. const rowIndex = $tr.data('index')
  1560. const item = this.data[rowIndex]
  1561. const index = this.options.cardView ? $cardViewArr.index($cardViewTarget) : $td[0].cellIndex
  1562. const fields = this.getVisibleFields()
  1563. const field = fields[index - Utils.getDetailViewIndexOffset(this.options)]
  1564. const column = this.columns[this.fieldsColumnsIndex[field]]
  1565. const value = Utils.getItemField(item, field, this.options.escape, column.escape)
  1566. this.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td)
  1567. this.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr, field)
  1568. // if click to select - then trigger the checkbox/radio click
  1569. if (
  1570. e.type === 'click' &&
  1571. this.options.clickToSelect &&
  1572. column.clickToSelect &&
  1573. !Utils.calculateObjectValue(this.options, this.options.ignoreClickToSelectOn, [e.target])
  1574. ) {
  1575. const $selectItem = $tr.find(Utils.sprintf('[name="%s"]', this.options.selectItemName))
  1576. if ($selectItem.length) {
  1577. $selectItem[0].click()
  1578. }
  1579. }
  1580. if (e.type === 'click' && this.options.detailViewByClick) {
  1581. this.toggleDetailView(rowIndex, this.header.detailFormatters[this.fieldsColumnsIndex[field]])
  1582. }
  1583. }).off('mousedown').on('mousedown', e => {
  1584. // https://github.com/jquery/jquery/issues/1741
  1585. this.multipleSelectRowCtrlKey = e.ctrlKey || e.metaKey
  1586. this.multipleSelectRowShiftKey = e.shiftKey
  1587. })
  1588. this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', e => {
  1589. e.preventDefault()
  1590. this.toggleDetailView($(e.currentTarget).parent().parent().data('index'))
  1591. return false
  1592. })
  1593. this.$selectItem = this.$body.find(Utils.sprintf('[name="%s"]', this.options.selectItemName))
  1594. this.$selectItem.off('click').on('click', e => {
  1595. e.stopImmediatePropagation()
  1596. const $this = $(e.currentTarget)
  1597. this._toggleCheck($this.prop('checked'), $this.data('index'))
  1598. })
  1599. this.header.events.forEach((_events, i) => {
  1600. let events = _events
  1601. if (!events) {
  1602. return
  1603. }
  1604. // fix bug, if events is defined with namespace
  1605. if (typeof events === 'string') {
  1606. events = Utils.calculateObjectValue(null, events)
  1607. }
  1608. if (!events) {
  1609. throw new Error(`Unknown event in the scope: ${_events}`)
  1610. }
  1611. const field = this.header.fields[i]
  1612. let fieldIndex = this.getVisibleFields().indexOf(field)
  1613. if (fieldIndex === -1) {
  1614. return
  1615. }
  1616. fieldIndex += Utils.getDetailViewIndexOffset(this.options)
  1617. for (const key in events) {
  1618. if (!events.hasOwnProperty(key)) {
  1619. continue
  1620. }
  1621. const event = events[key]
  1622. this.$body.find('>tr:not(.no-records-found)').each((i, tr) => {
  1623. const $tr = $(tr)
  1624. const $td = $tr.find(this.options.cardView ? '.card-views>.card-view' : '>td').eq(fieldIndex)
  1625. const index = key.indexOf(' ')
  1626. const name = key.substring(0, index)
  1627. const el = key.substring(index + 1)
  1628. $td.find(el).off(name).on(name, e => {
  1629. const index = $tr.data('index')
  1630. const row = this.data[index]
  1631. const value = row[field]
  1632. event.apply(this, [e, value, row, index])
  1633. })
  1634. })
  1635. }
  1636. })
  1637. }
  1638. initServer (silent) {
  1639. let data = {}
  1640. const index = this.header.fields.indexOf(this.options.sortName)
  1641. let params = {
  1642. searchText: this.searchText,
  1643. sortName: this.options.sortName,
  1644. sortOrder: this.options.sortOrder
  1645. }
  1646. if (this.header.sortNames[index]) {
  1647. params.sortName = this.header.sortNames[index]
  1648. }
  1649. if (this.options.pagination && this.options.sidePagination === 'server') {
  1650. params.pageSize = this.options.pageSize === this.options.formatAllRows() ?
  1651. this.options.totalRows : this.options.pageSize
  1652. params.pageNumber = this.options.pageNumber
  1653. }
  1654. if (!this.options.url && !this.options.ajax) {
  1655. return
  1656. }
  1657. if (this.options.queryParamsType === 'limit') {
  1658. params = {
  1659. search: params.searchText,
  1660. sort: params.sortName,
  1661. order: params.sortOrder
  1662. }
  1663. if (this.options.pagination && this.options.sidePagination === 'server') {
  1664. params.offset = this.options.pageSize === this.options.formatAllRows() ?
  1665. 0 : this.options.pageSize * (this.options.pageNumber - 1)
  1666. params.limit = this.options.pageSize
  1667. if (params.limit === 0 || this.options.pageSize === this.options.formatAllRows()) {
  1668. delete params.limit
  1669. }
  1670. }
  1671. }
  1672. if (
  1673. this.options.search &&
  1674. this.options.sidePagination === 'server' &&
  1675. this.options.searchable &&
  1676. this.columns.filter(column => column.searchable).length
  1677. ) {
  1678. params.searchable = []
  1679. for (const column of this.columns) {
  1680. if (
  1681. !column.checkbox &&
  1682. column.searchable &&
  1683. (
  1684. this.options.visibleSearch &&
  1685. column.visible ||
  1686. !this.options.visibleSearch
  1687. )
  1688. ) {
  1689. params.searchable.push(column.field)
  1690. }
  1691. }
  1692. }
  1693. if (!Utils.isEmptyObject(this.filterColumnsPartial)) {
  1694. params.filter = JSON.stringify(this.filterColumnsPartial, null)
  1695. }
  1696. data = Utils.calculateObjectValue(this.options, this.options.queryParams, [params], data)
  1697. // false to stop request
  1698. if (data === false) {
  1699. return
  1700. }
  1701. if (!silent) {
  1702. this.showLoading()
  1703. }
  1704. const request = Utils.extend({}, Utils.calculateObjectValue(null, this.options.ajaxOptions), {
  1705. type: this.options.method,
  1706. url: this.options.url,
  1707. data: this.options.contentType === 'application/json' && this.options.method === 'post' ?
  1708. JSON.stringify(data) : data,
  1709. cache: this.options.cache,
  1710. contentType: this.options.contentType,
  1711. dataType: this.options.dataType,
  1712. success: (_res, textStatus, jqXHR) => {
  1713. const res = Utils.calculateObjectValue(this.options,
  1714. this.options.responseHandler, [_res, jqXHR], _res)
  1715. if (
  1716. this.options.sidePagination === 'client' &&
  1717. this.options.paginationLoadMore
  1718. ) {
  1719. this._paginationLoaded = this.data.length === res.length
  1720. }
  1721. this.load(res)
  1722. this.trigger('load-success', res, jqXHR && jqXHR.status, jqXHR)
  1723. if (!silent) {
  1724. this.hideLoading()
  1725. }
  1726. if (
  1727. this.options.sidePagination === 'server' &&
  1728. this.options.pageNumber > 1 &&
  1729. res[this.options.totalField] > 0 &&
  1730. !res[this.options.dataField].length
  1731. ) {
  1732. this.updatePagination()
  1733. }
  1734. },
  1735. error: jqXHR => {
  1736. // abort ajax by multiple request
  1737. if (jqXHR && jqXHR.status === 0 && this._xhrAbort) {
  1738. this._xhrAbort = false
  1739. return
  1740. }
  1741. let data = []
  1742. if (this.options.sidePagination === 'server') {
  1743. data = {}
  1744. data[this.options.totalField] = 0
  1745. data[this.options.dataField] = []
  1746. }
  1747. this.load(data)
  1748. this.trigger('load-error', jqXHR && jqXHR.status, jqXHR)
  1749. if (!silent) {
  1750. this.hideLoading()
  1751. }
  1752. }
  1753. })
  1754. if (this.options.ajax) {
  1755. Utils.calculateObjectValue(this, this.options.ajax, [request], null)
  1756. } else {
  1757. if (this._xhr && this._xhr.readyState !== 4) {
  1758. this._xhrAbort = true
  1759. this._xhr.abort()
  1760. }
  1761. this._xhr = $.ajax(request)
  1762. }
  1763. return data
  1764. }
  1765. initSearchText () {
  1766. if (this.options.search) {
  1767. this.searchText = ''
  1768. if (this.options.searchText !== '') {
  1769. const $search = Utils.getSearchInput(this)
  1770. $search.val(this.options.searchText)
  1771. this.onSearch({ currentTarget: $search, firedByInitSearchText: true })
  1772. }
  1773. }
  1774. }
  1775. getCaret () {
  1776. this.$header.find('th').each((i, th) => {
  1777. $(th).find('.sortable').removeClass('desc asc')
  1778. .addClass($(th).data('field') === this.options.sortName ?
  1779. this.options.sortOrder : 'both')
  1780. })
  1781. }
  1782. updateSelected () {
  1783. const checkAll = this.$selectItem.filter(':enabled').length &&
  1784. this.$selectItem.filter(':enabled').length ===
  1785. this.$selectItem.filter(':enabled').filter(':checked').length
  1786. this.$selectAll.add(this.$selectAll_).prop('checked', checkAll)
  1787. this.$selectItem.each((i, el) => {
  1788. $(el).closest('tr')[$(el).prop('checked') ? 'addClass' : 'removeClass']('selected')
  1789. })
  1790. }
  1791. updateRows () {
  1792. this.$selectItem.each((i, el) => {
  1793. this.data[$(el).data('index')][this.header.stateField] = $(el).prop('checked')
  1794. })
  1795. }
  1796. resetRows () {
  1797. for (const row of this.data) {
  1798. this.$selectAll.prop('checked', false)
  1799. this.$selectItem.prop('checked', false)
  1800. if (this.header.stateField) {
  1801. row[this.header.stateField] = false
  1802. }
  1803. }
  1804. this.initHiddenRows()
  1805. }
  1806. trigger (_name, ...args) {
  1807. const name = `${_name}.bs.table`
  1808. this.options[BootstrapTable.EVENTS[name]](...[...args, this])
  1809. this.$el.trigger($.Event(name, { sender: this }), args)
  1810. this.options.onAll(name, ...[...args, this])
  1811. this.$el.trigger($.Event('all.bs.table', { sender: this }), [name, args])
  1812. }
  1813. resetHeader () {
  1814. // fix #61: the hidden table reset header bug.
  1815. // fix bug: get $el.css('width') error sometime (height = 500)
  1816. clearTimeout(this.timeoutId_)
  1817. this.timeoutId_ = setTimeout(() => this.fitHeader(), this.$el.is(':hidden') ? 100 : 0)
  1818. }
  1819. fitHeader () {
  1820. if (this.$el.is(':hidden')) {
  1821. this.timeoutId_ = setTimeout(() => this.fitHeader(), 100)
  1822. return
  1823. }
  1824. const fixedBody = this.$tableBody.get(0)
  1825. const scrollWidth = this.hasScrollBar &&
  1826. fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ?
  1827. Utils.getScrollBarWidth() : 0
  1828. this.$el.css('margin-top', -this.$header.outerHeight())
  1829. const focused = this.$tableHeader.find(':focus')
  1830. if (focused.length > 0) {
  1831. const $th = focused.parents('th')
  1832. if ($th.length > 0) {
  1833. const dataField = $th.attr('data-field')
  1834. if (dataField !== undefined) {
  1835. const $headerTh = this.$header.find(`[data-field='${dataField}']`)
  1836. if ($headerTh.length > 0) {
  1837. $headerTh.find(':input').addClass('focus-temp')
  1838. }
  1839. }
  1840. }
  1841. }
  1842. this.$header_ = this.$header.clone(true, true)
  1843. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]')
  1844. this.$tableHeader
  1845. .css('margin-right', scrollWidth)
  1846. .find('table').css('width', this.$el.outerWidth())
  1847. .html('').attr('class', this.$el.attr('class'))
  1848. .append(this.$header_)
  1849. this.$tableLoading.css('width', this.$el.outerWidth())
  1850. const focusedTemp = $('.focus-temp:visible:eq(0)')
  1851. if (focusedTemp.length > 0) {
  1852. focusedTemp.focus()
  1853. this.$header.find('.focus-temp').removeClass('focus-temp')
  1854. }
  1855. // fix bug: $.data() is not working as expected after $.append()
  1856. this.$header.find('th[data-field]').each((i, el) => {
  1857. this.$header_.find(Utils.sprintf('th[data-field="%s"]', $(el).data('field'))).data($(el).data())
  1858. })
  1859. const visibleFields = this.getVisibleFields()
  1860. const $ths = this.$header_.find('th')
  1861. let $tr = this.$body.find('>tr:not(.no-records-found,.virtual-scroll-top)').eq(0)
  1862. while ($tr.length && $tr.find('>td[colspan]:not([colspan="1"])').length) {
  1863. $tr = $tr.next()
  1864. }
  1865. const trLength = $tr.find('> *').length
  1866. $tr.find('> *').each((i, el) => {
  1867. const $this = $(el)
  1868. if (Utils.hasDetailViewIcon(this.options)) {
  1869. if (
  1870. i === 0 && this.options.detailViewAlign !== 'right' ||
  1871. i === trLength - 1 && this.options.detailViewAlign === 'right'
  1872. ) {
  1873. const $thDetail = $ths.filter('.detail')
  1874. const zoomWidth = $thDetail.innerWidth() - $thDetail.find('.fht-cell').width()
  1875. $thDetail.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1876. return
  1877. }
  1878. }
  1879. const index = i - Utils.getDetailViewIndexOffset(this.options)
  1880. let $th = this.$header_.find(Utils.sprintf('th[data-field="%s"]', visibleFields[index]))
  1881. if ($th.length > 1) {
  1882. $th = $($ths[$this[0].cellIndex])
  1883. }
  1884. const zoomWidth = $th.innerWidth() - $th.find('.fht-cell').width()
  1885. $th.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1886. })
  1887. this.horizontalScroll()
  1888. this.trigger('post-header')
  1889. }
  1890. initFooter () {
  1891. if (!this.options.showFooter || this.options.cardView) { // do nothing
  1892. return
  1893. }
  1894. const data = this.getData()
  1895. const html = []
  1896. let detailTemplate = ''
  1897. if (Utils.hasDetailViewIcon(this.options)) {
  1898. detailTemplate = '<th class="detail"><div class="th-inner"></div><div class="fht-cell"></div></th>'
  1899. }
  1900. if (detailTemplate && this.options.detailViewAlign !== 'right') {
  1901. html.push(detailTemplate)
  1902. }
  1903. for (const column of this.columns) {
  1904. let falign = ''
  1905. let valign = ''
  1906. const csses = []
  1907. let style = {}
  1908. let class_ = Utils.sprintf(' class="%s"', column['class'])
  1909. if (
  1910. !column.visible ||
  1911. this.footerData && this.footerData.length > 0 && !(column.field in this.footerData[0])
  1912. ) {
  1913. continue
  1914. }
  1915. if (this.options.cardView && !column.cardVisible) {
  1916. return
  1917. }
  1918. falign = Utils.sprintf('text-align: %s; ', column.falign ? column.falign : column.align)
  1919. valign = Utils.sprintf('vertical-align: %s; ', column.valign)
  1920. style = Utils.calculateObjectValue(null, column.footerStyle || this.options.footerStyle, [column])
  1921. if (style && style.css) {
  1922. for (const [key, value] of Object.entries(style.css)) {
  1923. csses.push(`${key}: ${value}`)
  1924. }
  1925. }
  1926. if (style && style.classes) {
  1927. class_ = Utils.sprintf(' class="%s"', column['class'] ?
  1928. [column['class'], style.classes].join(' ') : style.classes)
  1929. }
  1930. html.push('<th', class_, Utils.sprintf(' style="%s"', falign + valign + csses.concat().join('; ') || undefined))
  1931. let colspan = 0
  1932. if (this.footerData && this.footerData.length > 0) {
  1933. colspan = this.footerData[0][`_${column.field}_colspan`] || 0
  1934. }
  1935. if (colspan) {
  1936. html.push(` colspan="${colspan}" `)
  1937. }
  1938. html.push('>')
  1939. html.push('<div class="th-inner">')
  1940. let value = ''
  1941. if (this.footerData && this.footerData.length > 0) {
  1942. value = this.footerData[0][column.field] || ''
  1943. }
  1944. html.push(Utils.calculateObjectValue(column, column.footerFormatter,
  1945. [data, value], value))
  1946. html.push('</div>')
  1947. html.push('<div class="fht-cell"></div>')
  1948. html.push('</div>')
  1949. html.push('</th>')
  1950. }
  1951. if (detailTemplate && this.options.detailViewAlign === 'right') {
  1952. html.push(detailTemplate)
  1953. }
  1954. if (!this.options.height && !this.$tableFooter.length) {
  1955. this.$el.append('<tfoot><tr></tr></tfoot>')
  1956. this.$tableFooter = this.$el.find('tfoot')
  1957. }
  1958. if (!this.$tableFooter.find('tr').length) {
  1959. this.$tableFooter.html('<table><thead><tr></tr></thead></table>')
  1960. }
  1961. this.$tableFooter.find('tr').html(html.join(''))
  1962. this.trigger('post-footer', this.$tableFooter)
  1963. }
  1964. fitFooter () {
  1965. if (this.$el.is(':hidden')) {
  1966. setTimeout(() => this.fitFooter(), 100)
  1967. return
  1968. }
  1969. const fixedBody = this.$tableBody.get(0)
  1970. const scrollWidth = this.hasScrollBar &&
  1971. fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ?
  1972. Utils.getScrollBarWidth() : 0
  1973. this.$tableFooter
  1974. .css('margin-right', scrollWidth)
  1975. .find('table').css('width', this.$el.outerWidth())
  1976. .attr('class', this.$el.attr('class'))
  1977. const $ths = this.$tableFooter.find('th')
  1978. let $tr = this.$body.find('>tr:first-child:not(.no-records-found)')
  1979. $ths.find('.fht-cell').width('auto')
  1980. while ($tr.length && $tr.find('>td[colspan]:not([colspan="1"])').length) {
  1981. $tr = $tr.next()
  1982. }
  1983. const trLength = $tr.find('> *').length
  1984. $tr.find('> *').each((i, el) => {
  1985. const $this = $(el)
  1986. if (Utils.hasDetailViewIcon(this.options)) {
  1987. if (
  1988. i === 0 && this.options.detailViewAlign === 'left' ||
  1989. i === trLength - 1 && this.options.detailViewAlign === 'right'
  1990. ) {
  1991. const $thDetail = $ths.filter('.detail')
  1992. const zoomWidth = $thDetail.innerWidth() - $thDetail.find('.fht-cell').width()
  1993. $thDetail.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1994. return
  1995. }
  1996. }
  1997. const $th = $ths.eq(i)
  1998. const zoomWidth = $th.innerWidth() - $th.find('.fht-cell').width()
  1999. $th.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  2000. })
  2001. this.horizontalScroll()
  2002. }
  2003. horizontalScroll () {
  2004. // horizontal scroll event
  2005. // TODO: it's probably better improving the layout than binding to scroll event
  2006. this.$tableBody.off('scroll').on('scroll', () => {
  2007. const scrollLeft = this.$tableBody.scrollLeft()
  2008. if (this.options.showHeader && this.options.height) {
  2009. this.$tableHeader.scrollLeft(scrollLeft)
  2010. }
  2011. if (this.options.showFooter && !this.options.cardView) {
  2012. this.$tableFooter.scrollLeft(scrollLeft)
  2013. }
  2014. this.trigger('scroll-body', this.$tableBody)
  2015. })
  2016. }
  2017. getVisibleFields () {
  2018. const visibleFields = []
  2019. for (const field of this.header.fields) {
  2020. const column = this.columns[this.fieldsColumnsIndex[field]]
  2021. if (!column || !column.visible || this.options.cardView && !column.cardVisible) {
  2022. continue
  2023. }
  2024. visibleFields.push(field)
  2025. }
  2026. return visibleFields
  2027. }
  2028. initHiddenRows () {
  2029. this.hiddenRows = []
  2030. }
  2031. // PUBLIC FUNCTION DEFINITION
  2032. // =======================
  2033. getOptions () {
  2034. // deep copy and remove data
  2035. const options = Utils.extend({}, this.options)
  2036. delete options.data
  2037. return Utils.extend(true, {}, options)
  2038. }
  2039. refreshOptions (options) {
  2040. // If the objects are equivalent then avoid the call of destroy / init methods
  2041. if (Utils.compareObjects(this.options, options, true)) {
  2042. return
  2043. }
  2044. this.options = Utils.extend(this.options, options)
  2045. this.trigger('refresh-options', this.options)
  2046. this.destroy()
  2047. this.init()
  2048. }
  2049. getData (params) {
  2050. let data = this.options.data
  2051. if (
  2052. (
  2053. this.searchText ||
  2054. this.options.customSearch ||
  2055. this.options.sortName !== undefined ||
  2056. this.enableCustomSort || // Fix #4616: this.enableCustomSort is for extensions
  2057. !Utils.isEmptyObject(this.filterColumns) ||
  2058. typeof this.options.filterOptions.filterAlgorithm === 'function' ||
  2059. !Utils.isEmptyObject(this.filterColumnsPartial)
  2060. ) && (!params || !params.unfiltered)
  2061. ) {
  2062. data = this.data
  2063. }
  2064. if (params && !params.includeHiddenRows) {
  2065. const hiddenRows = this.getHiddenRows()
  2066. data = data.filter(row => Utils.findIndex(hiddenRows, row) === -1)
  2067. }
  2068. if (params && params.useCurrentPage) {
  2069. data = data.slice(this.pageFrom - 1, this.pageTo)
  2070. }
  2071. if (params && params.formatted) {
  2072. return data.map(row => {
  2073. for (const [key, value] of Object.entries(row)) {
  2074. const column = this.columns[this.fieldsColumnsIndex[key]]
  2075. if (!column) {
  2076. continue
  2077. }
  2078. return Utils.calculateObjectValue(column, this.header.formatters[column.fieldIndex],
  2079. [value, row, row.index, column.field], value)
  2080. }
  2081. })
  2082. }
  2083. return data
  2084. }
  2085. getSelections () {
  2086. return (this.options.maintainMetaData ? this.options.data : this.data)
  2087. .filter(row => row[this.header.stateField] === true)
  2088. }
  2089. load (_data) {
  2090. let fixedScroll = false
  2091. let data = _data
  2092. // #431: support pagination
  2093. if (this.options.pagination && this.options.sidePagination === 'server') {
  2094. this.options.totalRows = data[this.options.totalField]
  2095. this.options.totalNotFiltered = data[this.options.totalNotFilteredField]
  2096. this.footerData = data[this.options.footerField] ? [data[this.options.footerField]] : undefined
  2097. }
  2098. fixedScroll = this.options.fixedScroll || data.fixedScroll
  2099. data = Array.isArray(data) ? data : data[this.options.dataField]
  2100. this.initData(data)
  2101. this.initSearch()
  2102. this.initPagination()
  2103. this.initBody(fixedScroll)
  2104. }
  2105. append (data) {
  2106. this.initData(data, 'append')
  2107. this.initSearch()
  2108. this.initPagination()
  2109. this.initSort()
  2110. this.initBody(true)
  2111. }
  2112. prepend (data) {
  2113. this.initData(data, 'prepend')
  2114. this.initSearch()
  2115. this.initPagination()
  2116. this.initSort()
  2117. this.initBody(true)
  2118. }
  2119. remove (params) {
  2120. let removed = 0
  2121. for (let i = this.options.data.length - 1; i >= 0; i--) {
  2122. const row = this.options.data[i]
  2123. const value = Utils.getItemField(row, params.field, this.options.escape, row.escape)
  2124. if (value === undefined && params.field !== '$index') {
  2125. continue
  2126. }
  2127. if (
  2128. !row.hasOwnProperty(params.field) &&
  2129. params.field === '$index' &&
  2130. params.values.includes(i) ||
  2131. params.values.includes(value)
  2132. ) {
  2133. removed++
  2134. this.options.data.splice(i, 1)
  2135. }
  2136. }
  2137. if (!removed) {
  2138. return
  2139. }
  2140. if (this.options.sidePagination === 'server') {
  2141. this.options.totalRows -= removed
  2142. this.data = [...this.options.data]
  2143. }
  2144. this.initSearch()
  2145. this.initPagination()
  2146. this.initSort()
  2147. this.initBody(true)
  2148. }
  2149. removeAll () {
  2150. if (this.options.data.length > 0) {
  2151. this.data.splice(0, this.data.length)
  2152. this.options.data.splice(0, this.options.data.length)
  2153. this.initSearch()
  2154. this.initPagination()
  2155. this.initBody(true)
  2156. }
  2157. }
  2158. insertRow (params) {
  2159. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  2160. return
  2161. }
  2162. const row = this.data[params.index]
  2163. const originalIndex = this.options.data.indexOf(row)
  2164. this.data.splice(params.index, 0, params.row)
  2165. this.options.data.splice(originalIndex, 0, params.row)
  2166. this.initSearch()
  2167. this.initPagination()
  2168. this.initSort()
  2169. this.initBody(true)
  2170. }
  2171. updateRow (params) {
  2172. const allParams = Array.isArray(params) ? params : [params]
  2173. for (const params of allParams) {
  2174. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  2175. continue
  2176. }
  2177. const row = this.data[params.index]
  2178. const originalIndex = this.options.data.indexOf(row)
  2179. if (params.hasOwnProperty('replace') && params.replace) {
  2180. this.data[params.index] = params.row
  2181. this.options.data[originalIndex] = params.row
  2182. } else {
  2183. Utils.extend(this.data[params.index], params.row)
  2184. Utils.extend(this.options.data[originalIndex], params.row)
  2185. }
  2186. }
  2187. this.initSearch()
  2188. this.initPagination()
  2189. this.initSort()
  2190. this.initBody(true)
  2191. }
  2192. getRowByUniqueId (_id) {
  2193. const uniqueId = this.options.uniqueId
  2194. const len = this.options.data.length
  2195. let id = _id
  2196. let dataRow = null
  2197. let i
  2198. let row
  2199. for (i = len - 1; i >= 0; i--) {
  2200. row = this.options.data[i]
  2201. const rowUniqueId = Utils.getItemField(row, uniqueId, this.options.escape, row.escape)
  2202. if (rowUniqueId === undefined) {
  2203. continue
  2204. }
  2205. if (typeof rowUniqueId === 'string') {
  2206. id = _id.toString()
  2207. } else if (typeof rowUniqueId === 'number') {
  2208. if (Number(rowUniqueId) === rowUniqueId && rowUniqueId % 1 === 0) {
  2209. id = parseInt(_id, 10)
  2210. } else if (rowUniqueId === Number(rowUniqueId) && rowUniqueId !== 0) {
  2211. id = parseFloat(_id)
  2212. }
  2213. }
  2214. if (rowUniqueId === id) {
  2215. dataRow = row
  2216. break
  2217. }
  2218. }
  2219. return dataRow
  2220. }
  2221. updateByUniqueId (params) {
  2222. const allParams = Array.isArray(params) ? params : [params]
  2223. let updatedUid = null
  2224. for (const params of allParams) {
  2225. if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
  2226. continue
  2227. }
  2228. const rowId = this.options.data.indexOf(this.getRowByUniqueId(params.id))
  2229. if (rowId === -1) {
  2230. continue
  2231. }
  2232. if (params.hasOwnProperty('replace') && params.replace) {
  2233. this.options.data[rowId] = params.row
  2234. } else {
  2235. Utils.extend(this.options.data[rowId], params.row)
  2236. }
  2237. updatedUid = params.id
  2238. }
  2239. this.initSearch()
  2240. this.initPagination()
  2241. this.initSort()
  2242. this.initBody(true, updatedUid)
  2243. }
  2244. removeByUniqueId (id) {
  2245. const len = this.options.data.length
  2246. const row = this.getRowByUniqueId(id)
  2247. if (row) {
  2248. this.options.data.splice(this.options.data.indexOf(row), 1)
  2249. }
  2250. if (len === this.options.data.length) {
  2251. return
  2252. }
  2253. if (this.options.sidePagination === 'server') {
  2254. this.options.totalRows -= 1
  2255. this.data = [...this.options.data]
  2256. }
  2257. this.initSearch()
  2258. this.initPagination()
  2259. this.initBody(true)
  2260. }
  2261. _updateCellOnly (field, index) {
  2262. const rowHtml = this.initRow(this.data[index], index)
  2263. let fieldIndex = this.getVisibleFields().indexOf(field)
  2264. if (fieldIndex === -1) {
  2265. return
  2266. }
  2267. fieldIndex += Utils.getDetailViewIndexOffset(this.options)
  2268. this.$body.find(`>tr[data-index=${index}]`)
  2269. .find(`>td:eq(${fieldIndex})`)
  2270. .replaceWith($(rowHtml).find(`>td:eq(${fieldIndex})`))
  2271. this.initBodyEvent()
  2272. this.initFooter()
  2273. this.resetView()
  2274. this.updateSelected()
  2275. }
  2276. updateCell (params) {
  2277. if (!params.hasOwnProperty('index') ||
  2278. !params.hasOwnProperty('field') ||
  2279. !params.hasOwnProperty('value')) {
  2280. return
  2281. }
  2282. const row = this.data[params.index]
  2283. const originalIndex = this.options.data.indexOf(row)
  2284. this.data[params.index][params.field] = params.value
  2285. this.options.data[originalIndex][params.field] = params.value
  2286. if (params.reinit === false) {
  2287. this._updateCellOnly(params.field, params.index)
  2288. return
  2289. }
  2290. this.initSort()
  2291. this.initBody(true)
  2292. }
  2293. updateCellByUniqueId (params) {
  2294. const allParams = Array.isArray(params) ? params : [params]
  2295. allParams.forEach(({ id, field, value }) => {
  2296. const index = this.options.data.indexOf(this.getRowByUniqueId(id))
  2297. if (index === -1) {
  2298. return
  2299. }
  2300. this.options.data[index][field] = value
  2301. })
  2302. if (params.reinit === false) {
  2303. this._updateCellOnly(params.field,
  2304. this.options.data.indexOf(this.getRowByUniqueId(params.id)))
  2305. return
  2306. }
  2307. this.initSort()
  2308. this.initBody(true)
  2309. }
  2310. showRow (params) {
  2311. this._toggleRow(params, true)
  2312. }
  2313. hideRow (params) {
  2314. this._toggleRow(params, false)
  2315. }
  2316. _toggleRow (params, visible) {
  2317. let row
  2318. if (params.hasOwnProperty('index')) {
  2319. row = this.getData()[params.index]
  2320. } else if (params.hasOwnProperty('uniqueId')) {
  2321. row = this.getRowByUniqueId(params.uniqueId)
  2322. }
  2323. if (!row) {
  2324. return
  2325. }
  2326. const index = Utils.findIndex(this.hiddenRows, row)
  2327. if (!visible && index === -1) {
  2328. this.hiddenRows.push(row)
  2329. } else if (visible && index > -1) {
  2330. this.hiddenRows.splice(index, 1)
  2331. }
  2332. this.initBody(true)
  2333. this.initPagination()
  2334. }
  2335. getHiddenRows (show) {
  2336. if (show) {
  2337. this.initHiddenRows()
  2338. this.initBody(true)
  2339. this.initPagination()
  2340. return
  2341. }
  2342. const data = this.getData()
  2343. const rows = []
  2344. for (const row of data) {
  2345. if (this.hiddenRows.includes(row)) {
  2346. rows.push(row)
  2347. }
  2348. }
  2349. this.hiddenRows = rows
  2350. return rows
  2351. }
  2352. showColumn (field) {
  2353. const fields = Array.isArray(field) ? field : [field]
  2354. fields.forEach(field => {
  2355. this._toggleColumn(this.fieldsColumnsIndex[field], true, true)
  2356. })
  2357. }
  2358. hideColumn (field) {
  2359. const fields = Array.isArray(field) ? field : [field]
  2360. fields.forEach(field => {
  2361. this._toggleColumn(this.fieldsColumnsIndex[field], false, true)
  2362. })
  2363. }
  2364. _toggleColumn (index, checked, needUpdate) {
  2365. if (index === undefined || this.columns[index].visible === checked) {
  2366. return
  2367. }
  2368. this.columns[index].visible = checked
  2369. this.initHeader()
  2370. this.initSearch()
  2371. this.initPagination()
  2372. this.initBody()
  2373. if (this.options.showColumns) {
  2374. const $items = this.$toolbar.find('.keep-open input:not(".toggle-all")').prop('disabled', false)
  2375. if (needUpdate) {
  2376. $items.filter(Utils.sprintf('[value="%s"]', index)).prop('checked', checked)
  2377. }
  2378. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  2379. $items.filter(':checked').prop('disabled', true)
  2380. }
  2381. }
  2382. }
  2383. getVisibleColumns () {
  2384. return this.columns.filter(column => column.visible && !this.isSelectionColumn(column))
  2385. }
  2386. getHiddenColumns () {
  2387. return this.columns.filter(({ visible }) => !visible)
  2388. }
  2389. isSelectionColumn (column) {
  2390. return column.radio || column.checkbox
  2391. }
  2392. showAllColumns () {
  2393. this._toggleAllColumns(true)
  2394. }
  2395. hideAllColumns () {
  2396. this._toggleAllColumns(false)
  2397. }
  2398. _toggleAllColumns (visible) {
  2399. for (const column of this.columns.slice().reverse()) {
  2400. if (column.switchable) {
  2401. if (
  2402. !visible &&
  2403. this.options.showColumns &&
  2404. this.getVisibleColumns().filter(it => it.switchable).length === this.options.minimumCountColumns
  2405. ) {
  2406. continue
  2407. }
  2408. column.visible = visible
  2409. }
  2410. }
  2411. this.initHeader()
  2412. this.initSearch()
  2413. this.initPagination()
  2414. this.initBody()
  2415. if (this.options.showColumns) {
  2416. const $items = this.$toolbar.find('.keep-open input[type="checkbox"]:not(".toggle-all")').prop('disabled', false)
  2417. if (visible) {
  2418. $items.prop('checked', visible)
  2419. } else {
  2420. $items.get().reverse().forEach(item => {
  2421. if ($items.filter(':checked').length > this.options.minimumCountColumns) {
  2422. $(item).prop('checked', visible)
  2423. }
  2424. })
  2425. }
  2426. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  2427. $items.filter(':checked').prop('disabled', true)
  2428. }
  2429. }
  2430. }
  2431. mergeCells (options) {
  2432. const row = options.index
  2433. let col = this.getVisibleFields().indexOf(options.field)
  2434. const rowspan = options.rowspan || 1
  2435. const colspan = options.colspan || 1
  2436. let i
  2437. let j
  2438. const $tr = this.$body.find('>tr[data-index]')
  2439. col += Utils.getDetailViewIndexOffset(this.options)
  2440. const $td = $tr.eq(row).find('>td').eq(col)
  2441. if (row < 0 || col < 0 || row >= this.data.length) {
  2442. return
  2443. }
  2444. for (i = row; i < row + rowspan; i++) {
  2445. for (j = col; j < col + colspan; j++) {
  2446. $tr.eq(i).find('>td').eq(j).hide()
  2447. }
  2448. }
  2449. $td.attr('rowspan', rowspan).attr('colspan', colspan).show()
  2450. }
  2451. checkAll () {
  2452. this._toggleCheckAll(true)
  2453. }
  2454. uncheckAll () {
  2455. this._toggleCheckAll(false)
  2456. }
  2457. _toggleCheckAll (checked) {
  2458. const rowsBefore = this.getSelections()
  2459. this.$selectAll.add(this.$selectAll_).prop('checked', checked)
  2460. this.$selectItem.filter(':enabled').prop('checked', checked)
  2461. this.updateRows()
  2462. this.updateSelected()
  2463. const rowsAfter = this.getSelections()
  2464. if (checked) {
  2465. this.trigger('check-all', rowsAfter, rowsBefore)
  2466. return
  2467. }
  2468. this.trigger('uncheck-all', rowsAfter, rowsBefore)
  2469. }
  2470. checkInvert () {
  2471. const $items = this.$selectItem.filter(':enabled')
  2472. let checked = $items.filter(':checked')
  2473. $items.each((i, el) => {
  2474. $(el).prop('checked', !$(el).prop('checked'))
  2475. })
  2476. this.updateRows()
  2477. this.updateSelected()
  2478. this.trigger('uncheck-some', checked)
  2479. checked = this.getSelections()
  2480. this.trigger('check-some', checked)
  2481. }
  2482. check (index) {
  2483. this._toggleCheck(true, index)
  2484. }
  2485. uncheck (index) {
  2486. this._toggleCheck(false, index)
  2487. }
  2488. _toggleCheck (checked, index) {
  2489. const $el = this.$selectItem.filter(`[data-index="${index}"]`)
  2490. const row = this.data[index]
  2491. if (
  2492. $el.is(':radio') ||
  2493. this.options.singleSelect ||
  2494. this.options.multipleSelectRow &&
  2495. !this.multipleSelectRowCtrlKey &&
  2496. !this.multipleSelectRowShiftKey
  2497. ) {
  2498. for (const r of this.options.data) {
  2499. r[this.header.stateField] = false
  2500. }
  2501. this.$selectItem.filter(':checked').not($el).prop('checked', false)
  2502. }
  2503. row[this.header.stateField] = checked
  2504. if (this.options.multipleSelectRow) {
  2505. if (this.multipleSelectRowShiftKey && this.multipleSelectRowLastSelectedIndex >= 0) {
  2506. const [fromIndex, toIndex] = this.multipleSelectRowLastSelectedIndex < index ?
  2507. [this.multipleSelectRowLastSelectedIndex, index] : [index, this.multipleSelectRowLastSelectedIndex]
  2508. for (let i = fromIndex + 1; i < toIndex; i++) {
  2509. this.data[i][this.header.stateField] = true
  2510. this.$selectItem.filter(`[data-index="${i}"]`).prop('checked', true)
  2511. }
  2512. }
  2513. this.multipleSelectRowCtrlKey = false
  2514. this.multipleSelectRowShiftKey = false
  2515. this.multipleSelectRowLastSelectedIndex = checked ? index : -1
  2516. }
  2517. $el.prop('checked', checked)
  2518. this.updateSelected()
  2519. this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el)
  2520. }
  2521. checkBy (obj) {
  2522. this._toggleCheckBy(true, obj)
  2523. }
  2524. uncheckBy (obj) {
  2525. this._toggleCheckBy(false, obj)
  2526. }
  2527. _toggleCheckBy (checked, obj) {
  2528. if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
  2529. return
  2530. }
  2531. const rows = []
  2532. this.data.forEach((row, i) => {
  2533. if (!row.hasOwnProperty(obj.field)) {
  2534. return false
  2535. }
  2536. if (obj.values.includes(row[obj.field])) {
  2537. let $el = this.$selectItem.filter(':enabled')
  2538. .filter(Utils.sprintf('[data-index="%s"]', i))
  2539. const onlyCurrentPage = obj.hasOwnProperty('onlyCurrentPage') ? obj.onlyCurrentPage : false
  2540. $el = checked ? $el.not(':checked') : $el.filter(':checked')
  2541. if (!$el.length && onlyCurrentPage) {
  2542. return
  2543. }
  2544. $el.prop('checked', checked)
  2545. row[this.header.stateField] = checked
  2546. rows.push(row)
  2547. this.trigger(checked ? 'check' : 'uncheck', row, $el)
  2548. }
  2549. })
  2550. this.updateSelected()
  2551. this.trigger(checked ? 'check-some' : 'uncheck-some', rows)
  2552. }
  2553. refresh (params) {
  2554. if (params && params.url) {
  2555. this.options.url = params.url
  2556. }
  2557. if (params && params.pageNumber) {
  2558. this.options.pageNumber = params.pageNumber
  2559. }
  2560. if (params && params.pageSize) {
  2561. this.options.pageSize = params.pageSize
  2562. }
  2563. if (params && params.query) {
  2564. const url = new URL(this.options.url)
  2565. const urlParams = new URLSearchParams(url.search)
  2566. for (const [key, value] of Object.entries(params.query)) {
  2567. urlParams.set(key, value)
  2568. }
  2569. url.search = urlParams.toString()
  2570. this.options.url = url.toString()
  2571. }
  2572. this.trigger('refresh', this.initServer(params && params.silent))
  2573. }
  2574. destroy () {
  2575. this.$el.insertBefore(this.$container)
  2576. $(this.options.toolbar).insertBefore(this.$el)
  2577. this.$container.next().remove()
  2578. this.$container.remove()
  2579. this.$el.html(this.$el_.html())
  2580. .css('margin-top', '0')
  2581. .attr('class', this.$el_.attr('class') || '') // reset the class
  2582. const resizeEvent = Utils.getEventName('resize.bootstrap-table', this.$el.attr('id'))
  2583. $(window).off(resizeEvent)
  2584. }
  2585. resetView (params) {
  2586. let padding = 0
  2587. if (params && params.height) {
  2588. this.options.height = params.height
  2589. }
  2590. this.$tableContainer.toggleClass('has-card-view', this.options.cardView)
  2591. if (this.options.height) {
  2592. const fixedBody = this.$tableBody.get(0)
  2593. this.hasScrollBar = fixedBody.scrollWidth > fixedBody.clientWidth
  2594. }
  2595. if (!this.options.cardView && this.options.showHeader && this.options.height) {
  2596. this.$tableHeader.show()
  2597. this.resetHeader()
  2598. padding += this.$header.outerHeight(true) + 1
  2599. } else {
  2600. this.$tableHeader.hide()
  2601. this.trigger('post-header')
  2602. }
  2603. if (!this.options.cardView && this.options.showFooter) {
  2604. this.$tableFooter.show()
  2605. this.fitFooter()
  2606. if (this.options.height) {
  2607. padding += this.$tableFooter.outerHeight(true)
  2608. }
  2609. }
  2610. if (this.$container.hasClass('fullscreen')) {
  2611. this.$tableContainer.css('height', '')
  2612. this.$tableContainer.css('width', '')
  2613. } else if (this.options.height) {
  2614. if (this.$tableBorder) {
  2615. this.$tableBorder.css('width', '')
  2616. this.$tableBorder.css('height', '')
  2617. }
  2618. const toolbarHeight = this.$toolbar.outerHeight(true)
  2619. const paginationHeight = this.$pagination.outerHeight(true)
  2620. const height = this.options.height - toolbarHeight - paginationHeight
  2621. const $bodyTable = this.$tableBody.find('>table')
  2622. const tableHeight = $bodyTable.outerHeight()
  2623. this.$tableContainer.css('height', `${height}px`)
  2624. if (this.$tableBorder && $bodyTable.is(':visible')) {
  2625. let tableBorderHeight = height - tableHeight - 2
  2626. if (this.hasScrollBar) {
  2627. tableBorderHeight -= Utils.getScrollBarWidth()
  2628. }
  2629. this.$tableBorder.css('width', `${$bodyTable.outerWidth()}px`)
  2630. this.$tableBorder.css('height', `${tableBorderHeight}px`)
  2631. }
  2632. }
  2633. if (this.options.cardView) {
  2634. // remove the element css
  2635. this.$el.css('margin-top', '0')
  2636. this.$tableContainer.css('padding-bottom', '0')
  2637. this.$tableFooter.hide()
  2638. } else {
  2639. // Assign the correct sortable arrow
  2640. this.getCaret()
  2641. this.$tableContainer.css('padding-bottom', `${padding}px`)
  2642. }
  2643. this.trigger('reset-view')
  2644. }
  2645. showLoading () {
  2646. this.$tableLoading.toggleClass('open', true)
  2647. let fontSize = this.options.loadingFontSize
  2648. if (this.options.loadingFontSize === 'auto') {
  2649. fontSize = this.$tableLoading.width() * 0.04
  2650. fontSize = Math.max(12, fontSize)
  2651. fontSize = Math.min(32, fontSize)
  2652. fontSize = `${fontSize}px`
  2653. }
  2654. this.$tableLoading.find('.loading-text').css('font-size', fontSize)
  2655. }
  2656. hideLoading () {
  2657. this.$tableLoading.toggleClass('open', false)
  2658. }
  2659. togglePagination () {
  2660. this.options.pagination = !this.options.pagination
  2661. const icon = this.options.showButtonIcons ? this.options.pagination ? this.options.icons.paginationSwitchDown : this.options.icons.paginationSwitchUp : ''
  2662. const text = this.options.showButtonText ? this.options.pagination ? this.options.formatPaginationSwitchUp() : this.options.formatPaginationSwitchDown() : ''
  2663. this.$toolbar.find('button[name="paginationSwitch"]')
  2664. .html(`${Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, icon)} ${text}`)
  2665. this.updatePagination()
  2666. this.trigger('toggle-pagination', this.options.pagination)
  2667. }
  2668. toggleFullscreen () {
  2669. this.$el.closest('.bootstrap-table').toggleClass('fullscreen')
  2670. this.resetView()
  2671. }
  2672. toggleView () {
  2673. this.options.cardView = !this.options.cardView
  2674. this.initHeader()
  2675. const icon = this.options.showButtonIcons ? this.options.cardView ? this.options.icons.toggleOn : this.options.icons.toggleOff : ''
  2676. const text = this.options.cardView ? this.options.formatToggleOff() : this.options.formatToggleOn()
  2677. this.$toolbar.find('button[name="toggle"]')
  2678. .html(`${Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix,
  2679. icon)} ${this.options.showButtonText ? text : ''}`)
  2680. .attr('aria-label', text)
  2681. .attr(this.options.buttonsAttributeTitle, text)
  2682. this.initBody()
  2683. this.trigger('toggle', this.options.cardView)
  2684. }
  2685. resetSearch (text) {
  2686. const $search = Utils.getSearchInput(this)
  2687. const textToUse = text || ''
  2688. $search.val(textToUse)
  2689. this.searchText = textToUse
  2690. this.onSearch({ currentTarget: $search }, false)
  2691. }
  2692. filterBy (columns, options) {
  2693. this.filterOptions = Utils.isEmptyObject(options) ? this.options.filterOptions : Utils.extend(this.options.filterOptions, options)
  2694. this.filterColumns = Utils.isEmptyObject(columns) ? {} : columns
  2695. this.options.pageNumber = 1
  2696. this.initSearch()
  2697. this.updatePagination()
  2698. }
  2699. scrollTo (params) {
  2700. let options = { unit: 'px', value: 0 }
  2701. if (typeof params === 'object') {
  2702. options = Object.assign(options, params)
  2703. } else if (typeof params === 'string' && params === 'bottom') {
  2704. options.value = this.$tableBody[0].scrollHeight
  2705. } else if (typeof params === 'string' || typeof params === 'number') {
  2706. options.value = params
  2707. }
  2708. let scrollTo = options.value
  2709. if (options.unit === 'rows') {
  2710. scrollTo = 0
  2711. this.$body.find(`> tr:lt(${options.value})`).each((i, el) => {
  2712. scrollTo += $(el).outerHeight(true)
  2713. })
  2714. }
  2715. this.$tableBody.scrollTop(scrollTo)
  2716. }
  2717. getScrollPosition () {
  2718. return this.$tableBody.scrollTop()
  2719. }
  2720. selectPage (page) {
  2721. if (page > 0 && page <= this.options.totalPages) {
  2722. this.options.pageNumber = page
  2723. this.updatePagination()
  2724. }
  2725. }
  2726. prevPage () {
  2727. if (this.options.pageNumber > 1) {
  2728. this.options.pageNumber--
  2729. this.updatePagination()
  2730. }
  2731. }
  2732. nextPage () {
  2733. if (this.options.pageNumber < this.options.totalPages) {
  2734. this.options.pageNumber++
  2735. this.updatePagination()
  2736. }
  2737. }
  2738. toggleDetailView (index, _columnDetailFormatter) {
  2739. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"]', index))
  2740. if ($tr.next().is('tr.detail-view')) {
  2741. this.collapseRow(index)
  2742. } else {
  2743. this.expandRow(index, _columnDetailFormatter)
  2744. }
  2745. this.resetView()
  2746. }
  2747. expandRow (index, _columnDetailFormatter) {
  2748. const row = this.data[index]
  2749. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"][data-has-detail-view]', index))
  2750. if (this.options.detailViewIcon) {
  2751. $tr.find('a.detail-icon').html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailClose))
  2752. }
  2753. if ($tr.next().is('tr.detail-view')) {
  2754. return
  2755. }
  2756. $tr.after(Utils.sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.children('td').length))
  2757. const $element = $tr.next().find('td')
  2758. const detailFormatter = _columnDetailFormatter || this.options.detailFormatter
  2759. const content = Utils.calculateObjectValue(this.options, detailFormatter, [index, row, $element], '')
  2760. if ($element.length === 1) {
  2761. $element.append(content)
  2762. }
  2763. this.trigger('expand-row', index, row, $element)
  2764. }
  2765. expandRowByUniqueId (uniqueId) {
  2766. const row = this.getRowByUniqueId(uniqueId)
  2767. if (!row) {
  2768. return
  2769. }
  2770. this.expandRow(this.data.indexOf(row))
  2771. }
  2772. collapseRow (index) {
  2773. const row = this.data[index]
  2774. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"][data-has-detail-view]', index))
  2775. if (!$tr.next().is('tr.detail-view')) {
  2776. return
  2777. }
  2778. if (this.options.detailViewIcon) {
  2779. $tr.find('a.detail-icon').html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailOpen))
  2780. }
  2781. this.trigger('collapse-row', index, row, $tr.next())
  2782. $tr.next().remove()
  2783. }
  2784. collapseRowByUniqueId (uniqueId) {
  2785. const row = this.getRowByUniqueId(uniqueId)
  2786. if (!row) {
  2787. return
  2788. }
  2789. this.collapseRow(this.data.indexOf(row))
  2790. }
  2791. expandAllRows () {
  2792. const trs = this.$body.find('> tr[data-index][data-has-detail-view]')
  2793. for (let i = 0; i < trs.length; i++) {
  2794. this.expandRow($(trs[i]).data('index'))
  2795. }
  2796. }
  2797. collapseAllRows () {
  2798. const trs = this.$body.find('> tr[data-index][data-has-detail-view]')
  2799. for (let i = 0; i < trs.length; i++) {
  2800. this.collapseRow($(trs[i]).data('index'))
  2801. }
  2802. }
  2803. updateColumnTitle (params) {
  2804. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('title')) {
  2805. return
  2806. }
  2807. this.columns[this.fieldsColumnsIndex[params.field]].title =
  2808. this.options.escape && this.options.escapeTitle ? Utils.escapeHTML(params.title) : params.title
  2809. if (this.columns[this.fieldsColumnsIndex[params.field]].visible) {
  2810. this.$header.find('th[data-field]').each((i, el) => {
  2811. if ($(el).data('field') === params.field) {
  2812. $($(el).find('.th-inner')[0]).html(params.title)
  2813. return false
  2814. }
  2815. })
  2816. this.resetView()
  2817. }
  2818. }
  2819. updateFormatText (formatName, text) {
  2820. if (!/^format/.test(formatName) || !this.options[formatName]) {
  2821. return
  2822. }
  2823. if (typeof text === 'string') {
  2824. this.options[formatName] = () => text
  2825. } else if (typeof text === 'function') {
  2826. this.options[formatName] = text
  2827. }
  2828. this.initToolbar()
  2829. this.initPagination()
  2830. this.initBody()
  2831. }
  2832. }
  2833. BootstrapTable.VERSION = Constants.VERSION
  2834. BootstrapTable.DEFAULTS = Constants.DEFAULTS
  2835. BootstrapTable.LOCALES = Constants.LOCALES
  2836. BootstrapTable.COLUMN_DEFAULTS = Constants.COLUMN_DEFAULTS
  2837. BootstrapTable.METHODS = Constants.METHODS
  2838. BootstrapTable.EVENTS = Constants.EVENTS
  2839. // BOOTSTRAP TABLE PLUGIN DEFINITION
  2840. // =======================
  2841. $.BootstrapTable = BootstrapTable
  2842. $.fn.bootstrapTable = function (option, ...args) {
  2843. let value
  2844. this.each((i, el) => {
  2845. let data = $(el).data('bootstrap.table')
  2846. if (typeof option === 'string') {
  2847. if (!Constants.METHODS.includes(option)) {
  2848. throw new Error(`Unknown method: ${option}`)
  2849. }
  2850. if (!data) {
  2851. return
  2852. }
  2853. value = data[option](...args)
  2854. if (option === 'destroy') {
  2855. $(el).removeData('bootstrap.table')
  2856. }
  2857. return
  2858. }
  2859. if (data) {
  2860. console.warn('You cannot initialize the table more than once!')
  2861. return
  2862. }
  2863. const options = Utils.extend(true, {}, BootstrapTable.DEFAULTS, $(el).data(),
  2864. typeof option === 'object' && option)
  2865. data = new $.BootstrapTable(el, options)
  2866. $(el).data('bootstrap.table', data)
  2867. data.init()
  2868. })
  2869. return typeof value === 'undefined' ? this : value
  2870. }
  2871. $.fn.bootstrapTable.Constructor = BootstrapTable
  2872. $.fn.bootstrapTable.theme = Constants.THEME
  2873. $.fn.bootstrapTable.VERSION = Constants.VERSION
  2874. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS
  2875. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS
  2876. $.fn.bootstrapTable.events = BootstrapTable.EVENTS
  2877. $.fn.bootstrapTable.locales = BootstrapTable.LOCALES
  2878. $.fn.bootstrapTable.methods = BootstrapTable.METHODS
  2879. $.fn.bootstrapTable.utils = Utils
  2880. // BOOTSTRAP TABLE INIT
  2881. // =======================
  2882. $(() => {
  2883. $('[data-toggle="table"]').bootstrapTable()
  2884. })
  2885. export default BootstrapTable