bootstrap-table.js 96 KB

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