bootstrap-table.js 99 KB

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