bootstrap-table.js 99 KB

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