bootstrap-table.js 105 KB

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