bootstrap-table.js 97 KB

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