bootstrap-table.js 101 KB

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