bootstrap-table.js 98 KB

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