bootstrap-table.js 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196
  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * version: 1.12.2
  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 names) {
  153. func = func[f]
  154. }
  155. } else {
  156. func = window[name]
  157. }
  158. }
  159. if (func !== null && 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. Utils.calculateObjectValue(this.options, this.options.customSearch, [this.searchText])
  1113. return
  1114. }
  1115. const s = this.searchText && (this.options.escape
  1116. ? Utils.escapeHTML(this.searchText) : this.searchText).toLowerCase()
  1117. const f = $.isEmptyObject(this.filterColumns) ? null : this.filterColumns
  1118. // Check filter
  1119. this.data = f ? this.options.data.filter((item, i) => {
  1120. for (const key in f) {
  1121. if (
  1122. (Array.isArray(f[key]) &&
  1123. !f[key].includes(item[key])) ||
  1124. (!Array.isArray(f[key]) &&
  1125. item[key] !== f[key])
  1126. ) {
  1127. return false
  1128. }
  1129. }
  1130. return true
  1131. }) : this.options.data
  1132. this.data = s ? this.data.filter((item, i) => {
  1133. for (let j = 0; j < this.header.fields.length; j++) {
  1134. if (!this.header.searchables[j]) {
  1135. continue
  1136. }
  1137. const key = $.isNumeric(this.header.fields[j]) ? parseInt(this.header.fields[j], 10) : this.header.fields[j]
  1138. const column = this.columns[this.fieldsColumnsIndex[key]]
  1139. let value
  1140. if (typeof key === 'string') {
  1141. value = item
  1142. const props = key.split('.')
  1143. for (let i = 0; i < props.length; i++) {
  1144. if (value[props[i]] != null) {
  1145. value = value[props[i]]
  1146. }
  1147. }
  1148. } else {
  1149. value = item[key]
  1150. }
  1151. // Fix #142: respect searchForamtter boolean
  1152. if (column && column.searchFormatter) {
  1153. value = Utils.calculateObjectValue(column,
  1154. this.header.formatters[j], [value, item, i], value)
  1155. }
  1156. if (typeof value === 'string' || typeof value === 'number') {
  1157. if (this.options.strictSearch) {
  1158. if ((`${value}`).toLowerCase() === s) {
  1159. return true
  1160. }
  1161. } else {
  1162. if ((`${value}`).toLowerCase().includes(s)) {
  1163. return true
  1164. }
  1165. }
  1166. }
  1167. }
  1168. return false
  1169. }) : this.data
  1170. }
  1171. }
  1172. initPagination () {
  1173. if (!this.options.pagination) {
  1174. this.$pagination.hide()
  1175. return
  1176. } else {
  1177. this.$pagination.show()
  1178. }
  1179. const html = []
  1180. let $allSelected = false
  1181. let i
  1182. let from
  1183. let to
  1184. let $pageList
  1185. let $pre
  1186. let $next
  1187. let $number
  1188. const data = this.getData()
  1189. let pageList = this.options.pageList
  1190. if (this.options.sidePagination !== 'server') {
  1191. this.options.totalRows = data.length
  1192. }
  1193. this.totalPages = 0
  1194. if (this.options.totalRows) {
  1195. if (this.options.pageSize === this.options.formatAllRows()) {
  1196. this.options.pageSize = this.options.totalRows
  1197. $allSelected = true
  1198. } else if (this.options.pageSize === this.options.totalRows) {
  1199. // Fix #667 Table with pagination,
  1200. // multiple pages and a search this matches to one page throws exception
  1201. const pageLst = typeof this.options.pageList === 'string'
  1202. ? this.options.pageList.replace('[', '').replace(']', '')
  1203. .replace(/ /g, '').toLowerCase().split(',') : this.options.pageList
  1204. if (pageLst.includes(this.options.formatAllRows().toLowerCase())) {
  1205. $allSelected = true
  1206. }
  1207. }
  1208. this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1
  1209. this.options.totalPages = this.totalPages
  1210. }
  1211. if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) {
  1212. this.options.pageNumber = this.totalPages
  1213. }
  1214. this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1
  1215. this.pageTo = this.options.pageNumber * this.options.pageSize
  1216. if (this.pageTo > this.options.totalRows) {
  1217. this.pageTo = this.options.totalRows
  1218. }
  1219. html.push(
  1220. Utils.sprintf('<div class="%s-%s pagination-detail">', bootstrap.classes.pull, this.options.paginationDetailHAlign),
  1221. '<span class="pagination-info">',
  1222. this.options.onlyInfoPagination ? this.options.formatDetailPagination(this.options.totalRows)
  1223. : this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows),
  1224. '</span>')
  1225. if (!this.options.onlyInfoPagination) {
  1226. html.push('<span class="page-list">')
  1227. const pageNumber = [
  1228. Utils.sprintf('<span class="btn-group %s">',
  1229. this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both'
  1230. ? 'dropdown' : 'dropup'),
  1231. `<button type="button" class="btn${Utils.sprintf(' btn-%s', this.options.buttonsClass)}${Utils.sprintf(' btn-%s', this.options.iconSize)} dropdown-toggle" data-toggle="dropdown">`,
  1232. '<span class="page-size">',
  1233. $allSelected ? this.options.formatAllRows() : this.options.pageSize,
  1234. '</span>',
  1235. ' <span class="caret"></span>',
  1236. '</button>',
  1237. bootstrap.html.pageDropdown[0]
  1238. ]
  1239. if (typeof this.options.pageList === 'string') {
  1240. const list = this.options.pageList.replace('[', '').replace(']', '')
  1241. .replace(/ /g, '').split(',')
  1242. pageList = []
  1243. for (let value of list) {
  1244. pageList.push(
  1245. (value.toUpperCase() === this.options.formatAllRows().toUpperCase() ||
  1246. value.toUpperCase() === 'UNLIMITED')
  1247. ? this.options.formatAllRows() : +value)
  1248. }
  1249. }
  1250. pageList.forEach((page, i) => {
  1251. if (!this.options.smartDisplay || i === 0 || pageList[i - 1] < this.options.totalRows) {
  1252. let active
  1253. if ($allSelected) {
  1254. active = page === this.options.formatAllRows() ? 'active' : ''
  1255. } else {
  1256. active = page === this.options.pageSize ? 'active' : ''
  1257. }
  1258. pageNumber.push(Utils.sprintf(bootstrap.html.pageDropdownItem, active, page))
  1259. }
  1260. })
  1261. pageNumber.push(`${bootstrap.html.pageDropdown[1]}</span>`)
  1262. html.push(this.options.formatRecordsPerPage(pageNumber.join('')))
  1263. html.push('</span>')
  1264. html.push('</div>',
  1265. Utils.sprintf('<div class="%s-%s pagination">', bootstrap.classes.pull, this.options.paginationHAlign),
  1266. `<ul class="pagination${Utils.sprintf(' pagination-%s', this.options.iconSize)}">`,
  1267. Utils.sprintf('<li class="page-item page-pre"><a class="page-link" href="#">%s</a></li>',
  1268. this.options.paginationPreText))
  1269. if (this.totalPages < 5) {
  1270. from = 1
  1271. to = this.totalPages
  1272. } else {
  1273. from = this.options.pageNumber - 2
  1274. to = from + 4
  1275. if (from < 1) {
  1276. from = 1
  1277. to = 5
  1278. }
  1279. if (to > this.totalPages) {
  1280. to = this.totalPages
  1281. from = to - 4
  1282. }
  1283. }
  1284. if (this.totalPages >= 6) {
  1285. if (this.options.pageNumber >= 3) {
  1286. html.push(
  1287. Utils.sprintf('<li class="page-item page-first%s">',
  1288. this.options.pageNumber === 1 ? ' active' : ''),
  1289. '<a class="page-link" href="#">', 1, '</a>',
  1290. '</li>')
  1291. from++
  1292. }
  1293. if (this.options.pageNumber >= 4) {
  1294. if (this.options.pageNumber === 4 || this.totalPages === 6 || this.totalPages === 7) {
  1295. from--
  1296. } else {
  1297. html.push('<li class="page-item page-first-separator disabled">',
  1298. '<a class="page-link" href="#">...</a>',
  1299. '</li>')
  1300. }
  1301. to--
  1302. }
  1303. }
  1304. if (this.totalPages >= 7) {
  1305. if (this.options.pageNumber >= (this.totalPages - 2)) {
  1306. from--
  1307. }
  1308. }
  1309. if (this.totalPages === 6) {
  1310. if (this.options.pageNumber >= (this.totalPages - 2)) {
  1311. to++
  1312. }
  1313. } else if (this.totalPages >= 7) {
  1314. if (this.totalPages === 7 || this.options.pageNumber >= (this.totalPages - 3)) {
  1315. to++
  1316. }
  1317. }
  1318. for (i = from; i <= to; i++) {
  1319. html.push(Utils.sprintf('<li class="page-item%s">',
  1320. i === this.options.pageNumber ? ' active' : ''),
  1321. '<a class="page-link" href="#">', i, '</a>',
  1322. '</li>')
  1323. }
  1324. if (this.totalPages >= 8) {
  1325. if (this.options.pageNumber <= (this.totalPages - 4)) {
  1326. html.push('<li class="page-item page-last-separator disabled">',
  1327. '<a class="page-link" href="#">...</a>',
  1328. '</li>')
  1329. }
  1330. }
  1331. if (this.totalPages >= 6) {
  1332. if (this.options.pageNumber <= (this.totalPages - 3)) {
  1333. html.push(Utils.sprintf('<li class="page-item page-last%s">',
  1334. this.totalPages === this.options.pageNumber ? ' active' : ''),
  1335. '<a class="page-link" href="#">', this.totalPages, '</a>',
  1336. '</li>')
  1337. }
  1338. }
  1339. html.push(
  1340. Utils.sprintf('<li class="page-item page-next"><a class="page-link" href="#">%s</a></li>',
  1341. this.options.paginationNextText),
  1342. '</ul>',
  1343. '</div>')
  1344. }
  1345. this.$pagination.html(html.join(''))
  1346. if (!this.options.onlyInfoPagination) {
  1347. $pageList = this.$pagination.find('.page-list a')
  1348. $pre = this.$pagination.find('.page-pre')
  1349. $next = this.$pagination.find('.page-next')
  1350. $number = this.$pagination.find('.page-item').not('.page-next, .page-pre')
  1351. if (this.options.smartDisplay) {
  1352. if (this.totalPages <= 1) {
  1353. this.$pagination.find('div.pagination').hide()
  1354. }
  1355. if (pageList.length < 2 || this.options.totalRows <= pageList[0]) {
  1356. this.$pagination.find('span.page-list').hide()
  1357. }
  1358. // when data is empty, hide the pagination
  1359. this.$pagination[this.getData().length ? 'show' : 'hide']()
  1360. }
  1361. if (!this.options.paginationLoop) {
  1362. if (this.options.pageNumber === 1) {
  1363. $pre.addClass('disabled')
  1364. }
  1365. if (this.options.pageNumber === this.totalPages) {
  1366. $next.addClass('disabled')
  1367. }
  1368. }
  1369. if ($allSelected) {
  1370. this.options.pageSize = this.options.formatAllRows()
  1371. }
  1372. // removed the events for last and first, onPageNumber executeds the same logic
  1373. $pageList.off('click').on('click', $.proxy(this.onPageListChange, this))
  1374. $pre.off('click').on('click', $.proxy(this.onPagePre, this))
  1375. $next.off('click').on('click', $.proxy(this.onPageNext, this))
  1376. $number.off('click').on('click', $.proxy(this.onPageNumber, this))
  1377. }
  1378. }
  1379. updatePagination (event) {
  1380. // Fix #171: IE disabled button can be clicked bug.
  1381. if (event && $(event.currentTarget).hasClass('disabled')) {
  1382. return
  1383. }
  1384. if (!this.options.maintainSelected) {
  1385. this.resetRows()
  1386. }
  1387. this.initPagination()
  1388. if (this.options.sidePagination === 'server') {
  1389. this.initServer()
  1390. } else {
  1391. this.initBody()
  1392. }
  1393. this.trigger('page-change', this.options.pageNumber, this.options.pageSize)
  1394. }
  1395. onPageListChange (event) {
  1396. event.preventDefault()
  1397. const $this = $(event.currentTarget)
  1398. $this.parent().addClass('active').siblings().removeClass('active')
  1399. this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase()
  1400. ? this.options.formatAllRows() : +$this.text()
  1401. this.$toolbar.find('.page-size').text(this.options.pageSize)
  1402. this.updatePagination(event)
  1403. return false
  1404. }
  1405. onPagePre (event) {
  1406. event.preventDefault()
  1407. if ((this.options.pageNumber - 1) === 0) {
  1408. this.options.pageNumber = this.options.totalPages
  1409. } else {
  1410. this.options.pageNumber--
  1411. }
  1412. this.updatePagination(event)
  1413. return false
  1414. }
  1415. onPageNext (event) {
  1416. event.preventDefault()
  1417. if ((this.options.pageNumber + 1) > this.options.totalPages) {
  1418. this.options.pageNumber = 1
  1419. } else {
  1420. this.options.pageNumber++
  1421. }
  1422. this.updatePagination(event)
  1423. return false
  1424. }
  1425. onPageNumber (event) {
  1426. event.preventDefault()
  1427. if (this.options.pageNumber === +$(event.currentTarget).text()) {
  1428. return
  1429. }
  1430. this.options.pageNumber = +$(event.currentTarget).text()
  1431. this.updatePagination(event)
  1432. return false
  1433. }
  1434. initRow (item, i, data) {
  1435. let key
  1436. const html = []
  1437. let style = {}
  1438. const csses = []
  1439. let data_ = ''
  1440. let attributes = {}
  1441. const htmlAttributes = []
  1442. if (this.hiddenRows.includes(item)) {
  1443. return
  1444. }
  1445. style = Utils.calculateObjectValue(this.options, this.options.rowStyle, [item, i], style)
  1446. if (style && style.css) {
  1447. for (key in style.css) {
  1448. csses.push(`${key}: ${style.css[key]}`)
  1449. }
  1450. }
  1451. attributes = Utils.calculateObjectValue(this.options,
  1452. this.options.rowAttributes, [item, i], attributes)
  1453. if (attributes) {
  1454. for (key in attributes) {
  1455. htmlAttributes.push(`${key}="${Utils.escapeHTML(attributes[key])}"`)
  1456. }
  1457. }
  1458. if (item._data && !$.isEmptyObject(item._data)) {
  1459. item._data.forEach((v, k) => {
  1460. // ignore data-index
  1461. if (k === 'index') {
  1462. return
  1463. }
  1464. data_ += ` data-${k}="${v}"`
  1465. })
  1466. }
  1467. html.push('<tr',
  1468. Utils.sprintf(' %s', htmlAttributes.length ? htmlAttributes.join(' ') : undefined),
  1469. Utils.sprintf(' id="%s"', Array.isArray(item) ? undefined : item._id),
  1470. Utils.sprintf(' class="%s"', style.classes || (Array.isArray(item) ? undefined : item._class)),
  1471. ` data-index="${i}"`,
  1472. Utils.sprintf(' data-uniqueid="%s"', item[this.options.uniqueId]),
  1473. Utils.sprintf('%s', data_),
  1474. '>'
  1475. )
  1476. if (this.options.cardView) {
  1477. html.push(`<td colspan="${this.header.fields.length}"><div class="card-views">`)
  1478. }
  1479. if (!this.options.cardView && this.options.detailView) {
  1480. html.push('<td>')
  1481. if (Utils.calculateObjectValue(null, this.options.detailFilter, [i, item])) {
  1482. html.push(`
  1483. <a class="detail-icon" href="#">
  1484. <i class="${this.options.iconsPrefix} ${this.options.icons.detailOpen}"></i>
  1485. </a>
  1486. `)
  1487. }
  1488. html.push('</td>')
  1489. }
  1490. this.header.fields.forEach((field, j) => {
  1491. let text = ''
  1492. let value_ = Utils.getItemField(item, field, this.options.escape)
  1493. let value = ''
  1494. let type = ''
  1495. let cellStyle = {}
  1496. let id_ = ''
  1497. let class_ = this.header.classes[j]
  1498. let style_ = ''
  1499. let data_ = ''
  1500. let rowspan_ = ''
  1501. let colspan_ = ''
  1502. let title_ = ''
  1503. const column = this.columns[j]
  1504. if (this.fromHtml && typeof value_ === 'undefined') {
  1505. if ((!column.checkbox) && (!column.radio)) {
  1506. return
  1507. }
  1508. }
  1509. if (!column.visible) {
  1510. return
  1511. }
  1512. if (this.options.cardView && (!column.cardVisible)) {
  1513. return
  1514. }
  1515. if (column.escape) {
  1516. value_ = Utils.escapeHTML(value_)
  1517. }
  1518. if (csses.concat([this.header.styles[j]]).length) {
  1519. style_ = ` style="${csses.concat([this.header.styles[j]]).join('; ')}"`
  1520. }
  1521. // handle td's id and class
  1522. if (item[`_${field}_id`]) {
  1523. id_ = Utils.sprintf(' id="%s"', item[`_${field}_id`])
  1524. }
  1525. if (item[`_${field}_class`]) {
  1526. class_ = Utils.sprintf(' class="%s"', item[`_${field}_class`])
  1527. }
  1528. if (item[`_${field}_rowspan`]) {
  1529. rowspan_ = Utils.sprintf(' rowspan="%s"', item[`_${field}_rowspan`])
  1530. }
  1531. if (item[`_${field}_colspan`]) {
  1532. colspan_ = Utils.sprintf(' colspan="%s"', item[`_${field}_colspan`])
  1533. }
  1534. if (item[`_${field}_title`]) {
  1535. title_ = Utils.sprintf(' title="%s"', item[`_${field}_title`])
  1536. }
  1537. cellStyle = Utils.calculateObjectValue(this.header,
  1538. this.header.cellStyles[j], [value_, item, i, field], cellStyle)
  1539. if (cellStyle.classes) {
  1540. class_ = ` class="${cellStyle.classes}"`
  1541. }
  1542. if (cellStyle.css) {
  1543. const csses_ = []
  1544. for (const key in cellStyle.css) {
  1545. csses_.push(`${key}: ${cellStyle.css[key]}`)
  1546. }
  1547. style_ = ` style="${csses_.concat(this.header.styles[j]).join('; ')}"`
  1548. }
  1549. value = Utils.calculateObjectValue(column,
  1550. this.header.formatters[j], [value_, item, i, field], value_)
  1551. if (item[`_${field}_data`] && !$.isEmptyObject(item[`_${field}_data`])) {
  1552. item[`_${field}_data`].forEach((v, k) => {
  1553. // ignore data-index
  1554. if (k === 'index') {
  1555. return
  1556. }
  1557. data_ += ` data-${k}="${v}"`
  1558. })
  1559. }
  1560. if (column.checkbox || column.radio) {
  1561. type = column.checkbox ? 'checkbox' : type
  1562. type = column.radio ? 'radio' : type
  1563. const c = column['class'] || ''
  1564. const isChecked = value === true || (value_ || value && value.checked)
  1565. const isDisabled = !column.checkboxEnabled || (value && value.disabled)
  1566. text = [
  1567. this.options.cardView
  1568. ? `<div class="card-view ${c}">`
  1569. : `<td class="bs-checkbox ${c}">`,
  1570. `<input
  1571. data-index="${i}"
  1572. name="${this.options.selectItemName}"
  1573. type="${type}"
  1574. ${Utils.sprintf('value="%s"', item[this.options.idField])}
  1575. ${Utils.sprintf('checked="%s"', isChecked ? 'checked' : undefined)}
  1576. ${Utils.sprintf('disabled="%s"', isDisabled ? 'disabled' : undefined)} />`,
  1577. this.header.formatters[j] && typeof value === 'string' ? value : '',
  1578. this.options.cardView ? '</div>' : '</td>'
  1579. ].join('')
  1580. item[this.header.stateField] = value === true || (!!value_ || (value && value.checked))
  1581. } else {
  1582. value = typeof value === 'undefined' || value === null
  1583. ? this.options.undefinedText : value
  1584. if (this.options.cardView) {
  1585. const cardTitle = this.options.showHeader
  1586. ? `<span class="title"${style}>${Utils.getFieldTitle(this.columns, field)}</span>` : ''
  1587. text = `<div class="card-view">${cardTitle}<span class="value">${value}</span></div>`
  1588. if (this.options.smartDisplay && value === '') {
  1589. text = '<div class="card-view"></div>'
  1590. }
  1591. } else {
  1592. text = `<td${id_}${class_}${style_}${data_}${rowspan_}${colspan_}${title_}>${value}</td>`
  1593. }
  1594. }
  1595. html.push(text)
  1596. })
  1597. if (this.options.cardView) {
  1598. html.push('</div></td>')
  1599. }
  1600. html.push('</tr>')
  1601. return html.join('')
  1602. }
  1603. initBody (fixedScroll) {
  1604. const data = this.getData()
  1605. this.trigger('pre-body', data)
  1606. this.$body = this.$el.find('>tbody')
  1607. if (!this.$body.length) {
  1608. this.$body = $('<tbody></tbody>').appendTo(this.$el)
  1609. }
  1610. // Fix #389 Bootstrap-table-flatJSON is not working
  1611. if (!this.options.pagination || this.options.sidePagination === 'server') {
  1612. this.pageFrom = 1
  1613. this.pageTo = data.length
  1614. }
  1615. const html = []
  1616. for (let i = this.pageFrom - 1; i < this.pageTo; i++) {
  1617. html.push(this.initRow(data[i], i, data))
  1618. }
  1619. // show no records
  1620. if (!html.length) {
  1621. this.$body.html(`<tr class="no-records-found">${Utils.sprintf('<td colspan="%s">%s</td>',
  1622. this.$header.find('th').length,
  1623. this.options.formatNoMatches())}</tr>`)
  1624. }
  1625. this.$body.html(html.join(''))
  1626. if (!fixedScroll) {
  1627. this.scrollTo(0)
  1628. }
  1629. // click to select by column
  1630. this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', (e) => {
  1631. const $td = $(e.currentTarget)
  1632. const $tr = $td.parent()
  1633. const item = this.data[$tr.data('index')]
  1634. const index = $td[0].cellIndex
  1635. const fields = this.getVisibleFields()
  1636. const field = fields[this.options.detailView && !this.options.cardView ? index - 1 : index]
  1637. const column = this.columns[this.fieldsColumnsIndex[field]]
  1638. const value = Utils.getItemField(item, field, this.options.escape)
  1639. if ($td.find('.detail-icon').length) {
  1640. return
  1641. }
  1642. this.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td)
  1643. this.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr, field)
  1644. // if click to select - then trigger the checkbox/radio click
  1645. if (
  1646. e.type === 'click' &&
  1647. this.options.clickToSelect &&
  1648. column.clickToSelect &&
  1649. !this.options.ignoreClickToSelectOn(e.target)
  1650. ) {
  1651. const $selectItem = $tr.find(Utils.sprintf('[name="%s"]', this.options.selectItemName))
  1652. if ($selectItem.length) {
  1653. $selectItem[0].click() // #144: .trigger('click') bug
  1654. }
  1655. }
  1656. })
  1657. this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', e => {
  1658. e.preventDefault()
  1659. const $this = $(e.currentTarget) // Fix #980 Detail view, when searching, returns wrong row
  1660. const $tr = $this.parent().parent()
  1661. const index = $tr.data('index')
  1662. const row = data[index]
  1663. // remove and update
  1664. if ($tr.next().is('tr.detail-view')) {
  1665. $this.find('i').attr('class', Utils.sprintf('%s %s', this.options.iconsPrefix, this.options.icons.detailOpen))
  1666. this.trigger('collapse-row', index, row, $tr.next())
  1667. $tr.next().remove()
  1668. } else {
  1669. $this.find('i').attr('class', Utils.sprintf('%s %s', this.options.iconsPrefix, this.options.icons.detailClose))
  1670. $tr.after(Utils.sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.find('td').length))
  1671. const $element = $tr.next().find('td')
  1672. const content = Utils.calculateObjectValue(this.options, this.options.detailFormatter, [index, row, $element], '')
  1673. if ($element.length === 1) {
  1674. $element.append(content)
  1675. }
  1676. this.trigger('expand-row', index, row, $element)
  1677. }
  1678. this.resetView()
  1679. return false
  1680. })
  1681. this.$selectItem = this.$body.find(Utils.sprintf('[name="%s"]', this.options.selectItemName))
  1682. this.$selectItem.off('click').on('click', e => {
  1683. e.stopImmediatePropagation()
  1684. const $this = $(e.currentTarget)
  1685. this.check_($this.prop('checked'), $this.data('index'))
  1686. })
  1687. this.header.events.forEach((events, i) => {
  1688. if (!events) {
  1689. return
  1690. }
  1691. // fix bug, if events is defined with namespace
  1692. if (typeof events === 'string') {
  1693. events = Utils.calculateObjectValue(null, events)
  1694. }
  1695. const field = this.header.fields[i]
  1696. let fieldIndex = this.getVisibleFields().indexOf(field)
  1697. if (fieldIndex === -1) {
  1698. return
  1699. }
  1700. if (this.options.detailView && !this.options.cardView) {
  1701. fieldIndex += 1
  1702. }
  1703. for (const key in events) {
  1704. this.$body.find('>tr:not(.no-records-found)').each((i, tr) => {
  1705. const $tr = $(tr)
  1706. const $td = $tr.find(this.options.cardView ? '.card-view' : 'td').eq(fieldIndex)
  1707. const index = key.indexOf(' ')
  1708. const name = key.substring(0, index)
  1709. const el = key.substring(index + 1)
  1710. const func = events[key]
  1711. $td.find(el).off(name).on(name, e => {
  1712. const index = $tr.data('index')
  1713. const row = this.data[index]
  1714. const value = row[field]
  1715. func.apply(this, [e, value, row, index])
  1716. })
  1717. })
  1718. }
  1719. })
  1720. this.updateSelected()
  1721. this.resetView()
  1722. this.trigger('post-body', data)
  1723. }
  1724. initServer (silent, query, url) {
  1725. let data = {}
  1726. const index = this.header.fields.indexOf(this.options.sortName)
  1727. let params = {
  1728. searchText: this.searchText,
  1729. sortName: this.options.sortName,
  1730. sortOrder: this.options.sortOrder
  1731. }
  1732. let request
  1733. if (this.header.sortNames[index]) {
  1734. params.sortName = this.header.sortNames[index]
  1735. }
  1736. if (this.options.pagination && this.options.sidePagination === 'server') {
  1737. params.pageSize = this.options.pageSize === this.options.formatAllRows()
  1738. ? this.options.totalRows : this.options.pageSize
  1739. params.pageNumber = this.options.pageNumber
  1740. }
  1741. if (!(url || this.options.url) && !this.options.ajax) {
  1742. return
  1743. }
  1744. if (this.options.queryParamsType === 'limit') {
  1745. params = {
  1746. search: params.searchText,
  1747. sort: params.sortName,
  1748. order: params.sortOrder
  1749. }
  1750. if (this.options.pagination && this.options.sidePagination === 'server') {
  1751. params.offset = this.options.pageSize === this.options.formatAllRows()
  1752. ? 0 : this.options.pageSize * (this.options.pageNumber - 1)
  1753. params.limit = this.options.pageSize === this.options.formatAllRows()
  1754. ? this.options.totalRows : this.options.pageSize
  1755. if (params.limit === 0) {
  1756. delete params.limit
  1757. }
  1758. }
  1759. }
  1760. if (!($.isEmptyObject(this.filterColumnsPartial))) {
  1761. params.filter = JSON.stringify(this.filterColumnsPartial, null)
  1762. }
  1763. data = Utils.calculateObjectValue(this.options, this.options.queryParams, [params], data)
  1764. $.extend(data, query || {})
  1765. // false to stop request
  1766. if (data === false) {
  1767. return
  1768. }
  1769. if (!silent) {
  1770. this.$tableLoading.show()
  1771. }
  1772. request = $.extend({}, Utils.calculateObjectValue(null, this.options.ajaxOptions), {
  1773. type: this.options.method,
  1774. url: url || this.options.url,
  1775. data: this.options.contentType === 'application/json' && this.options.method === 'post'
  1776. ? JSON.stringify(data) : data,
  1777. cache: this.options.cache,
  1778. contentType: this.options.contentType,
  1779. dataType: this.options.dataType,
  1780. success: res => {
  1781. res = Utils.calculateObjectValue(this.options, this.options.responseHandler, [res], res)
  1782. this.load(res)
  1783. this.trigger('load-success', res)
  1784. if (!silent) this.$tableLoading.hide()
  1785. },
  1786. error: res => {
  1787. let data = []
  1788. if (this.options.sidePagination === 'server') {
  1789. data = {}
  1790. data[this.options.totalField] = 0
  1791. data[this.options.dataField] = []
  1792. }
  1793. this.load(data)
  1794. this.trigger('load-error', res.status, res)
  1795. if (!silent) this.$tableLoading.hide()
  1796. }
  1797. })
  1798. if (this.options.ajax) {
  1799. Utils.calculateObjectValue(this, this.options.ajax, [request], null)
  1800. } else {
  1801. if (this._xhr && this._xhr.readyState !== 4) {
  1802. this._xhr.abort()
  1803. }
  1804. this._xhr = $.ajax(request)
  1805. }
  1806. }
  1807. initSearchText () {
  1808. if (this.options.search) {
  1809. this.searchText = ''
  1810. if (this.options.searchText !== '') {
  1811. const $search = this.$toolbar.find('.search input')
  1812. $search.val(this.options.searchText)
  1813. this.onSearch({currentTarget: $search, firedByInitSearchText: true})
  1814. }
  1815. }
  1816. }
  1817. getCaret () {
  1818. this.$header.find('th').each((i, th) => {
  1819. $(th).find('.sortable').removeClass('desc asc')
  1820. .addClass($(th).data('field') === this.options.sortName
  1821. ? this.options.sortOrder : 'both')
  1822. })
  1823. }
  1824. updateSelected () {
  1825. const checkAll = this.$selectItem.filter(':enabled').length &&
  1826. this.$selectItem.filter(':enabled').length ===
  1827. this.$selectItem.filter(':enabled').filter(':checked').length
  1828. this.$selectAll.add(this.$selectAll_).prop('checked', checkAll)
  1829. this.$selectItem.each((i, el) => {
  1830. $(el).closest('tr')[$(el).prop('checked') ? 'addClass' : 'removeClass']('selected')
  1831. })
  1832. }
  1833. updateRows () {
  1834. this.$selectItem.each((i, el) => {
  1835. this.data[$(el).data('index')][this.header.stateField] = $(el).prop('checked')
  1836. })
  1837. }
  1838. resetRows () {
  1839. for (let row of this.data) {
  1840. this.$selectAll.prop('checked', false)
  1841. this.$selectItem.prop('checked', false)
  1842. if (this.header.stateField) {
  1843. row[this.header.stateField] = false
  1844. }
  1845. }
  1846. this.initHiddenRows()
  1847. }
  1848. trigger (name, ...args) {
  1849. name += '.bs.table'
  1850. this.options[BootstrapTable.EVENTS[name]].apply(this.options, args)
  1851. this.$el.trigger($.Event(name), args)
  1852. this.options.onAll(name, args)
  1853. this.$el.trigger($.Event('all.bs.table'), [name, args])
  1854. }
  1855. resetHeader () {
  1856. // fix #61: the hidden table reset header bug.
  1857. // fix bug: get $el.css('width') error sometime (height = 500)
  1858. clearTimeout(this.timeoutId_)
  1859. this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), this.$el.is(':hidden') ? 100 : 0)
  1860. }
  1861. fitHeader () {
  1862. let fixedBody
  1863. let scrollWidth
  1864. let focused
  1865. let focusedTemp
  1866. if (this.$el.is(':hidden')) {
  1867. this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), 100)
  1868. return
  1869. }
  1870. fixedBody = this.$tableBody.get(0)
  1871. scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
  1872. fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight()
  1873. ? Utils.getScrollBarWidth() : 0
  1874. this.$el.css('margin-top', -this.$header.outerHeight())
  1875. focused = $(':focus')
  1876. if (focused.length > 0) {
  1877. const $th = focused.parents('th')
  1878. if ($th.length > 0) {
  1879. const dataField = $th.attr('data-field')
  1880. if (dataField !== undefined) {
  1881. const $headerTh = this.$header.find(`[data-field='${dataField}']`)
  1882. if ($headerTh.length > 0) {
  1883. $headerTh.find(':input').addClass('focus-temp')
  1884. }
  1885. }
  1886. }
  1887. }
  1888. this.$header_ = this.$header.clone(true, true)
  1889. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]')
  1890. this.$tableHeader.css({
  1891. 'margin-right': scrollWidth
  1892. }).find('table').css('width', this.$el.outerWidth())
  1893. .html('').attr('class', this.$el.attr('class'))
  1894. .append(this.$header_)
  1895. focusedTemp = $('.focus-temp:visible:eq(0)')
  1896. if (focusedTemp.length > 0) {
  1897. focusedTemp.focus()
  1898. this.$header.find('.focus-temp').removeClass('focus-temp')
  1899. }
  1900. // fix bug: $.data() is not working as expected after $.append()
  1901. this.$header.find('th[data-field]').each((i, el) => {
  1902. this.$header_.find(Utils.sprintf('th[data-field="%s"]', $(el).data('field'))).data($(el).data())
  1903. })
  1904. const visibleFields = this.getVisibleFields()
  1905. const $ths = this.$header_.find('th')
  1906. this.$body.find('>tr:first-child:not(.no-records-found) > *').each((i, el) => {
  1907. const $this = $(el)
  1908. let index = i
  1909. if (this.options.detailView && !this.options.cardView) {
  1910. if (i === 0) {
  1911. this.$header_.find('th.detail').find('.fht-cell').width($this.innerWidth())
  1912. }
  1913. index = i - 1
  1914. }
  1915. if (index === -1) {
  1916. return
  1917. }
  1918. let $th = this.$header_.find(Utils.sprintf('th[data-field="%s"]', visibleFields[index]))
  1919. if ($th.length > 1) {
  1920. $th = $($ths[$this[0].cellIndex])
  1921. }
  1922. const zoomWidth = $th.width() - $th.find('.fht-cell').width()
  1923. $th.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1924. })
  1925. this.horizontalScroll()
  1926. this.trigger('post-header')
  1927. }
  1928. resetFooter () {
  1929. const data = this.getData()
  1930. const html = []
  1931. if (!this.options.showFooter || this.options.cardView) { // do nothing
  1932. return
  1933. }
  1934. if (!this.options.cardView && this.options.detailView) {
  1935. html.push('<td><div class="th-inner">&nbsp;</div><div class="fht-cell"></div></td>')
  1936. }
  1937. for (let column of this.columns) {
  1938. let key
  1939. let // footer align style
  1940. falign = ''
  1941. let valign = ''
  1942. const csses = []
  1943. let style = {}
  1944. const class_ = Utils.sprintf(' class="%s"', column['class'])
  1945. if (!column.visible) {
  1946. return
  1947. }
  1948. if (this.options.cardView && (!column.cardVisible)) {
  1949. return
  1950. }
  1951. falign = Utils.sprintf('text-align: %s; ', column.falign ? column.falign : column.align)
  1952. valign = Utils.sprintf('vertical-align: %s; ', column.valign)
  1953. style = Utils.calculateObjectValue(null, this.options.footerStyle)
  1954. if (style && style.css) {
  1955. for (key in style.css) {
  1956. csses.push(`${key}: ${style.css[key]}`)
  1957. }
  1958. }
  1959. html.push('<td', class_, Utils.sprintf(' style="%s"', falign + valign + csses.concat().join('; ')), '>')
  1960. html.push('<div class="th-inner">')
  1961. html.push(Utils.calculateObjectValue(column, column.footerFormatter, [data], '&nbsp;') || '&nbsp;')
  1962. html.push('</div>')
  1963. html.push('<div class="fht-cell"></div>')
  1964. html.push('</div>')
  1965. html.push('</td>')
  1966. }
  1967. this.$tableFooter.find('tr').html(html.join(''))
  1968. this.$tableFooter.show()
  1969. clearTimeout(this.timeoutFooter_)
  1970. this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this),
  1971. this.$el.is(':hidden') ? 100 : 0)
  1972. }
  1973. fitFooter () {
  1974. let $footerTd
  1975. let elWidth
  1976. let scrollWidth
  1977. clearTimeout(this.timeoutFooter_)
  1978. if (this.$el.is(':hidden')) {
  1979. this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), 100)
  1980. return
  1981. }
  1982. elWidth = this.$el.css('width')
  1983. scrollWidth = elWidth > this.$tableBody.width() ? Utils.getScrollBarWidth() : 0
  1984. this.$tableFooter.css({
  1985. 'margin-right': scrollWidth
  1986. }).find('table').css('width', elWidth)
  1987. .attr('class', this.$el.attr('class'))
  1988. $footerTd = this.$tableFooter.find('td')
  1989. this.$body.find('>tr:first-child:not(.no-records-found) > *').each((i, el) => {
  1990. const $this = $(el)
  1991. $footerTd.eq(i).find('.fht-cell').width($this.innerWidth())
  1992. })
  1993. this.horizontalScroll()
  1994. }
  1995. horizontalScroll () {
  1996. // horizontal scroll event
  1997. // TODO: it's probably better improving the layout than binding to scroll event
  1998. this.trigger('scroll-body')
  1999. this.$tableBody.off('scroll').on('scroll', e => {
  2000. if (this.options.showHeader && this.options.height) {
  2001. this.$tableHeader.scrollLeft($(e.currentTarget).scrollLeft())
  2002. }
  2003. if (this.options.showFooter && !this.options.cardView) {
  2004. this.$tableFooter.scrollLeft($(e.currentTarget).scrollLeft())
  2005. }
  2006. })
  2007. }
  2008. toggleColumn (index, checked, needUpdate) {
  2009. if (index === -1) {
  2010. return
  2011. }
  2012. this.columns[index].visible = checked
  2013. this.initHeader()
  2014. this.initSearch()
  2015. this.initPagination()
  2016. this.initBody()
  2017. if (this.options.showColumns) {
  2018. const $items = this.$toolbar.find('.keep-open input').prop('disabled', false)
  2019. if (needUpdate) {
  2020. $items.filter(Utils.sprintf('[value="%s"]', index)).prop('checked', checked)
  2021. }
  2022. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  2023. $items.filter(':checked').prop('disabled', true)
  2024. }
  2025. }
  2026. }
  2027. getVisibleFields () {
  2028. const visibleFields = []
  2029. for (let field of this.header.fields) {
  2030. const column = this.columns[this.fieldsColumnsIndex[field]]
  2031. if (!column.visible) {
  2032. continue
  2033. }
  2034. visibleFields.push(field)
  2035. }
  2036. return visibleFields
  2037. }
  2038. // PUBLIC FUNCTION DEFINITION
  2039. // =======================
  2040. resetView (params) {
  2041. let padding = 0
  2042. if (params && params.height) {
  2043. this.options.height = params.height
  2044. }
  2045. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  2046. this.$selectItem.length === this.$selectItem.filter(':checked').length)
  2047. if (this.options.height) {
  2048. const toolbarHeight = this.$toolbar.outerHeight(true)
  2049. const paginationHeight = this.$pagination.outerHeight(true)
  2050. const height = this.options.height - toolbarHeight - paginationHeight
  2051. this.$tableContainer.css('height', `${height}px`)
  2052. }
  2053. if (this.options.cardView) {
  2054. // remove the element css
  2055. this.$el.css('margin-top', '0')
  2056. this.$tableContainer.css('padding-bottom', '0')
  2057. this.$tableFooter.hide()
  2058. return
  2059. }
  2060. if (this.options.showHeader && this.options.height) {
  2061. this.$tableHeader.show()
  2062. this.resetHeader()
  2063. padding += this.$header.outerHeight()
  2064. } else {
  2065. this.$tableHeader.hide()
  2066. this.trigger('post-header')
  2067. }
  2068. if (this.options.showFooter) {
  2069. this.resetFooter()
  2070. if (this.options.height) {
  2071. padding += this.$tableFooter.outerHeight() + 1
  2072. }
  2073. }
  2074. // Assign the correct sortable arrow
  2075. this.getCaret()
  2076. this.$tableContainer.css('padding-bottom', `${padding}px`)
  2077. this.trigger('reset-view')
  2078. }
  2079. getData (useCurrentPage) {
  2080. let data = this.options.data
  2081. if (this.searchText || this.options.sortName || !$.isEmptyObject(this.filterColumns) || !$.isEmptyObject(this.filterColumnsPartial)) {
  2082. data = this.data
  2083. }
  2084. if (useCurrentPage) {
  2085. return data.slice(this.pageFrom - 1, this.pageTo)
  2086. }
  2087. return data
  2088. }
  2089. load (data) {
  2090. let fixedScroll = false
  2091. // #431: support pagination
  2092. if (this.options.pagination && this.options.sidePagination === 'server') {
  2093. this.options.totalRows = data[this.options.totalField]
  2094. }
  2095. fixedScroll = data.fixedScroll
  2096. data = Array.isArray(data) ? data : data[this.options.dataField]
  2097. this.initData(data)
  2098. this.initSearch()
  2099. this.initPagination()
  2100. this.initBody(fixedScroll)
  2101. }
  2102. append (data) {
  2103. this.initData(data, 'append')
  2104. this.initSearch()
  2105. this.initPagination()
  2106. this.initSort()
  2107. this.initBody(true)
  2108. }
  2109. prepend (data) {
  2110. this.initData(data, 'prepend')
  2111. this.initSearch()
  2112. this.initPagination()
  2113. this.initSort()
  2114. this.initBody(true)
  2115. }
  2116. remove (params) {
  2117. const len = this.options.data.length
  2118. let i
  2119. let row
  2120. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
  2121. return
  2122. }
  2123. for (i = len - 1; i >= 0; i--) {
  2124. row = this.options.data[i]
  2125. if (!row.hasOwnProperty(params.field)) {
  2126. continue
  2127. }
  2128. if (params.values.includes(row[params.field])) {
  2129. this.options.data.splice(i, 1)
  2130. if (this.options.sidePagination === 'server') {
  2131. this.options.totalRows -= 1
  2132. }
  2133. }
  2134. }
  2135. if (len === this.options.data.length) {
  2136. return
  2137. }
  2138. this.initSearch()
  2139. this.initPagination()
  2140. this.initSort()
  2141. this.initBody(true)
  2142. }
  2143. removeAll () {
  2144. if (this.options.data.length > 0) {
  2145. this.options.data.splice(0, this.options.data.length)
  2146. this.initSearch()
  2147. this.initPagination()
  2148. this.initBody(true)
  2149. }
  2150. }
  2151. getRowByUniqueId (id) {
  2152. const uniqueId = this.options.uniqueId
  2153. const len = this.options.data.length
  2154. let dataRow = null
  2155. let i
  2156. let row
  2157. let rowUniqueId
  2158. for (i = len - 1; i >= 0; i--) {
  2159. row = this.options.data[i]
  2160. if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column
  2161. rowUniqueId = row[uniqueId]
  2162. } else if (row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property
  2163. rowUniqueId = row._data[uniqueId]
  2164. } else {
  2165. continue
  2166. }
  2167. if (typeof rowUniqueId === 'string') {
  2168. id = id.toString()
  2169. } else if (typeof rowUniqueId === 'number') {
  2170. if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) {
  2171. id = parseInt(id)
  2172. } else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) {
  2173. id = parseFloat(id)
  2174. }
  2175. }
  2176. if (rowUniqueId === id) {
  2177. dataRow = row
  2178. break
  2179. }
  2180. }
  2181. return dataRow
  2182. }
  2183. removeByUniqueId (id) {
  2184. const len = this.options.data.length
  2185. const row = this.getRowByUniqueId(id)
  2186. if (row) {
  2187. this.options.data.splice(this.options.data.indexOf(row), 1)
  2188. }
  2189. if (len === this.options.data.length) {
  2190. return
  2191. }
  2192. this.initSearch()
  2193. this.initPagination()
  2194. this.initBody(true)
  2195. }
  2196. updateByUniqueId (params) {
  2197. const allParams = Array.isArray(params) ? params : [ params ]
  2198. for (let params of allParams) {
  2199. let rowId
  2200. if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
  2201. continue
  2202. }
  2203. rowId = this.options.data.indexOf(this.getRowByUniqueId(params.id))
  2204. if (rowId === -1) {
  2205. continue
  2206. }
  2207. $.extend(this.options.data[rowId], params.row)
  2208. }
  2209. this.initSearch()
  2210. this.initPagination()
  2211. this.initSort()
  2212. this.initBody(true)
  2213. }
  2214. refreshColumnTitle (params) {
  2215. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('title')) {
  2216. return
  2217. }
  2218. this.columns[this.fieldsColumnsIndex[params.field]].title =
  2219. this.options.escape ? Utils.escapeHTML(params.title) : params.title
  2220. if (this.columns[this.fieldsColumnsIndex[params.field]].visible) {
  2221. const header = this.options.height !== undefined ? this.$tableHeader : this.$header
  2222. header.find('th[data-field]').each((i, el) => {
  2223. if ($(el).data('field') === params.field) {
  2224. $($(el).find('.th-inner')[0]).text(params.title)
  2225. return false
  2226. }
  2227. })
  2228. }
  2229. }
  2230. insertRow (params) {
  2231. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  2232. return
  2233. }
  2234. this.options.data.splice(params.index, 0, params.row)
  2235. this.initSearch()
  2236. this.initPagination()
  2237. this.initSort()
  2238. this.initBody(true)
  2239. }
  2240. updateRow (params) {
  2241. const allParams = Array.isArray(params) ? params : [ params ]
  2242. for (let params of allParams) {
  2243. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  2244. continue
  2245. }
  2246. $.extend(this.options.data[params.index], params.row)
  2247. }
  2248. this.initSearch()
  2249. this.initPagination()
  2250. this.initSort()
  2251. this.initBody(true)
  2252. }
  2253. initHiddenRows () {
  2254. this.hiddenRows = []
  2255. }
  2256. showRow (params) {
  2257. this.toggleRow(params, true)
  2258. }
  2259. hideRow (params) {
  2260. this.toggleRow(params, false)
  2261. }
  2262. toggleRow (params, visible) {
  2263. let row
  2264. let index
  2265. if (params.hasOwnProperty('index')) {
  2266. row = this.getData()[params.index]
  2267. } else if (params.hasOwnProperty('uniqueId')) {
  2268. row = this.getRowByUniqueId(params.uniqueId)
  2269. }
  2270. if (!row) {
  2271. return
  2272. }
  2273. index = this.hiddenRows.indexOf(row)
  2274. if (!visible && index === -1) {
  2275. this.hiddenRows.push(row)
  2276. } else if (visible && index > -1) {
  2277. this.hiddenRows.splice(index, 1)
  2278. }
  2279. this.initBody(true)
  2280. }
  2281. getHiddenRows (show) {
  2282. const data = this.getData()
  2283. const rows = []
  2284. for (let row of data) {
  2285. if (this.hiddenRows.includes(row)) {
  2286. rows.push(row)
  2287. }
  2288. }
  2289. this.hiddenRows = rows
  2290. return rows
  2291. }
  2292. mergeCells (options) {
  2293. const row = options.index
  2294. let col = this.getVisibleFields().indexOf(options.field)
  2295. const rowspan = options.rowspan || 1
  2296. const colspan = options.colspan || 1
  2297. let i
  2298. let j
  2299. const $tr = this.$body.find('>tr')
  2300. let $td
  2301. if (this.options.detailView && !this.options.cardView) {
  2302. col += 1
  2303. }
  2304. $td = $tr.eq(row).find('>td').eq(col)
  2305. if (row < 0 || col < 0 || row >= this.data.length) {
  2306. return
  2307. }
  2308. for (i = row; i < row + rowspan; i++) {
  2309. for (j = col; j < col + colspan; j++) {
  2310. $tr.eq(i).find('>td').eq(j).hide()
  2311. }
  2312. }
  2313. $td.attr('rowspan', rowspan).attr('colspan', colspan).show()
  2314. }
  2315. updateCell (params) {
  2316. if (!params.hasOwnProperty('index') ||
  2317. !params.hasOwnProperty('field') ||
  2318. !params.hasOwnProperty('value')) {
  2319. return
  2320. }
  2321. this.data[params.index][params.field] = params.value
  2322. if (params.reinit === false) {
  2323. return
  2324. }
  2325. this.initSort()
  2326. this.initBody(true)
  2327. }
  2328. updateCellById (params) {
  2329. if (!params.hasOwnProperty('id') ||
  2330. !params.hasOwnProperty('field') ||
  2331. !params.hasOwnProperty('value')) {
  2332. return
  2333. }
  2334. const allParams = Array.isArray(params) ? params : [ params ]
  2335. allParams.forEach(({id, field, value}) => {
  2336. let rowId
  2337. rowId = this.options.data.indexOf(this.getRowByUniqueId(id))
  2338. if (rowId === -1) {
  2339. return
  2340. }
  2341. this.data[rowId][field] = value
  2342. })
  2343. if (params.reinit === false) {
  2344. return
  2345. }
  2346. this.initSort()
  2347. this.initBody(true)
  2348. }
  2349. getOptions () {
  2350. // Deep copy
  2351. return $.extend(true, {}, this.options)
  2352. }
  2353. getSelections () {
  2354. // fix #2424: from html with checkbox
  2355. return this.options.data.filter(row =>
  2356. row[this.header.stateField] === true)
  2357. }
  2358. getAllSelections () {
  2359. return this.options.data.filter(row => row[this.header.stateField])
  2360. }
  2361. checkAll () {
  2362. this.checkAll_(true)
  2363. }
  2364. uncheckAll () {
  2365. this.checkAll_(false)
  2366. }
  2367. checkInvert () {
  2368. const $items = this.$selectItem.filter(':enabled')
  2369. let checked = $items.filter(':checked')
  2370. $items.each((i, el) => {
  2371. $(el).prop('checked', !$(el).prop('checked'))
  2372. })
  2373. this.updateRows()
  2374. this.updateSelected()
  2375. this.trigger('uncheck-some', checked)
  2376. checked = this.getSelections()
  2377. this.trigger('check-some', checked)
  2378. }
  2379. checkAll_ (checked) {
  2380. let rows
  2381. if (!checked) {
  2382. rows = this.getSelections()
  2383. }
  2384. this.$selectAll.add(this.$selectAll_).prop('checked', checked)
  2385. this.$selectItem.filter(':enabled').prop('checked', checked)
  2386. this.updateRows()
  2387. if (checked) {
  2388. rows = this.getSelections()
  2389. }
  2390. this.trigger(checked ? 'check-all' : 'uncheck-all', rows)
  2391. }
  2392. check (index) {
  2393. this.check_(true, index)
  2394. }
  2395. uncheck (index) {
  2396. this.check_(false, index)
  2397. }
  2398. check_ (checked, index) {
  2399. const $el = this.$selectItem.filter(`[data-index="${index}"]`)
  2400. const row = this.data[index]
  2401. if ($el.is(':radio') || this.options.singleSelect) {
  2402. for (let r of this.options.data) {
  2403. r[this.header.stateField] = false
  2404. }
  2405. this.$selectItem.filter(':checked').not($el).prop('checked', false)
  2406. }
  2407. row[this.header.stateField] = checked
  2408. $el.prop('checked', checked)
  2409. this.updateSelected()
  2410. this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el)
  2411. }
  2412. checkBy (obj) {
  2413. this.checkBy_(true, obj)
  2414. }
  2415. uncheckBy (obj) {
  2416. this.checkBy_(false, obj)
  2417. }
  2418. checkBy_ (checked, obj) {
  2419. if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
  2420. return
  2421. }
  2422. const rows = []
  2423. this.options.data.forEach((row, i) => {
  2424. if (!row.hasOwnProperty(obj.field)) {
  2425. return false
  2426. }
  2427. if (obj.values.includes(row[obj.field])) {
  2428. const $el = this.$selectItem.filter(':enabled')
  2429. .filter(Utils.sprintf('[data-index="%s"]', i)).prop('checked', checked)
  2430. row[this.header.stateField] = checked
  2431. rows.push(row)
  2432. this.trigger(checked ? 'check' : 'uncheck', row, $el)
  2433. }
  2434. })
  2435. this.updateSelected()
  2436. this.trigger(checked ? 'check-some' : 'uncheck-some', rows)
  2437. }
  2438. destroy () {
  2439. this.$el.insertBefore(this.$container)
  2440. $(this.options.toolbar).insertBefore(this.$el)
  2441. this.$container.next().remove()
  2442. this.$container.remove()
  2443. this.$el.html(this.$el_.html())
  2444. .css('margin-top', '0')
  2445. .attr('class', this.$el_.attr('class') || '') // reset the class
  2446. }
  2447. showLoading () {
  2448. this.$tableLoading.show()
  2449. }
  2450. hideLoading () {
  2451. this.$tableLoading.hide()
  2452. }
  2453. togglePagination () {
  2454. this.options.pagination = !this.options.pagination
  2455. const button = this.$toolbar.find('button[name="paginationSwitch"] i')
  2456. if (this.options.pagination) {
  2457. button.attr('class', `${this.options.iconsPrefix} ${this.options.icons.paginationSwitchDown}`)
  2458. } else {
  2459. button.attr('class', `${this.options.iconsPrefix} ${this.options.icons.paginationSwitchUp}`)
  2460. }
  2461. this.updatePagination()
  2462. }
  2463. toggleFullscreen () {
  2464. this.$el.closest('.bootstrap-table').toggleClass('fullscreen')
  2465. }
  2466. refresh (params) {
  2467. if (params && params.url) {
  2468. this.options.url = params.url
  2469. }
  2470. if (params && params.pageNumber) {
  2471. this.options.pageNumber = params.pageNumber
  2472. }
  2473. if (params && params.pageSize) {
  2474. this.options.pageSize = params.pageSize
  2475. }
  2476. this.initServer(params && params.silent,
  2477. params && params.query, params && params.url)
  2478. this.trigger('refresh', params)
  2479. }
  2480. resetWidth () {
  2481. if (this.options.showHeader && this.options.height) {
  2482. this.fitHeader()
  2483. }
  2484. if (this.options.showFooter && !this.options.cardView) {
  2485. this.fitFooter()
  2486. }
  2487. }
  2488. showColumn (field) {
  2489. this.toggleColumn(this.fieldsColumnsIndex[field], true, true)
  2490. }
  2491. hideColumn (field) {
  2492. this.toggleColumn(this.fieldsColumnsIndex[field], false, true)
  2493. }
  2494. getHiddenColumns () {
  2495. return this.columns.filter(({visible}) => !visible)
  2496. }
  2497. getVisibleColumns () {
  2498. return this.columns.filter(({visible}) => visible)
  2499. }
  2500. toggleAllColumns (visible) {
  2501. for (let column of this.columns) {
  2502. column.visible = visible
  2503. }
  2504. this.initHeader()
  2505. this.initSearch()
  2506. this.initPagination()
  2507. this.initBody()
  2508. if (this.options.showColumns) {
  2509. const $items = this.$toolbar.find('.keep-open input').prop('disabled', false)
  2510. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  2511. $items.filter(':checked').prop('disabled', true)
  2512. }
  2513. }
  2514. }
  2515. showAllColumns () {
  2516. this.toggleAllColumns(true)
  2517. }
  2518. hideAllColumns () {
  2519. this.toggleAllColumns(false)
  2520. }
  2521. filterBy (columns) {
  2522. this.filterColumns = $.isEmptyObject(columns) ? {} : columns
  2523. this.options.pageNumber = 1
  2524. this.initSearch()
  2525. this.updatePagination()
  2526. }
  2527. scrollTo (value) {
  2528. if (typeof value === 'string') {
  2529. value = value === 'bottom' ? this.$tableBody[0].scrollHeight : 0
  2530. }
  2531. if (typeof value === 'number') {
  2532. this.$tableBody.scrollTop(value)
  2533. }
  2534. if (typeof value === 'undefined') {
  2535. return this.$tableBody.scrollTop()
  2536. }
  2537. }
  2538. getScrollPosition () {
  2539. return this.scrollTo()
  2540. }
  2541. selectPage (page) {
  2542. if (page > 0 && page <= this.options.totalPages) {
  2543. this.options.pageNumber = page
  2544. this.updatePagination()
  2545. }
  2546. }
  2547. prevPage () {
  2548. if (this.options.pageNumber > 1) {
  2549. this.options.pageNumber--
  2550. this.updatePagination()
  2551. }
  2552. }
  2553. nextPage () {
  2554. if (this.options.pageNumber < this.options.totalPages) {
  2555. this.options.pageNumber++
  2556. this.updatePagination()
  2557. }
  2558. }
  2559. toggleView () {
  2560. this.options.cardView = !this.options.cardView
  2561. this.initHeader()
  2562. // Fixed remove toolbar when click cardView button.
  2563. // this.initToolbar();
  2564. const $icon = this.$toolbar.find('button[name="toggle"] i')
  2565. if (this.options.cardView) {
  2566. $icon.removeClass(this.options.icons.toggleOff)
  2567. $icon.addClass(this.options.icons.toggleOn)
  2568. } else {
  2569. $icon.removeClass(this.options.icons.toggleOn)
  2570. $icon.addClass(this.options.icons.toggleOff)
  2571. }
  2572. this.initBody()
  2573. this.trigger('toggle', this.options.cardView)
  2574. }
  2575. refreshOptions (options) {
  2576. // If the objects are equivalent then avoid the call of destroy / init methods
  2577. if (Utils.compareObjects(this.options, options, true)) {
  2578. return
  2579. }
  2580. this.options = $.extend(this.options, options)
  2581. this.trigger('refresh-options', this.options)
  2582. this.destroy()
  2583. this.init()
  2584. }
  2585. resetSearch (text) {
  2586. const $search = this.$toolbar.find('.search input')
  2587. $search.val(text || '')
  2588. this.onSearch({currentTarget: $search})
  2589. }
  2590. expandRow_ (expand, index) {
  2591. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"]', index))
  2592. if ($tr.next().is('tr.detail-view') === (!expand)) {
  2593. $tr.find('> td > .detail-icon').click()
  2594. }
  2595. }
  2596. expandRow (index) {
  2597. this.expandRow_(true, index)
  2598. }
  2599. collapseRow (index) {
  2600. this.expandRow_(false, index)
  2601. }
  2602. expandAllRows (isSubTable) {
  2603. if (isSubTable) {
  2604. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"]', 0))
  2605. let detailIcon = null
  2606. let executeInterval = false
  2607. let idInterval = -1
  2608. if (!$tr.next().is('tr.detail-view')) {
  2609. $tr.find('> td > .detail-icon').click()
  2610. executeInterval = true
  2611. } else if (!$tr.next().next().is('tr.detail-view')) {
  2612. $tr.next().find('.detail-icon').click()
  2613. executeInterval = true
  2614. }
  2615. if (executeInterval) {
  2616. try {
  2617. idInterval = setInterval(() => {
  2618. detailIcon = this.$body.find('tr.detail-view').last().find('.detail-icon')
  2619. if (detailIcon.length > 0) {
  2620. detailIcon.click()
  2621. } else {
  2622. clearInterval(idInterval)
  2623. }
  2624. }, 1)
  2625. } catch (ex) {
  2626. clearInterval(idInterval)
  2627. }
  2628. }
  2629. } else {
  2630. const trs = this.$body.children()
  2631. for (let i = 0; i < trs.length; i++) {
  2632. this.expandRow_(true, $(trs[i]).data('index'))
  2633. }
  2634. }
  2635. }
  2636. collapseAllRows (isSubTable) {
  2637. if (isSubTable) {
  2638. this.expandRow_(false, 0)
  2639. } else {
  2640. const trs = this.$body.children()
  2641. for (let i = 0; i < trs.length; i++) {
  2642. this.expandRow_(false, $(trs[i]).data('index'))
  2643. }
  2644. }
  2645. }
  2646. updateFormatText (name, text) {
  2647. if (this.options[Utils.sprintf('format%s', name)]) {
  2648. if (typeof text === 'string') {
  2649. this.options[Utils.sprintf('format%s', name)] = () => text
  2650. } else if (typeof text === 'function') {
  2651. this.options[Utils.sprintf('format%s', name)] = text
  2652. }
  2653. }
  2654. this.initToolbar()
  2655. this.initPagination()
  2656. this.initBody()
  2657. }
  2658. }
  2659. BootstrapTable.DEFAULTS = DEFAULTS
  2660. BootstrapTable.LOCALES = LOCALES
  2661. BootstrapTable.COLUMN_DEFAULTS = COLUMN_DEFAULTS
  2662. BootstrapTable.EVENTS = EVENTS
  2663. // BOOTSTRAP TABLE PLUGIN DEFINITION
  2664. // =======================
  2665. const allowedMethods = [
  2666. 'getOptions',
  2667. 'getSelections', 'getAllSelections', 'getData',
  2668. 'load', 'append', 'prepend', 'remove', 'removeAll',
  2669. 'insertRow', 'updateRow', 'updateCell',
  2670. 'updateByUniqueId', 'removeByUniqueId',
  2671. 'getRowByUniqueId', 'showRow', 'hideRow', 'getHiddenRows',
  2672. 'mergeCells', 'refreshColumnTitle',
  2673. 'checkAll', 'uncheckAll', 'checkInvert',
  2674. 'check', 'uncheck',
  2675. 'checkBy', 'uncheckBy',
  2676. 'refresh',
  2677. 'resetView',
  2678. 'resetWidth',
  2679. 'destroy',
  2680. 'showLoading', 'hideLoading',
  2681. 'showColumn', 'hideColumn',
  2682. 'getHiddenColumns', 'getVisibleColumns',
  2683. 'showAllColumns', 'hideAllColumns',
  2684. 'filterBy',
  2685. 'scrollTo',
  2686. 'getScrollPosition',
  2687. 'selectPage', 'prevPage', 'nextPage',
  2688. 'togglePagination',
  2689. 'toggleView',
  2690. 'refreshOptions',
  2691. 'resetSearch',
  2692. 'expandRow', 'collapseRow',
  2693. 'expandAllRows', 'collapseAllRows',
  2694. 'updateFormatText', 'updateCellById'
  2695. ]
  2696. $.BootstrapTable = BootstrapTable
  2697. $.fn.bootstrapTable = function (option, ...args) {
  2698. let value
  2699. this.each((i, el) => {
  2700. let data = $(el).data('bootstrap.table')
  2701. const options = $.extend({}, BootstrapTable.DEFAULTS, $(el).data(),
  2702. typeof option === 'object' && option)
  2703. if (typeof option === 'string') {
  2704. if (!allowedMethods.includes(option)) {
  2705. throw new Error('Unknown method: ' + option)
  2706. }
  2707. if (!data) {
  2708. return
  2709. }
  2710. value = data[option].apply(data, args)
  2711. if (option === 'destroy') {
  2712. $(el).removeData('bootstrap.table')
  2713. }
  2714. }
  2715. if (!data) {
  2716. $(el).data('bootstrap.table', (data = new $.BootstrapTable(el, options)))
  2717. }
  2718. })
  2719. return typeof value === 'undefined' ? this : value
  2720. }
  2721. $.fn.bootstrapTable.Constructor = BootstrapTable
  2722. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS
  2723. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS
  2724. $.fn.bootstrapTable.locales = BootstrapTable.LOCALES
  2725. $.fn.bootstrapTable.methods = allowedMethods
  2726. $.fn.bootstrapTable.utils = Utils
  2727. // BOOTSTRAP TABLE INIT
  2728. // =======================
  2729. $(() => {
  2730. $('[data-toggle="table"]').bootstrapTable()
  2731. })
  2732. })(jQuery)