bootstrap-table.js 95 KB

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