bootstrap-table.js 101 KB

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