bootstrap-table.js 95 KB

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