bootstrap-table.js 95 KB

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