bootstrap-table.js 104 KB

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