bootstrap-table.js 105 KB

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