bootstrap-table.js 102 KB

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