bootstrap-table.js 98 KB

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