bootstrap-table.js 107 KB

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