bootstrap-table.js 105 KB

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