bootstrap-table.js 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240
  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 [i, it] of items.entries()) {
  225. if (JSON.stringify(it) === JSON.stringify(item)) {
  226. return i
  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><tr></tr></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.classes.split(' ').includes('table-bordered')) {
  598. this.$tableBody.append('<div class="fixed-table-border"></div>')
  599. this.$tableBorder = this.$tableBody.find('.fixed-table-border')
  600. this.$tableLoading.addClass('fixed-table-border')
  601. }
  602. }
  603. }
  604. initTable () {
  605. const columns = []
  606. const data = []
  607. this.$header = this.$el.find('>thead')
  608. if (!this.$header.length) {
  609. this.$header = $(`<thead class="${this.options.theadClasses}"></thead>`).appendTo(this.$el)
  610. } else if (this.options.theadClasses) {
  611. this.$header.addClass(this.options.theadClasses)
  612. }
  613. this.$header.find('tr').each((i, el) => {
  614. const column = []
  615. $(el).find('th').each((i, el) => {
  616. // #2014: getFieldIndex and elsewhere assume this is string, causes issues if not
  617. if (typeof $(el).data('field') !== 'undefined') {
  618. $(el).data('field', `${$(el).data('field')}`)
  619. }
  620. column.push($.extend({}, {
  621. title: $(el).html(),
  622. 'class': $(el).attr('class'),
  623. titleTooltip: $(el).attr('title'),
  624. rowspan: $(el).attr('rowspan') ? +$(el).attr('rowspan') : undefined,
  625. colspan: $(el).attr('colspan') ? +$(el).attr('colspan') : undefined
  626. }, $(el).data()))
  627. })
  628. columns.push(column)
  629. })
  630. if (!Array.isArray(this.options.columns[0])) {
  631. this.options.columns = [this.options.columns]
  632. }
  633. this.options.columns = $.extend(true, [], columns, this.options.columns)
  634. this.columns = []
  635. this.fieldsColumnsIndex = []
  636. Utils.setFieldIndex(this.options.columns)
  637. this.options.columns.forEach((columns, i) => {
  638. columns.forEach((_column, j) => {
  639. const column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, _column)
  640. if (typeof column.fieldIndex !== 'undefined') {
  641. this.columns[column.fieldIndex] = column
  642. this.fieldsColumnsIndex[column.field] = column.fieldIndex
  643. }
  644. this.options.columns[i][j] = column
  645. })
  646. })
  647. // if options.data is setting, do not process tbody data
  648. if (this.options.data.length) {
  649. return
  650. }
  651. const m = []
  652. this.$el.find('>tbody>tr').each((y, el) => {
  653. const row = {}
  654. // save tr's id, class and data-* attributes
  655. row._id = $(el).attr('id')
  656. row._class = $(el).attr('class')
  657. row._data = Utils.getRealDataAttr($(el).data())
  658. $(el).find('>td').each((_x, el) => {
  659. const cspan = +$(el).attr('colspan') || 1
  660. const rspan = +$(el).attr('rowspan') || 1
  661. let x = _x
  662. // skip already occupied cells in current row
  663. for (; m[y] && m[y][x]; x++) {
  664. // ignore
  665. }
  666. // mark matrix elements occupied by current cell with true
  667. for (let tx = x; tx < x + cspan; tx++) {
  668. for (let ty = y; ty < y + rspan; ty++) {
  669. if (!m[ty]) { // fill missing rows
  670. m[ty] = []
  671. }
  672. m[ty][tx] = true
  673. }
  674. }
  675. const field = this.columns[x].field
  676. row[field] = $(el).html()
  677. // save td's id, class and data-* attributes
  678. row[`_${field}_id`] = $(el).attr('id')
  679. row[`_${field}_class`] = $(el).attr('class')
  680. row[`_${field}_rowspan`] = $(el).attr('rowspan')
  681. row[`_${field}_colspan`] = $(el).attr('colspan')
  682. row[`_${field}_title`] = $(el).attr('title')
  683. row[`_${field}_data`] = Utils.getRealDataAttr($(el).data())
  684. })
  685. data.push(row)
  686. })
  687. this.options.data = data
  688. if (data.length) {
  689. this.fromHtml = true
  690. }
  691. }
  692. initHeader () {
  693. const visibleColumns = {}
  694. const html = []
  695. this.header = {
  696. fields: [],
  697. styles: [],
  698. classes: [],
  699. formatters: [],
  700. events: [],
  701. sorters: [],
  702. sortNames: [],
  703. cellStyles: [],
  704. searchables: []
  705. }
  706. this.options.columns.forEach((columns, i) => {
  707. html.push('<tr>')
  708. if (i === 0 && !this.options.cardView && this.options.detailView) {
  709. html.push(`<th class="detail" rowspan="${this.options.columns.length}">
  710. <div class="fht-cell"></div>
  711. </th>
  712. `)
  713. }
  714. columns.forEach((column, j) => {
  715. let text = ''
  716. let halign = '' // header align style
  717. let align = '' // body align style
  718. let style = ''
  719. const class_ = Utils.sprintf(' class="%s"', column['class'])
  720. let unitWidth = 'px'
  721. let width = column.width
  722. if (column.width !== undefined && (!this.options.cardView)) {
  723. if (typeof column.width === 'string') {
  724. if (column.width.includes('%')) {
  725. unitWidth = '%'
  726. }
  727. }
  728. }
  729. if (column.width && typeof column.width === 'string') {
  730. width = column.width.replace('%', '').replace('px', '')
  731. }
  732. halign = Utils.sprintf('text-align: %s; ', column.halign ? column.halign : column.align)
  733. align = Utils.sprintf('text-align: %s; ', column.align)
  734. style = Utils.sprintf('vertical-align: %s; ', column.valign)
  735. style += Utils.sprintf('width: %s; ', (column.checkbox || column.radio) && !width
  736. ? (!column.showSelectTitle ? '36px' : undefined)
  737. : (width ? width + unitWidth : undefined))
  738. if (typeof column.fieldIndex !== 'undefined') {
  739. this.header.fields[column.fieldIndex] = column.field
  740. this.header.styles[column.fieldIndex] = align + style
  741. this.header.classes[column.fieldIndex] = class_
  742. this.header.formatters[column.fieldIndex] = column.formatter
  743. this.header.events[column.fieldIndex] = column.events
  744. this.header.sorters[column.fieldIndex] = column.sorter
  745. this.header.sortNames[column.fieldIndex] = column.sortName
  746. this.header.cellStyles[column.fieldIndex] = column.cellStyle
  747. this.header.searchables[column.fieldIndex] = column.searchable
  748. if (!column.visible) {
  749. return
  750. }
  751. if (this.options.cardView && (!column.cardVisible)) {
  752. return
  753. }
  754. visibleColumns[column.field] = column
  755. }
  756. html.push(`<th${Utils.sprintf(' title="%s"', column.titleTooltip)}`,
  757. column.checkbox || column.radio
  758. ? Utils.sprintf(' class="bs-checkbox %s"', column['class'] || '')
  759. : class_,
  760. Utils.sprintf(' style="%s"', halign + style),
  761. Utils.sprintf(' rowspan="%s"', column.rowspan),
  762. Utils.sprintf(' colspan="%s"', column.colspan),
  763. Utils.sprintf(' data-field="%s"', column.field),
  764. // If `column` is not the first element of `this.options.columns[0]`, then className 'data-not-first-th' should be added.
  765. j === 0 && i > 0 ? ' data-not-first-th' : '',
  766. '>')
  767. html.push(Utils.sprintf('<div class="th-inner %s">', this.options.sortable && column.sortable
  768. ? 'sortable both' : ''))
  769. text = this.options.escape ? Utils.escapeHTML(column.title) : column.title
  770. const title = text
  771. if (column.checkbox) {
  772. text = ''
  773. if (!this.options.singleSelect && this.options.checkboxHeader) {
  774. text = '<input name="btSelectAll" type="checkbox" />'
  775. }
  776. this.header.stateField = column.field
  777. }
  778. if (column.radio) {
  779. text = ''
  780. this.header.stateField = column.field
  781. this.options.singleSelect = true
  782. }
  783. if (!text && column.showSelectTitle) {
  784. text += title
  785. }
  786. html.push(text)
  787. html.push('</div>')
  788. html.push('<div class="fht-cell"></div>')
  789. html.push('</div>')
  790. html.push('</th>')
  791. })
  792. html.push('</tr>')
  793. })
  794. this.$header.html(html.join(''))
  795. this.$header.find('th[data-field]').each((i, el) => {
  796. $(el).data(visibleColumns[$(el).data('field')])
  797. })
  798. this.$container.off('click', '.th-inner').on('click', '.th-inner', e => {
  799. const $this = $(e.currentTarget)
  800. if (this.options.detailView && !$this.parent().hasClass('bs-checkbox')) {
  801. if ($this.closest('.bootstrap-table')[0] !== this.$container[0]) {
  802. return false
  803. }
  804. }
  805. if (this.options.sortable && $this.parent().data().sortable) {
  806. this.onSort(e)
  807. }
  808. })
  809. this.$header.children().children().off('keypress').on('keypress', e => {
  810. if (this.options.sortable && $(e.currentTarget).data().sortable) {
  811. const code = e.keyCode || e.which
  812. if (code === 13) { // Enter keycode
  813. this.onSort(e)
  814. }
  815. }
  816. })
  817. $(window).off('resize.bootstrap-table')
  818. if (!this.options.showHeader || this.options.cardView) {
  819. this.$header.hide()
  820. this.$tableHeader.hide()
  821. this.$tableLoading.css('top', 0)
  822. } else {
  823. this.$header.show()
  824. this.$tableHeader.show()
  825. this.$tableLoading.css('top', this.$header.outerHeight() + 1)
  826. // Assign the correct sortable arrow
  827. this.getCaret()
  828. $(window).on('resize.bootstrap-table', $.proxy(this.resetWidth, this))
  829. }
  830. this.$selectAll = this.$header.find('[name="btSelectAll"]')
  831. this.$selectAll.off('click').on('click', ({currentTarget}) => {
  832. const checked = $(currentTarget).prop('checked')
  833. this[checked ? 'checkAll' : 'uncheckAll']()
  834. this.updateSelected()
  835. })
  836. }
  837. initFooter () {
  838. if (!this.options.showFooter || this.options.cardView) {
  839. this.$tableFooter.hide()
  840. } else {
  841. this.$tableFooter.show()
  842. }
  843. }
  844. initData (data, type) {
  845. if (type === 'append') {
  846. this.options.data = this.options.data.concat(data)
  847. } else if (type === 'prepend') {
  848. this.options.data = [].concat(data).concat(this.options.data)
  849. } else {
  850. this.options.data = data || this.options.data
  851. }
  852. this.data = this.options.data
  853. if (this.options.sidePagination === 'server') {
  854. return
  855. }
  856. this.initSort()
  857. }
  858. initSort () {
  859. let name = this.options.sortName
  860. const order = this.options.sortOrder === 'desc' ? -1 : 1
  861. const index = this.header.fields.indexOf(this.options.sortName)
  862. let timeoutId = 0
  863. if (index !== -1) {
  864. if (this.options.sortStable) {
  865. this.data.forEach((row, i) => {
  866. if (!row.hasOwnProperty('_position')) {
  867. row._position = i
  868. }
  869. })
  870. }
  871. if (this.options.customSort) {
  872. Utils.calculateObjectValue(this.options, this.options.customSort, [
  873. this.options.sortName,
  874. this.options.sortOrder,
  875. this.data
  876. ])
  877. } else {
  878. this.data.sort((a, b) => {
  879. if (this.header.sortNames[index]) {
  880. name = this.header.sortNames[index]
  881. }
  882. let aa = Utils.getItemField(a, name, this.options.escape)
  883. let bb = Utils.getItemField(b, name, this.options.escape)
  884. const value = Utils.calculateObjectValue(this.header, this.header.sorters[index], [aa, bb, a, b])
  885. if (value !== undefined) {
  886. if (this.options.sortStable && value === 0) {
  887. return order * (a._position - b._position)
  888. }
  889. return order * value
  890. }
  891. // Fix #161: undefined or null string sort bug.
  892. if (aa === undefined || aa === null) {
  893. aa = ''
  894. }
  895. if (bb === undefined || bb === null) {
  896. bb = ''
  897. }
  898. if (this.options.sortStable && aa === bb) {
  899. aa = a._position
  900. bb = b._position
  901. }
  902. // IF both values are numeric, do a numeric comparison
  903. if ($.isNumeric(aa) && $.isNumeric(bb)) {
  904. // Convert numerical values form string to float.
  905. aa = parseFloat(aa)
  906. bb = parseFloat(bb)
  907. if (aa < bb) {
  908. return order * -1
  909. }
  910. if (aa > bb) {
  911. return order
  912. }
  913. return 0
  914. }
  915. if (aa === bb) {
  916. return 0
  917. }
  918. // If value is not a string, convert to string
  919. if (typeof aa !== 'string') {
  920. aa = aa.toString()
  921. }
  922. if (aa.localeCompare(bb) === -1) {
  923. return order * -1
  924. }
  925. return order
  926. })
  927. }
  928. if (this.options.sortClass !== undefined) {
  929. clearTimeout(timeoutId)
  930. timeoutId = setTimeout(() => {
  931. this.$el.removeClass(this.options.sortClass)
  932. const index = this.$header.find(`[data-field="${this.options.sortName}"]`).index()
  933. this.$el.find(`tr td:nth-child(${index + 1})`).addClass(this.options.sortClass)
  934. }, 250)
  935. }
  936. }
  937. }
  938. onSort ({type, currentTarget}) {
  939. const $this = type === 'keypress' ? $(currentTarget) : $(currentTarget).parent()
  940. const $this_ = this.$header.find('th').eq($this.index())
  941. this.$header.add(this.$header_).find('span.order').remove()
  942. if (this.options.sortName === $this.data('field')) {
  943. this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc'
  944. } else {
  945. this.options.sortName = $this.data('field')
  946. if (this.options.rememberOrder) {
  947. this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc'
  948. } else {
  949. this.options.sortOrder = this.columns[this.fieldsColumnsIndex[$this.data('field')]].order
  950. }
  951. }
  952. this.trigger('sort', this.options.sortName, this.options.sortOrder)
  953. $this.add($this_).data('order', this.options.sortOrder)
  954. // Assign the correct sortable arrow
  955. this.getCaret()
  956. if (this.options.sidePagination === 'server') {
  957. this.initServer(this.options.silentSort)
  958. return
  959. }
  960. this.initSort()
  961. this.initBody()
  962. }
  963. initToolbar () {
  964. let html = []
  965. let timeoutId = 0
  966. let $keepOpen
  967. let $search
  968. let switchableCount = 0
  969. if (this.$toolbar.find('.bs-bars').children().length) {
  970. $('body').append($(this.options.toolbar))
  971. }
  972. this.$toolbar.html('')
  973. if (typeof this.options.toolbar === 'string' || typeof this.options.toolbar === 'object') {
  974. $(Utils.sprintf('<div class="bs-bars %s-%s"></div>', bootstrap.classes.pull, this.options.toolbarAlign))
  975. .appendTo(this.$toolbar)
  976. .append($(this.options.toolbar))
  977. }
  978. // showColumns, showToggle, showRefresh
  979. html = [Utils.sprintf('<div class="columns columns-%s btn-group %s-%s">',
  980. this.options.buttonsAlign, bootstrap.classes.pull, this.options.buttonsAlign)]
  981. if (typeof this.options.icons === 'string') {
  982. this.options.icons = Utils.calculateObjectValue(null, this.options.icons)
  983. }
  984. if (this.options.showPaginationSwitch) {
  985. html.push(Utils.sprintf(`<button class="btn${Utils.sprintf(' btn-%s', this.options.buttonsClass)}${Utils.sprintf(' btn-%s', this.options.iconSize)}" type="button" name="paginationSwitch" aria-label="pagination Switch" title="%s">`,
  986. this.options.formatPaginationSwitch()),
  987. Utils.sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.paginationSwitchDown),
  988. '</button>')
  989. }
  990. if (this.options.showFullscreen) {
  991. this.$toolbar.find('button[name="fullscreen"]')
  992. .off('click').on('click', $.proxy(this.toggleFullscreen, this))
  993. }
  994. if (this.options.showRefresh) {
  995. 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">`,
  996. this.options.formatRefresh()),
  997. Utils.sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.refresh),
  998. '</button>')
  999. }
  1000. if (this.options.showToggle) {
  1001. 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">`,
  1002. this.options.formatToggle()),
  1003. Utils.sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.toggleOff),
  1004. '</button>')
  1005. }
  1006. if (this.options.showFullscreen) {
  1007. 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">`,
  1008. this.options.formatFullscreen()),
  1009. Utils.sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.fullscreen),
  1010. '</button>')
  1011. }
  1012. if (this.options.showColumns) {
  1013. html.push(Utils.sprintf('<div class="keep-open btn-group" title="%s">',
  1014. this.options.formatColumns()),
  1015. `<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">`,
  1016. Utils.sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.columns),
  1017. ' <span class="caret"></span>',
  1018. '</button>',
  1019. bootstrap.html.toobarDropdow[0])
  1020. this.columns.forEach((column, i) => {
  1021. if (column.radio || column.checkbox) {
  1022. return
  1023. }
  1024. if (this.options.cardView && !column.cardVisible) {
  1025. return
  1026. }
  1027. const checked = column.visible ? ' checked="checked"' : ''
  1028. if (column.switchable) {
  1029. html.push(Utils.sprintf(bootstrap.html.toobarDropdowItem,
  1030. Utils.sprintf('<input type="checkbox" data-field="%s" value="%s"%s> %s',
  1031. column.field, i, checked, column.title)))
  1032. switchableCount++
  1033. }
  1034. })
  1035. html.push(bootstrap.html.toobarDropdow[1], '</div>')
  1036. }
  1037. html.push('</div>')
  1038. // Fix #188: this.showToolbar is for extensions
  1039. if (this.showToolbar || html.length > 2) {
  1040. this.$toolbar.append(html.join(''))
  1041. }
  1042. if (this.options.showPaginationSwitch) {
  1043. this.$toolbar.find('button[name="paginationSwitch"]')
  1044. .off('click').on('click', $.proxy(this.togglePagination, this))
  1045. }
  1046. if (this.options.showRefresh) {
  1047. this.$toolbar.find('button[name="refresh"]')
  1048. .off('click').on('click', $.proxy(this.refresh, this))
  1049. }
  1050. if (this.options.showToggle) {
  1051. this.$toolbar.find('button[name="toggle"]')
  1052. .off('click').on('click', () => {
  1053. this.toggleView()
  1054. })
  1055. }
  1056. if (this.options.showColumns) {
  1057. $keepOpen = this.$toolbar.find('.keep-open')
  1058. if (switchableCount <= this.options.minimumCountColumns) {
  1059. $keepOpen.find('input').prop('disabled', true)
  1060. }
  1061. $keepOpen.find('li').off('click').on('click', e => {
  1062. e.stopImmediatePropagation()
  1063. })
  1064. $keepOpen.find('input').off('click').on('click', ({currentTarget}) => {
  1065. const $this = $(currentTarget)
  1066. this.toggleColumn($this.val(), $this.prop('checked'), false)
  1067. this.trigger('column-switch', $this.data('field'), $this.prop('checked'))
  1068. })
  1069. }
  1070. if (this.options.search) {
  1071. html = []
  1072. html.push(
  1073. Utils.sprintf('<div class="%s-%s search">', bootstrap.classes.pull, this.options.searchAlign),
  1074. Utils.sprintf(`<input class="form-control${Utils.sprintf(' input-%s', this.options.iconSize)}" type="text" placeholder="%s">`,
  1075. this.options.formatSearch()),
  1076. '</div>')
  1077. this.$toolbar.append(html.join(''))
  1078. $search = this.$toolbar.find('.search input')
  1079. $search.off('keyup drop blur').on('keyup drop blur', event => {
  1080. if (this.options.searchOnEnterKey && event.keyCode !== 13) {
  1081. return
  1082. }
  1083. if ([37, 38, 39, 40].includes(event.keyCode)) {
  1084. return
  1085. }
  1086. clearTimeout(timeoutId) // doesn't matter if it's 0
  1087. timeoutId = setTimeout(() => {
  1088. this.onSearch(event)
  1089. }, this.options.searchTimeOut)
  1090. })
  1091. if (Utils.isIEBrowser()) {
  1092. $search.off('mouseup').on('mouseup', event => {
  1093. clearTimeout(timeoutId) // doesn't matter if it's 0
  1094. timeoutId = setTimeout(() => {
  1095. this.onSearch(event)
  1096. }, this.options.searchTimeOut)
  1097. })
  1098. }
  1099. }
  1100. }
  1101. onSearch ({currentTarget, firedByInitSearchText}) {
  1102. const text = $.trim($(currentTarget).val())
  1103. // trim search input
  1104. if (this.options.trimOnSearch && $(currentTarget).val() !== text) {
  1105. $(currentTarget).val(text)
  1106. }
  1107. if (text === this.searchText) {
  1108. return
  1109. }
  1110. this.searchText = text
  1111. this.options.searchText = text
  1112. if (!firedByInitSearchText) {
  1113. this.options.pageNumber = 1
  1114. }
  1115. this.initSearch()
  1116. if (firedByInitSearchText) {
  1117. if (this.options.sidePagination === 'client') {
  1118. this.updatePagination()
  1119. }
  1120. } else {
  1121. this.updatePagination()
  1122. }
  1123. this.trigger('search', text)
  1124. }
  1125. initSearch () {
  1126. if (this.options.sidePagination !== 'server') {
  1127. if (this.options.customSearch) {
  1128. Utils.calculateObjectValue(this.options, this.options.customSearch, [this.searchText])
  1129. return
  1130. }
  1131. const s = this.searchText && (this.options.escape
  1132. ? Utils.escapeHTML(this.searchText) : this.searchText).toLowerCase()
  1133. const f = $.isEmptyObject(this.filterColumns) ? null : this.filterColumns
  1134. // Check filter
  1135. this.data = f ? this.options.data.filter((item, i) => {
  1136. for (const key in f) {
  1137. if (
  1138. (Array.isArray(f[key]) &&
  1139. !f[key].includes(item[key])) ||
  1140. (!Array.isArray(f[key]) &&
  1141. item[key] !== f[key])
  1142. ) {
  1143. return false
  1144. }
  1145. }
  1146. return true
  1147. }) : this.options.data
  1148. this.data = s ? this.data.filter((item, i) => {
  1149. for (let j = 0; j < this.header.fields.length; j++) {
  1150. if (!this.header.searchables[j]) {
  1151. continue
  1152. }
  1153. const key = $.isNumeric(this.header.fields[j]) ? parseInt(this.header.fields[j], 10) : this.header.fields[j]
  1154. const column = this.columns[this.fieldsColumnsIndex[key]]
  1155. let value
  1156. if (typeof key === 'string') {
  1157. value = item
  1158. const props = key.split('.')
  1159. for (let i = 0; i < props.length; i++) {
  1160. if (value[props[i]] !== null) {
  1161. value = value[props[i]]
  1162. }
  1163. }
  1164. } else {
  1165. value = item[key]
  1166. }
  1167. // Fix #142: respect searchForamtter boolean
  1168. if (column && column.searchFormatter) {
  1169. value = Utils.calculateObjectValue(column,
  1170. this.header.formatters[j], [value, item, i], value)
  1171. }
  1172. if (typeof value === 'string' || typeof value === 'number') {
  1173. if (this.options.strictSearch) {
  1174. if ((`${value}`).toLowerCase() === s) {
  1175. return true
  1176. }
  1177. } else {
  1178. if ((`${value}`).toLowerCase().includes(s)) {
  1179. return true
  1180. }
  1181. }
  1182. }
  1183. }
  1184. return false
  1185. }) : this.data
  1186. }
  1187. }
  1188. initPagination () {
  1189. if (!this.options.pagination) {
  1190. this.$pagination.hide()
  1191. return
  1192. }
  1193. this.$pagination.show()
  1194. const html = []
  1195. let $allSelected = false
  1196. let i
  1197. let from
  1198. let to
  1199. let $pageList
  1200. let $pre
  1201. let $next
  1202. let $number
  1203. const data = this.getData()
  1204. let pageList = this.options.pageList
  1205. if (this.options.sidePagination !== 'server') {
  1206. this.options.totalRows = data.length
  1207. }
  1208. this.totalPages = 0
  1209. if (this.options.totalRows) {
  1210. if (this.options.pageSize === this.options.formatAllRows()) {
  1211. this.options.pageSize = this.options.totalRows
  1212. $allSelected = true
  1213. } else if (this.options.pageSize === this.options.totalRows) {
  1214. // Fix #667 Table with pagination,
  1215. // multiple pages and a search this matches to one page throws exception
  1216. const pageLst = typeof this.options.pageList === 'string'
  1217. ? this.options.pageList.replace('[', '').replace(']', '')
  1218. .replace(/ /g, '').toLowerCase().split(',') : this.options.pageList
  1219. if (pageLst.includes(this.options.formatAllRows().toLowerCase())) {
  1220. $allSelected = true
  1221. }
  1222. }
  1223. this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1
  1224. this.options.totalPages = this.totalPages
  1225. }
  1226. if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) {
  1227. this.options.pageNumber = this.totalPages
  1228. }
  1229. this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1
  1230. this.pageTo = this.options.pageNumber * this.options.pageSize
  1231. if (this.pageTo > this.options.totalRows) {
  1232. this.pageTo = this.options.totalRows
  1233. }
  1234. html.push(
  1235. Utils.sprintf('<div class="%s-%s pagination-detail">', bootstrap.classes.pull, this.options.paginationDetailHAlign),
  1236. '<span class="pagination-info">',
  1237. this.options.onlyInfoPagination ? this.options.formatDetailPagination(this.options.totalRows)
  1238. : this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows),
  1239. '</span>')
  1240. if (!this.options.onlyInfoPagination) {
  1241. html.push('<span class="page-list">')
  1242. const pageNumber = [
  1243. Utils.sprintf('<span class="btn-group %s">',
  1244. this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both'
  1245. ? 'dropdown' : 'dropup'),
  1246. `<button type="button" class="btn${Utils.sprintf(' btn-%s', this.options.buttonsClass)}${Utils.sprintf(' btn-%s', this.options.iconSize)} dropdown-toggle" data-toggle="dropdown">`,
  1247. '<span class="page-size">',
  1248. $allSelected ? this.options.formatAllRows() : this.options.pageSize,
  1249. '</span>',
  1250. ' <span class="caret"></span>',
  1251. '</button>',
  1252. bootstrap.html.pageDropdown[0]
  1253. ]
  1254. if (typeof this.options.pageList === 'string') {
  1255. const list = this.options.pageList.replace('[', '').replace(']', '')
  1256. .replace(/ /g, '').split(',')
  1257. pageList = []
  1258. for (const value of list) {
  1259. pageList.push(
  1260. (value.toUpperCase() === this.options.formatAllRows().toUpperCase() ||
  1261. value.toUpperCase() === 'UNLIMITED')
  1262. ? this.options.formatAllRows() : +value)
  1263. }
  1264. }
  1265. pageList.forEach((page, i) => {
  1266. if (!this.options.smartDisplay || i === 0 || pageList[i - 1] < this.options.totalRows) {
  1267. let active
  1268. if ($allSelected) {
  1269. active = page === this.options.formatAllRows() ? 'active' : ''
  1270. } else {
  1271. active = page === this.options.pageSize ? 'active' : ''
  1272. }
  1273. pageNumber.push(Utils.sprintf(bootstrap.html.pageDropdownItem, active, page))
  1274. }
  1275. })
  1276. pageNumber.push(`${bootstrap.html.pageDropdown[1]}</span>`)
  1277. html.push(this.options.formatRecordsPerPage(pageNumber.join('')))
  1278. html.push('</span>')
  1279. html.push('</div>',
  1280. Utils.sprintf('<div class="%s-%s pagination">', bootstrap.classes.pull, this.options.paginationHAlign),
  1281. `<ul class="pagination${Utils.sprintf(' pagination-%s', this.options.iconSize)}">`,
  1282. Utils.sprintf('<li class="page-item page-pre"><a class="page-link" href="#">%s</a></li>',
  1283. this.options.paginationPreText))
  1284. if (this.totalPages < this.options.paginationSuccessivelySize) {
  1285. from = 1
  1286. to = this.totalPages
  1287. } else {
  1288. from = this.options.pageNumber - this.options.paginationPagesBySide
  1289. to = from + (this.options.paginationPagesBySide * 2)
  1290. }
  1291. if (this.options.pageNumber < (this.options.paginationSuccessivelySize - 1)) {
  1292. to = this.options.paginationSuccessivelySize
  1293. }
  1294. if (to > this.totalPages) {
  1295. to = this.totalPages
  1296. }
  1297. if (this.options.paginationSuccessivelySize > this.totalPages - from) {
  1298. from = from - (this.options.paginationSuccessivelySize - (this.totalPages - from)) + 1
  1299. }
  1300. if (from < 1) {
  1301. from = 1
  1302. }
  1303. if (to > this.totalPages) {
  1304. to = this.totalPages
  1305. }
  1306. const middleSize = Math.round(this.options.paginationPagesBySide / 2)
  1307. const pageItem = (i, classes = '') => `
  1308. <li class="page-item${classes}${i === this.options.pageNumber ? ' active' : ''}">
  1309. <a class="page-link" href="#">${i}</a>
  1310. </li>
  1311. `
  1312. if (from > 1) {
  1313. let max = this.options.paginationPagesBySide
  1314. if (max >= from) max = from - 1
  1315. for (i = 1; i <= max; i++) {
  1316. html.push(pageItem(i))
  1317. }
  1318. if ((from - 1) === max + 1) {
  1319. i = from - 1
  1320. html.push(pageItem(i))
  1321. } else {
  1322. if ((from - 1) > max) {
  1323. if (
  1324. (from - this.options.paginationPagesBySide * 2) > this.options.paginationPagesBySide &&
  1325. this.options.paginationUseIntermediate
  1326. ) {
  1327. i = Math.round(((from - middleSize) / 2) + middleSize)
  1328. html.push(pageItem(i, ' page-intermediate'))
  1329. } else {
  1330. html.push(`
  1331. <li class="page-item page-first-separator disabled">
  1332. <a class="page-link" href="#">...</a>
  1333. </li>`
  1334. )
  1335. }
  1336. }
  1337. }
  1338. }
  1339. for (i = from; i <= to; i++) {
  1340. html.push(pageItem(i))
  1341. }
  1342. if (this.totalPages > to) {
  1343. let min = this.totalPages - (this.options.paginationPagesBySide - 1)
  1344. if (to >= min) min = to + 1
  1345. if ((to + 1) === min - 1) {
  1346. i = to + 1
  1347. html.push(pageItem(i))
  1348. } else {
  1349. if (min > (to + 1)) {
  1350. if (
  1351. (this.totalPages - to) > this.options.paginationPagesBySide * 2 &&
  1352. this.options.paginationUseIntermediate
  1353. ) {
  1354. i = Math.round(((this.totalPages - middleSize - to) / 2) + to)
  1355. html.push(pageItem(i, ' page-intermediate'))
  1356. } else {
  1357. html.push(`
  1358. <li class="page-item page-last-separator disabled">
  1359. <a class="page-link" href="#">...</a>
  1360. </li>`
  1361. )
  1362. }
  1363. }
  1364. }
  1365. for (i = min; i <= this.totalPages; i++) {
  1366. html.push(pageItem(i))
  1367. }
  1368. }
  1369. html.push(`
  1370. <li class="page-item page-next">
  1371. <a class="page-link" href="#">${this.options.paginationNextText}</a>
  1372. </li>
  1373. </ul>
  1374. </div>
  1375. `)
  1376. }
  1377. this.$pagination.html(html.join(''))
  1378. if (!this.options.onlyInfoPagination) {
  1379. $pageList = this.$pagination.find('.page-list a')
  1380. $pre = this.$pagination.find('.page-pre')
  1381. $next = this.$pagination.find('.page-next')
  1382. $number = this.$pagination.find('.page-item').not('.page-next, .page-pre')
  1383. if (this.options.smartDisplay) {
  1384. if (this.totalPages <= 1) {
  1385. this.$pagination.find('div.pagination').hide()
  1386. }
  1387. if (pageList.length < 2 || this.options.totalRows <= pageList[0]) {
  1388. this.$pagination.find('span.page-list').hide()
  1389. }
  1390. // when data is empty, hide the pagination
  1391. this.$pagination[this.getData().length ? 'show' : 'hide']()
  1392. }
  1393. if (!this.options.paginationLoop) {
  1394. if (this.options.pageNumber === 1) {
  1395. $pre.addClass('disabled')
  1396. }
  1397. if (this.options.pageNumber === this.totalPages) {
  1398. $next.addClass('disabled')
  1399. }
  1400. }
  1401. if ($allSelected) {
  1402. this.options.pageSize = this.options.formatAllRows()
  1403. }
  1404. // removed the events for last and first, onPageNumber executeds the same logic
  1405. $pageList.off('click').on('click', $.proxy(this.onPageListChange, this))
  1406. $pre.off('click').on('click', $.proxy(this.onPagePre, this))
  1407. $next.off('click').on('click', $.proxy(this.onPageNext, this))
  1408. $number.off('click').on('click', $.proxy(this.onPageNumber, this))
  1409. }
  1410. }
  1411. updatePagination (event) {
  1412. // Fix #171: IE disabled button can be clicked bug.
  1413. if (event && $(event.currentTarget).hasClass('disabled')) {
  1414. return
  1415. }
  1416. if (!this.options.maintainSelected) {
  1417. this.resetRows()
  1418. }
  1419. this.initPagination()
  1420. if (this.options.sidePagination === 'server') {
  1421. this.initServer()
  1422. } else {
  1423. this.initBody()
  1424. }
  1425. this.trigger('page-change', this.options.pageNumber, this.options.pageSize)
  1426. }
  1427. onPageListChange (event) {
  1428. event.preventDefault()
  1429. const $this = $(event.currentTarget)
  1430. $this.parent().addClass('active').siblings().removeClass('active')
  1431. this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase()
  1432. ? this.options.formatAllRows() : +$this.text()
  1433. this.$toolbar.find('.page-size').text(this.options.pageSize)
  1434. this.updatePagination(event)
  1435. return false
  1436. }
  1437. onPagePre (event) {
  1438. event.preventDefault()
  1439. if ((this.options.pageNumber - 1) === 0) {
  1440. this.options.pageNumber = this.options.totalPages
  1441. } else {
  1442. this.options.pageNumber--
  1443. }
  1444. this.updatePagination(event)
  1445. return false
  1446. }
  1447. onPageNext (event) {
  1448. event.preventDefault()
  1449. if ((this.options.pageNumber + 1) > this.options.totalPages) {
  1450. this.options.pageNumber = 1
  1451. } else {
  1452. this.options.pageNumber++
  1453. }
  1454. this.updatePagination(event)
  1455. return false
  1456. }
  1457. onPageNumber (event) {
  1458. event.preventDefault()
  1459. if (this.options.pageNumber === +$(event.currentTarget).text()) {
  1460. return
  1461. }
  1462. this.options.pageNumber = +$(event.currentTarget).text()
  1463. this.updatePagination(event)
  1464. return false
  1465. }
  1466. initRow (item, i, data, parentDom) {
  1467. const html = []
  1468. let style = {}
  1469. const csses = []
  1470. let data_ = ''
  1471. let attributes = {}
  1472. const htmlAttributes = []
  1473. if (Utils.findIndex(this.hiddenRows, item) > -1) {
  1474. return
  1475. }
  1476. style = Utils.calculateObjectValue(this.options, this.options.rowStyle, [item, i], style)
  1477. if (style && style.css) {
  1478. for (const [key, value] of Object.entries(style.css)) {
  1479. csses.push(`${key}: ${value}`)
  1480. }
  1481. }
  1482. attributes = Utils.calculateObjectValue(this.options,
  1483. this.options.rowAttributes, [item, i], attributes)
  1484. if (attributes) {
  1485. for (const [key, value] of Object.entries(attributes)) {
  1486. htmlAttributes.push(`${key}="${Utils.escapeHTML(value)}"`)
  1487. }
  1488. }
  1489. if (item._data && !$.isEmptyObject(item._data)) {
  1490. for (const [k, v] of Object.entries(item._data)) {
  1491. // ignore data-index
  1492. if (k === 'index') {
  1493. return
  1494. }
  1495. data_ += ` data-${k}="${v}"`
  1496. }
  1497. }
  1498. html.push('<tr',
  1499. Utils.sprintf(' %s', htmlAttributes.length ? htmlAttributes.join(' ') : undefined),
  1500. Utils.sprintf(' id="%s"', Array.isArray(item) ? undefined : item._id),
  1501. Utils.sprintf(' class="%s"', style.classes || (Array.isArray(item) ? undefined : item._class)),
  1502. ` data-index="${i}"`,
  1503. Utils.sprintf(' data-uniqueid="%s"', item[this.options.uniqueId]),
  1504. Utils.sprintf('%s', data_),
  1505. '>'
  1506. )
  1507. if (this.options.cardView) {
  1508. html.push(`<td colspan="${this.header.fields.length}"><div class="card-views">`)
  1509. }
  1510. if (!this.options.cardView && this.options.detailView) {
  1511. html.push('<td>')
  1512. if (Utils.calculateObjectValue(null, this.options.detailFilter, [i, item])) {
  1513. html.push(`
  1514. <a class="detail-icon" href="#">
  1515. <i class="${this.options.iconsPrefix} ${this.options.icons.detailOpen}"></i>
  1516. </a>
  1517. `)
  1518. }
  1519. html.push('</td>')
  1520. }
  1521. this.header.fields.forEach((field, j) => {
  1522. let text = ''
  1523. let value_ = Utils.getItemField(item, field, this.options.escape)
  1524. let value = ''
  1525. let type = ''
  1526. let cellStyle = {}
  1527. let id_ = ''
  1528. let class_ = this.header.classes[j]
  1529. let style_ = ''
  1530. let data_ = ''
  1531. let rowspan_ = ''
  1532. let colspan_ = ''
  1533. let title_ = ''
  1534. const column = this.columns[j]
  1535. if (this.fromHtml && typeof value_ === 'undefined') {
  1536. if ((!column.checkbox) && (!column.radio)) {
  1537. return
  1538. }
  1539. }
  1540. if (!column.visible) {
  1541. return
  1542. }
  1543. if (this.options.cardView && (!column.cardVisible)) {
  1544. return
  1545. }
  1546. if (column.escape) {
  1547. value_ = Utils.escapeHTML(value_)
  1548. }
  1549. if (csses.concat([this.header.styles[j]]).length) {
  1550. style_ = ` style="${csses.concat([this.header.styles[j]]).join('; ')}"`
  1551. }
  1552. // handle td's id and class
  1553. if (item[`_${field}_id`]) {
  1554. id_ = Utils.sprintf(' id="%s"', item[`_${field}_id`])
  1555. }
  1556. if (item[`_${field}_class`]) {
  1557. class_ = Utils.sprintf(' class="%s"', item[`_${field}_class`])
  1558. }
  1559. if (item[`_${field}_rowspan`]) {
  1560. rowspan_ = Utils.sprintf(' rowspan="%s"', item[`_${field}_rowspan`])
  1561. }
  1562. if (item[`_${field}_colspan`]) {
  1563. colspan_ = Utils.sprintf(' colspan="%s"', item[`_${field}_colspan`])
  1564. }
  1565. if (item[`_${field}_title`]) {
  1566. title_ = Utils.sprintf(' title="%s"', item[`_${field}_title`])
  1567. }
  1568. cellStyle = Utils.calculateObjectValue(this.header,
  1569. this.header.cellStyles[j], [value_, item, i, field], cellStyle)
  1570. if (cellStyle.classes) {
  1571. class_ = ` class="${cellStyle.classes}"`
  1572. }
  1573. if (cellStyle.css) {
  1574. const csses_ = []
  1575. for (const [key, value] of Object.entries(cellStyle.css)) {
  1576. csses_.push(`${key}: ${value}`)
  1577. }
  1578. style_ = ` style="${csses_.concat(this.header.styles[j]).join('; ')}"`
  1579. }
  1580. value = Utils.calculateObjectValue(column,
  1581. this.header.formatters[j], [value_, item, i, field], value_)
  1582. if (item[`_${field}_data`] && !$.isEmptyObject(item[`_${field}_data`])) {
  1583. for (const [k, v] of Object.entries(item[`_${field}_data`])) {
  1584. // ignore data-index
  1585. if (k === 'index') {
  1586. return
  1587. }
  1588. data_ += ` data-${k}="${v}"`
  1589. }
  1590. }
  1591. if (column.checkbox || column.radio) {
  1592. type = column.checkbox ? 'checkbox' : type
  1593. type = column.radio ? 'radio' : type
  1594. const c = column['class'] || ''
  1595. const isChecked = value === true || (value_ || (value && value.checked))
  1596. const isDisabled = !column.checkboxEnabled || (value && value.disabled)
  1597. text = [
  1598. this.options.cardView
  1599. ? `<div class="card-view ${c}">`
  1600. : `<td class="bs-checkbox ${c}">`,
  1601. `<input
  1602. data-index="${i}"
  1603. name="${this.options.selectItemName}"
  1604. type="${type}"
  1605. ${Utils.sprintf('value="%s"', item[this.options.idField])}
  1606. ${Utils.sprintf('checked="%s"', isChecked ? 'checked' : undefined)}
  1607. ${Utils.sprintf('disabled="%s"', isDisabled ? 'disabled' : undefined)} />`,
  1608. this.header.formatters[j] && typeof value === 'string' ? value : '',
  1609. this.options.cardView ? '</div>' : '</td>'
  1610. ].join('')
  1611. item[this.header.stateField] = value === true || (!!value_ || (value && value.checked))
  1612. } else {
  1613. value = typeof value === 'undefined' || value === null
  1614. ? this.options.undefinedText : value
  1615. if (this.options.cardView) {
  1616. const cardTitle = this.options.showHeader
  1617. ? `<span class="title"${style}>${Utils.getFieldTitle(this.columns, field)}</span>` : ''
  1618. text = `<div class="card-view">${cardTitle}<span class="value">${value}</span></div>`
  1619. if (this.options.smartDisplay && value === '') {
  1620. text = '<div class="card-view"></div>'
  1621. }
  1622. } else {
  1623. text = `<td${id_}${class_}${style_}${data_}${rowspan_}${colspan_}${title_}>${value}</td>`
  1624. }
  1625. }
  1626. html.push(text)
  1627. })
  1628. if (this.options.cardView) {
  1629. html.push('</div></td>')
  1630. }
  1631. html.push('</tr>')
  1632. return html.join('')
  1633. }
  1634. initBody (fixedScroll) {
  1635. const data = this.getData()
  1636. this.trigger('pre-body', data)
  1637. this.$body = this.$el.find('>tbody')
  1638. if (!this.$body.length) {
  1639. this.$body = $('<tbody></tbody>').appendTo(this.$el)
  1640. }
  1641. // Fix #389 Bootstrap-table-flatJSON is not working
  1642. if (!this.options.pagination || this.options.sidePagination === 'server') {
  1643. this.pageFrom = 1
  1644. this.pageTo = data.length
  1645. }
  1646. const trFragments = $(document.createDocumentFragment())
  1647. let hasTr = false
  1648. for (let i = this.pageFrom - 1; i < this.pageTo; i++) {
  1649. const item = data[i]
  1650. const tr = this.initRow(item, i, data, trFragments)
  1651. hasTr = hasTr || !!tr
  1652. if (tr && typeof tr === 'string') {
  1653. trFragments.append(tr)
  1654. }
  1655. }
  1656. // show no records
  1657. if (!hasTr) {
  1658. this.$body.html(`<tr class="no-records-found">${Utils.sprintf('<td colspan="%s">%s</td>',
  1659. this.$header.find('th').length,
  1660. this.options.formatNoMatches())}</tr>`)
  1661. } else {
  1662. this.$body.html(trFragments)
  1663. }
  1664. if (!fixedScroll) {
  1665. this.scrollTo(0)
  1666. }
  1667. // click to select by column
  1668. this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', ({currentTarget, type, target}) => {
  1669. const $td = $(currentTarget)
  1670. const $tr = $td.parent()
  1671. const item = this.data[$tr.data('index')]
  1672. const index = $td[0].cellIndex
  1673. const fields = this.getVisibleFields()
  1674. const field = fields[this.options.detailView && !this.options.cardView ? index - 1 : index]
  1675. const column = this.columns[this.fieldsColumnsIndex[field]]
  1676. const value = Utils.getItemField(item, field, this.options.escape)
  1677. if ($td.find('.detail-icon').length) {
  1678. return
  1679. }
  1680. this.trigger(type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td)
  1681. this.trigger(type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr, field)
  1682. // if click to select - then trigger the checkbox/radio click
  1683. if (
  1684. type === 'click' &&
  1685. this.options.clickToSelect &&
  1686. column.clickToSelect &&
  1687. !this.options.ignoreClickToSelectOn(target)
  1688. ) {
  1689. const $selectItem = $tr.find(Utils.sprintf('[name="%s"]', this.options.selectItemName))
  1690. if ($selectItem.length) {
  1691. $selectItem[0].click() // #144: .trigger('click') bug
  1692. }
  1693. }
  1694. })
  1695. this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', e => {
  1696. e.preventDefault()
  1697. const $this = $(e.currentTarget) // Fix #980 Detail view, when searching, returns wrong row
  1698. const $tr = $this.parent().parent()
  1699. const index = $tr.data('index')
  1700. const row = data[index]
  1701. // remove and update
  1702. if ($tr.next().is('tr.detail-view')) {
  1703. $this.find('i').attr('class', Utils.sprintf('%s %s', this.options.iconsPrefix, this.options.icons.detailOpen))
  1704. this.trigger('collapse-row', index, row, $tr.next())
  1705. $tr.next().remove()
  1706. } else {
  1707. $this.find('i').attr('class', Utils.sprintf('%s %s', this.options.iconsPrefix, this.options.icons.detailClose))
  1708. $tr.after(Utils.sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.find('td').length))
  1709. const $element = $tr.next().find('td')
  1710. const content = Utils.calculateObjectValue(this.options, this.options.detailFormatter, [index, row, $element], '')
  1711. if ($element.length === 1) {
  1712. $element.append(content)
  1713. }
  1714. this.trigger('expand-row', index, row, $element)
  1715. }
  1716. this.resetView()
  1717. return false
  1718. })
  1719. this.$selectItem = this.$body.find(Utils.sprintf('[name="%s"]', this.options.selectItemName))
  1720. this.$selectItem.off('click').on('click', e => {
  1721. e.stopImmediatePropagation()
  1722. const $this = $(e.currentTarget)
  1723. this.check_($this.prop('checked'), $this.data('index'))
  1724. })
  1725. this.header.events.forEach((_events, i) => {
  1726. let events = _events
  1727. if (!events) {
  1728. return
  1729. }
  1730. // fix bug, if events is defined with namespace
  1731. if (typeof events === 'string') {
  1732. events = Utils.calculateObjectValue(null, events)
  1733. }
  1734. const field = this.header.fields[i]
  1735. let fieldIndex = this.getVisibleFields().indexOf(field)
  1736. if (fieldIndex === -1) {
  1737. return
  1738. }
  1739. if (this.options.detailView && !this.options.cardView) {
  1740. fieldIndex += 1
  1741. }
  1742. for (const [key, event] of Object.entries(events)) {
  1743. this.$body.find('>tr:not(.no-records-found)').each((i, tr) => {
  1744. const $tr = $(tr)
  1745. const $td = $tr.find(this.options.cardView ? '.card-view' : 'td').eq(fieldIndex)
  1746. const index = key.indexOf(' ')
  1747. const name = key.substring(0, index)
  1748. const el = key.substring(index + 1)
  1749. $td.find(el).off(name).on(name, e => {
  1750. const index = $tr.data('index')
  1751. const row = this.data[index]
  1752. const value = row[field]
  1753. event.apply(this, [e, value, row, index])
  1754. })
  1755. })
  1756. }
  1757. })
  1758. this.updateSelected()
  1759. this.resetView()
  1760. this.trigger('post-body', data)
  1761. }
  1762. initServer (silent, query, url) {
  1763. let data = {}
  1764. const index = this.header.fields.indexOf(this.options.sortName)
  1765. let params = {
  1766. searchText: this.searchText,
  1767. sortName: this.options.sortName,
  1768. sortOrder: this.options.sortOrder
  1769. }
  1770. if (this.header.sortNames[index]) {
  1771. params.sortName = this.header.sortNames[index]
  1772. }
  1773. if (this.options.pagination && this.options.sidePagination === 'server') {
  1774. params.pageSize = this.options.pageSize === this.options.formatAllRows()
  1775. ? this.options.totalRows : this.options.pageSize
  1776. params.pageNumber = this.options.pageNumber
  1777. }
  1778. if (!(url || this.options.url) && !this.options.ajax) {
  1779. return
  1780. }
  1781. if (this.options.queryParamsType === 'limit') {
  1782. params = {
  1783. search: params.searchText,
  1784. sort: params.sortName,
  1785. order: params.sortOrder
  1786. }
  1787. if (this.options.pagination && this.options.sidePagination === 'server') {
  1788. params.offset = this.options.pageSize === this.options.formatAllRows()
  1789. ? 0 : this.options.pageSize * (this.options.pageNumber - 1)
  1790. params.limit = this.options.pageSize === this.options.formatAllRows()
  1791. ? this.options.totalRows : this.options.pageSize
  1792. if (params.limit === 0) {
  1793. delete params.limit
  1794. }
  1795. }
  1796. }
  1797. if (!($.isEmptyObject(this.filterColumnsPartial))) {
  1798. params.filter = JSON.stringify(this.filterColumnsPartial, null)
  1799. }
  1800. data = Utils.calculateObjectValue(this.options, this.options.queryParams, [params], data)
  1801. $.extend(data, query || {})
  1802. // false to stop request
  1803. if (data === false) {
  1804. return
  1805. }
  1806. if (!silent) {
  1807. this.$tableLoading.show()
  1808. }
  1809. const request = $.extend({}, Utils.calculateObjectValue(null, this.options.ajaxOptions), {
  1810. type: this.options.method,
  1811. url: url || this.options.url,
  1812. data: this.options.contentType === 'application/json' && this.options.method === 'post'
  1813. ? JSON.stringify(data) : data,
  1814. cache: this.options.cache,
  1815. contentType: this.options.contentType,
  1816. dataType: this.options.dataType,
  1817. success: _res => {
  1818. const res = Utils.calculateObjectValue(this.options,
  1819. this.options.responseHandler, [_res], _res)
  1820. this.load(res)
  1821. this.trigger('load-success', res)
  1822. if (!silent) {
  1823. this.$tableLoading.hide()
  1824. }
  1825. },
  1826. error: jqXHR => {
  1827. let data = []
  1828. if (this.options.sidePagination === 'server') {
  1829. data = {}
  1830. data[this.options.totalField] = 0
  1831. data[this.options.dataField] = []
  1832. }
  1833. this.load(data)
  1834. this.trigger('load-error', jqXHR.status, jqXHR)
  1835. if (!silent) this.$tableLoading.hide()
  1836. }
  1837. })
  1838. if (this.options.ajax) {
  1839. Utils.calculateObjectValue(this, this.options.ajax, [request], null)
  1840. } else {
  1841. if (this._xhr && this._xhr.readyState !== 4) {
  1842. this._xhr.abort()
  1843. }
  1844. this._xhr = $.ajax(request)
  1845. }
  1846. }
  1847. initSearchText () {
  1848. if (this.options.search) {
  1849. this.searchText = ''
  1850. if (this.options.searchText !== '') {
  1851. const $search = this.$toolbar.find('.search input')
  1852. $search.val(this.options.searchText)
  1853. this.onSearch({currentTarget: $search, firedByInitSearchText: true})
  1854. }
  1855. }
  1856. }
  1857. getCaret () {
  1858. this.$header.find('th').each((i, th) => {
  1859. $(th).find('.sortable').removeClass('desc asc')
  1860. .addClass($(th).data('field') === this.options.sortName
  1861. ? this.options.sortOrder : 'both')
  1862. })
  1863. }
  1864. updateSelected () {
  1865. const checkAll = this.$selectItem.filter(':enabled').length &&
  1866. this.$selectItem.filter(':enabled').length ===
  1867. this.$selectItem.filter(':enabled').filter(':checked').length
  1868. this.$selectAll.add(this.$selectAll_).prop('checked', checkAll)
  1869. this.$selectItem.each((i, el) => {
  1870. $(el).closest('tr')[$(el).prop('checked') ? 'addClass' : 'removeClass']('selected')
  1871. })
  1872. }
  1873. updateRows () {
  1874. this.$selectItem.each((i, el) => {
  1875. this.data[$(el).data('index')][this.header.stateField] = $(el).prop('checked')
  1876. })
  1877. }
  1878. resetRows () {
  1879. for (const row of this.data) {
  1880. this.$selectAll.prop('checked', false)
  1881. this.$selectItem.prop('checked', false)
  1882. if (this.header.stateField) {
  1883. row[this.header.stateField] = false
  1884. }
  1885. }
  1886. this.initHiddenRows()
  1887. }
  1888. trigger (_name, ...args) {
  1889. const name = `${_name}.bs.table`
  1890. this.options[BootstrapTable.EVENTS[name]](...args)
  1891. this.$el.trigger($.Event(name), args)
  1892. this.options.onAll(name, args)
  1893. this.$el.trigger($.Event('all.bs.table'), [name, args])
  1894. }
  1895. resetHeader () {
  1896. // fix #61: the hidden table reset header bug.
  1897. // fix bug: get $el.css('width') error sometime (height = 500)
  1898. clearTimeout(this.timeoutId_)
  1899. this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), this.$el.is(':hidden') ? 100 : 0)
  1900. }
  1901. fitHeader () {
  1902. if (this.$el.is(':hidden')) {
  1903. this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), 100)
  1904. return
  1905. }
  1906. const fixedBody = this.$tableBody.get(0)
  1907. const scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
  1908. fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight()
  1909. ? Utils.getScrollBarWidth() : 0
  1910. this.$el.css('margin-top', -this.$header.outerHeight())
  1911. const focused = $(':focus')
  1912. if (focused.length > 0) {
  1913. const $th = focused.parents('th')
  1914. if ($th.length > 0) {
  1915. const dataField = $th.attr('data-field')
  1916. if (dataField !== undefined) {
  1917. const $headerTh = this.$header.find(`[data-field='${dataField}']`)
  1918. if ($headerTh.length > 0) {
  1919. $headerTh.find(':input').addClass('focus-temp')
  1920. }
  1921. }
  1922. }
  1923. }
  1924. this.$header_ = this.$header.clone(true, true)
  1925. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]')
  1926. this.$tableHeader.css({
  1927. 'margin-right': scrollWidth
  1928. }).find('table').css('width', this.$el.outerWidth())
  1929. .html('').attr('class', this.$el.attr('class'))
  1930. .append(this.$header_)
  1931. const focusedTemp = $('.focus-temp:visible:eq(0)')
  1932. if (focusedTemp.length > 0) {
  1933. focusedTemp.focus()
  1934. this.$header.find('.focus-temp').removeClass('focus-temp')
  1935. }
  1936. // fix bug: $.data() is not working as expected after $.append()
  1937. this.$header.find('th[data-field]').each((i, el) => {
  1938. this.$header_.find(Utils.sprintf('th[data-field="%s"]', $(el).data('field'))).data($(el).data())
  1939. })
  1940. const visibleFields = this.getVisibleFields()
  1941. const $ths = this.$header_.find('th')
  1942. let $tr = this.$body.find('>tr:first-child:not(.no-records-found)')
  1943. while ($tr.length && $tr.find('>td[colspan]:not([colspan="1"])').length) {
  1944. $tr = $tr.next()
  1945. }
  1946. $tr.find('> *').each((i, el) => {
  1947. const $this = $(el)
  1948. let index = i
  1949. if (this.options.detailView && !this.options.cardView) {
  1950. if (i === 0) {
  1951. const $thDetail = $ths.filter('.detail')
  1952. const zoomWidth = $thDetail.width() - $thDetail.find('.fht-cell').width()
  1953. $thDetail.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1954. }
  1955. index = i - 1
  1956. }
  1957. if (index === -1) {
  1958. return
  1959. }
  1960. let $th = this.$header_.find(Utils.sprintf('th[data-field="%s"]', visibleFields[index]))
  1961. if ($th.length > 1) {
  1962. $th = $($ths[$this[0].cellIndex])
  1963. }
  1964. const zoomWidth = $th.width() - $th.find('.fht-cell').width()
  1965. $th.find('.fht-cell').width($this.innerWidth() - zoomWidth)
  1966. })
  1967. this.horizontalScroll()
  1968. this.trigger('post-header')
  1969. }
  1970. resetFooter () {
  1971. const data = this.getData()
  1972. const html = []
  1973. if (!this.options.showFooter || this.options.cardView) { // do nothing
  1974. return
  1975. }
  1976. if (!this.options.cardView && this.options.detailView) {
  1977. html.push('<td><div class="th-inner">&nbsp;</div><div class="fht-cell"></div></td>')
  1978. }
  1979. for (const column of this.columns) {
  1980. let falign = ''
  1981. let valign = ''
  1982. const csses = []
  1983. let style = {}
  1984. const class_ = Utils.sprintf(' class="%s"', column['class'])
  1985. if (!column.visible) {
  1986. return
  1987. }
  1988. if (this.options.cardView && (!column.cardVisible)) {
  1989. return
  1990. }
  1991. falign = Utils.sprintf('text-align: %s; ', column.falign ? column.falign : column.align)
  1992. valign = Utils.sprintf('vertical-align: %s; ', column.valign)
  1993. style = Utils.calculateObjectValue(null, this.options.footerStyle)
  1994. if (style && style.css) {
  1995. for (const [key, value] of Object.keys(style.css)) {
  1996. csses.push(`${key}: ${value}`)
  1997. }
  1998. }
  1999. html.push('<td', class_, Utils.sprintf(' style="%s"', falign + valign + csses.concat().join('; ')), '>')
  2000. html.push('<div class="th-inner">')
  2001. html.push(Utils.calculateObjectValue(column, column.footerFormatter, [data], '&nbsp;') || '&nbsp;')
  2002. html.push('</div>')
  2003. html.push('<div class="fht-cell"></div>')
  2004. html.push('</div>')
  2005. html.push('</td>')
  2006. }
  2007. this.$tableFooter.find('tr').html(html.join(''))
  2008. this.$tableFooter.show()
  2009. clearTimeout(this.timeoutFooter_)
  2010. this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this),
  2011. this.$el.is(':hidden') ? 100 : 0)
  2012. }
  2013. fitFooter () {
  2014. clearTimeout(this.timeoutFooter_)
  2015. if (this.$el.is(':hidden')) {
  2016. this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), 100)
  2017. return
  2018. }
  2019. const elWidth = this.$el.css('width')
  2020. const scrollWidth = elWidth > this.$tableBody.width() ? Utils.getScrollBarWidth() : 0
  2021. this.$tableFooter.css({
  2022. 'margin-right': scrollWidth
  2023. }).find('table').css('width', elWidth)
  2024. .attr('class', this.$el.attr('class'))
  2025. const $footerTd = this.$tableFooter.find('td')
  2026. this.$body.find('>tr:first-child:not(.no-records-found) > *').each((i, el) => {
  2027. const $this = $(el)
  2028. $footerTd.eq(i).find('.fht-cell').width($this.innerWidth())
  2029. })
  2030. this.horizontalScroll()
  2031. }
  2032. horizontalScroll () {
  2033. // horizontal scroll event
  2034. // TODO: it's probably better improving the layout than binding to scroll event
  2035. this.trigger('scroll-body')
  2036. this.$tableBody.off('scroll').on('scroll', ({currentTarget}) => {
  2037. if (this.options.showHeader && this.options.height) {
  2038. this.$tableHeader.scrollLeft($(currentTarget).scrollLeft())
  2039. }
  2040. if (this.options.showFooter && !this.options.cardView) {
  2041. this.$tableFooter.scrollLeft($(currentTarget).scrollLeft())
  2042. }
  2043. })
  2044. }
  2045. toggleColumn (index, checked, needUpdate) {
  2046. if (index === -1) {
  2047. return
  2048. }
  2049. this.columns[index].visible = checked
  2050. this.initHeader()
  2051. this.initSearch()
  2052. this.initPagination()
  2053. this.initBody()
  2054. if (this.options.showColumns) {
  2055. const $items = this.$toolbar.find('.keep-open input').prop('disabled', false)
  2056. if (needUpdate) {
  2057. $items.filter(Utils.sprintf('[value="%s"]', index)).prop('checked', checked)
  2058. }
  2059. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  2060. $items.filter(':checked').prop('disabled', true)
  2061. }
  2062. }
  2063. }
  2064. getVisibleFields () {
  2065. const visibleFields = []
  2066. for (const field of this.header.fields) {
  2067. const column = this.columns[this.fieldsColumnsIndex[field]]
  2068. if (!column.visible) {
  2069. continue
  2070. }
  2071. visibleFields.push(field)
  2072. }
  2073. return visibleFields
  2074. }
  2075. // PUBLIC FUNCTION DEFINITION
  2076. // =======================
  2077. resetView (params) {
  2078. let padding = 0
  2079. if (params && params.height) {
  2080. this.options.height = params.height
  2081. }
  2082. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  2083. this.$selectItem.length === this.$selectItem.filter(':checked').length)
  2084. if (this.options.cardView) {
  2085. // remove the element css
  2086. this.$el.css('margin-top', '0')
  2087. this.$tableContainer.css('padding-bottom', '0')
  2088. this.$tableFooter.hide()
  2089. return
  2090. }
  2091. if (this.options.showHeader && this.options.height) {
  2092. this.$tableHeader.show()
  2093. this.resetHeader()
  2094. padding += this.$header.outerHeight()
  2095. } else {
  2096. this.$tableHeader.hide()
  2097. this.trigger('post-header')
  2098. }
  2099. if (this.options.showFooter) {
  2100. this.resetFooter()
  2101. if (this.options.height) {
  2102. padding += this.$tableFooter.outerHeight() + 1
  2103. }
  2104. }
  2105. if (this.options.height) {
  2106. const toolbarHeight = this.$toolbar.outerHeight(true)
  2107. const paginationHeight = this.$pagination.outerHeight(true)
  2108. const height = this.options.height - toolbarHeight - paginationHeight
  2109. const tableHeight = this.$tableBody.find('table').outerHeight(true)
  2110. this.$tableContainer.css('height', `${height}px`)
  2111. this.$tableBorder && this.$tableBorder.css('height', `${height - tableHeight - padding - 1}px`)
  2112. }
  2113. // Assign the correct sortable arrow
  2114. this.getCaret()
  2115. this.$tableContainer.css('padding-bottom', `${padding}px`)
  2116. this.trigger('reset-view')
  2117. }
  2118. getData (useCurrentPage) {
  2119. let data = this.options.data
  2120. if (this.searchText || this.options.sortName || !$.isEmptyObject(this.filterColumns) || !$.isEmptyObject(this.filterColumnsPartial)) {
  2121. data = this.data
  2122. }
  2123. if (useCurrentPage) {
  2124. return data.slice(this.pageFrom - 1, this.pageTo)
  2125. }
  2126. return data
  2127. }
  2128. load (_data) {
  2129. let fixedScroll = false
  2130. let data = _data
  2131. // #431: support pagination
  2132. if (this.options.pagination && this.options.sidePagination === 'server') {
  2133. this.options.totalRows = data[this.options.totalField]
  2134. }
  2135. fixedScroll = data.fixedScroll
  2136. data = Array.isArray(data) ? data : data[this.options.dataField]
  2137. this.initData(data)
  2138. this.initSearch()
  2139. this.initPagination()
  2140. this.initBody(fixedScroll)
  2141. }
  2142. append (data) {
  2143. this.initData(data, 'append')
  2144. this.initSearch()
  2145. this.initPagination()
  2146. this.initSort()
  2147. this.initBody(true)
  2148. }
  2149. prepend (data) {
  2150. this.initData(data, 'prepend')
  2151. this.initSearch()
  2152. this.initPagination()
  2153. this.initSort()
  2154. this.initBody(true)
  2155. }
  2156. remove (params) {
  2157. const len = this.options.data.length
  2158. let i
  2159. let row
  2160. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
  2161. return
  2162. }
  2163. for (i = len - 1; i >= 0; i--) {
  2164. row = this.options.data[i]
  2165. if (!row.hasOwnProperty(params.field)) {
  2166. continue
  2167. }
  2168. if (params.values.includes(row[params.field])) {
  2169. this.options.data.splice(i, 1)
  2170. if (this.options.sidePagination === 'server') {
  2171. this.options.totalRows -= 1
  2172. }
  2173. }
  2174. }
  2175. if (len === this.options.data.length) {
  2176. return
  2177. }
  2178. this.initSearch()
  2179. this.initPagination()
  2180. this.initSort()
  2181. this.initBody(true)
  2182. }
  2183. removeAll () {
  2184. if (this.options.data.length > 0) {
  2185. this.options.data.splice(0, this.options.data.length)
  2186. this.initSearch()
  2187. this.initPagination()
  2188. this.initBody(true)
  2189. }
  2190. }
  2191. getRowByUniqueId (_id) {
  2192. const uniqueId = this.options.uniqueId
  2193. const len = this.options.data.length
  2194. let id = _id
  2195. let dataRow = null
  2196. let i
  2197. let row
  2198. let rowUniqueId
  2199. for (i = len - 1; i >= 0; i--) {
  2200. row = this.options.data[i]
  2201. if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column
  2202. rowUniqueId = row[uniqueId]
  2203. } else if (row._data && row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property
  2204. rowUniqueId = row._data[uniqueId]
  2205. } else {
  2206. continue
  2207. }
  2208. if (typeof rowUniqueId === 'string') {
  2209. id = id.toString()
  2210. } else if (typeof rowUniqueId === 'number') {
  2211. if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) {
  2212. id = parseInt(id)
  2213. } else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) {
  2214. id = parseFloat(id)
  2215. }
  2216. }
  2217. if (rowUniqueId === id) {
  2218. dataRow = row
  2219. break
  2220. }
  2221. }
  2222. return dataRow
  2223. }
  2224. removeByUniqueId (id) {
  2225. const len = this.options.data.length
  2226. const row = this.getRowByUniqueId(id)
  2227. if (row) {
  2228. this.options.data.splice(this.options.data.indexOf(row), 1)
  2229. }
  2230. if (len === this.options.data.length) {
  2231. return
  2232. }
  2233. this.initSearch()
  2234. this.initPagination()
  2235. this.initBody(true)
  2236. }
  2237. updateByUniqueId (params) {
  2238. const allParams = Array.isArray(params) ? params : [params]
  2239. for (const params of allParams) {
  2240. if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
  2241. continue
  2242. }
  2243. const rowId = this.options.data.indexOf(this.getRowByUniqueId(params.id))
  2244. if (rowId === -1) {
  2245. continue
  2246. }
  2247. $.extend(this.options.data[rowId], params.row)
  2248. }
  2249. this.initSearch()
  2250. this.initPagination()
  2251. this.initSort()
  2252. this.initBody(true)
  2253. }
  2254. refreshColumnTitle (params) {
  2255. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('title')) {
  2256. return
  2257. }
  2258. this.columns[this.fieldsColumnsIndex[params.field]].title =
  2259. this.options.escape ? Utils.escapeHTML(params.title) : params.title
  2260. if (this.columns[this.fieldsColumnsIndex[params.field]].visible) {
  2261. const header = this.options.height !== undefined ? this.$tableHeader : this.$header
  2262. header.find('th[data-field]').each((i, el) => {
  2263. if ($(el).data('field') === params.field) {
  2264. $($(el).find('.th-inner')[0]).text(params.title)
  2265. return false
  2266. }
  2267. })
  2268. }
  2269. }
  2270. insertRow (params) {
  2271. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  2272. return
  2273. }
  2274. this.options.data.splice(params.index, 0, params.row)
  2275. this.initSearch()
  2276. this.initPagination()
  2277. this.initSort()
  2278. this.initBody(true)
  2279. }
  2280. updateRow (params) {
  2281. const allParams = Array.isArray(params) ? params : [params]
  2282. for (const params of allParams) {
  2283. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  2284. continue
  2285. }
  2286. $.extend(this.options.data[params.index], params.row)
  2287. }
  2288. this.initSearch()
  2289. this.initPagination()
  2290. this.initSort()
  2291. this.initBody(true)
  2292. }
  2293. initHiddenRows () {
  2294. this.hiddenRows = []
  2295. }
  2296. showRow (params) {
  2297. this.toggleRow(params, true)
  2298. }
  2299. hideRow (params) {
  2300. this.toggleRow(params, false)
  2301. }
  2302. toggleRow (params, visible) {
  2303. let row
  2304. if (params.hasOwnProperty('index')) {
  2305. row = this.getData()[params.index]
  2306. } else if (params.hasOwnProperty('uniqueId')) {
  2307. row = this.getRowByUniqueId(params.uniqueId)
  2308. }
  2309. if (!row) {
  2310. return
  2311. }
  2312. const index = Utils.findIndex(this.hiddenRows, row)
  2313. if (!visible && index === -1) {
  2314. this.hiddenRows.push(row)
  2315. } else if (visible && index > -1) {
  2316. this.hiddenRows.splice(index, 1)
  2317. }
  2318. this.initBody(true)
  2319. }
  2320. getHiddenRows (show) {
  2321. if (show) {
  2322. this.initHiddenRows()
  2323. this.initBody(true)
  2324. return
  2325. }
  2326. const data = this.getData()
  2327. const rows = []
  2328. for (const row of data) {
  2329. if (this.hiddenRows.includes(row)) {
  2330. rows.push(row)
  2331. }
  2332. }
  2333. this.hiddenRows = rows
  2334. return rows
  2335. }
  2336. mergeCells (options) {
  2337. const row = options.index
  2338. let col = this.getVisibleFields().indexOf(options.field)
  2339. const rowspan = options.rowspan || 1
  2340. const colspan = options.colspan || 1
  2341. let i
  2342. let j
  2343. const $tr = this.$body.find('>tr')
  2344. if (this.options.detailView && !this.options.cardView) {
  2345. col += 1
  2346. }
  2347. const $td = $tr.eq(row).find('>td').eq(col)
  2348. if (row < 0 || col < 0 || row >= this.data.length) {
  2349. return
  2350. }
  2351. for (i = row; i < row + rowspan; i++) {
  2352. for (j = col; j < col + colspan; j++) {
  2353. $tr.eq(i).find('>td').eq(j).hide()
  2354. }
  2355. }
  2356. $td.attr('rowspan', rowspan).attr('colspan', colspan).show()
  2357. }
  2358. updateCell (params) {
  2359. if (!params.hasOwnProperty('index') ||
  2360. !params.hasOwnProperty('field') ||
  2361. !params.hasOwnProperty('value')) {
  2362. return
  2363. }
  2364. this.data[params.index][params.field] = params.value
  2365. if (params.reinit === false) {
  2366. return
  2367. }
  2368. this.initSort()
  2369. this.initBody(true)
  2370. }
  2371. updateCellById (params) {
  2372. if (!params.hasOwnProperty('id') ||
  2373. !params.hasOwnProperty('field') ||
  2374. !params.hasOwnProperty('value')) {
  2375. return
  2376. }
  2377. const allParams = Array.isArray(params) ? params : [params]
  2378. allParams.forEach(({id, field, value}) => {
  2379. const rowId = this.options.data.indexOf(this.getRowByUniqueId(id))
  2380. if (rowId === -1) {
  2381. return
  2382. }
  2383. this.data[rowId][field] = value
  2384. })
  2385. if (params.reinit === false) {
  2386. return
  2387. }
  2388. this.initSort()
  2389. this.initBody(true)
  2390. }
  2391. getOptions () {
  2392. // Deep copy: remove data
  2393. const options = $.extend({}, this.options)
  2394. delete options.data
  2395. return $.extend(true, {}, options)
  2396. }
  2397. getSelections () {
  2398. // fix #2424: from html with checkbox
  2399. return this.options.data.filter(row =>
  2400. row[this.header.stateField] === true)
  2401. }
  2402. getAllSelections () {
  2403. return this.options.data.filter(row => row[this.header.stateField])
  2404. }
  2405. checkAll () {
  2406. this.checkAll_(true)
  2407. }
  2408. uncheckAll () {
  2409. this.checkAll_(false)
  2410. }
  2411. checkInvert () {
  2412. const $items = this.$selectItem.filter(':enabled')
  2413. let checked = $items.filter(':checked')
  2414. $items.each((i, el) => {
  2415. $(el).prop('checked', !$(el).prop('checked'))
  2416. })
  2417. this.updateRows()
  2418. this.updateSelected()
  2419. this.trigger('uncheck-some', checked)
  2420. checked = this.getSelections()
  2421. this.trigger('check-some', checked)
  2422. }
  2423. checkAll_ (checked) {
  2424. let rows
  2425. if (!checked) {
  2426. rows = this.getSelections()
  2427. }
  2428. this.$selectAll.add(this.$selectAll_).prop('checked', checked)
  2429. this.$selectItem.filter(':enabled').prop('checked', checked)
  2430. this.updateRows()
  2431. if (checked) {
  2432. rows = this.getSelections()
  2433. }
  2434. this.trigger(checked ? 'check-all' : 'uncheck-all', rows)
  2435. }
  2436. check (index) {
  2437. this.check_(true, index)
  2438. }
  2439. uncheck (index) {
  2440. this.check_(false, index)
  2441. }
  2442. check_ (checked, index) {
  2443. const $el = this.$selectItem.filter(`[data-index="${index}"]`)
  2444. const row = this.data[index]
  2445. if ($el.is(':radio') || this.options.singleSelect) {
  2446. for (const r of this.options.data) {
  2447. r[this.header.stateField] = false
  2448. }
  2449. this.$selectItem.filter(':checked').not($el).prop('checked', false)
  2450. }
  2451. row[this.header.stateField] = checked
  2452. $el.prop('checked', checked)
  2453. this.updateSelected()
  2454. this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el)
  2455. }
  2456. checkBy (obj) {
  2457. this.checkBy_(true, obj)
  2458. }
  2459. uncheckBy (obj) {
  2460. this.checkBy_(false, obj)
  2461. }
  2462. checkBy_ (checked, obj) {
  2463. if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
  2464. return
  2465. }
  2466. const rows = []
  2467. this.options.data.forEach((row, i) => {
  2468. if (!row.hasOwnProperty(obj.field)) {
  2469. return false
  2470. }
  2471. if (obj.values.includes(row[obj.field])) {
  2472. const $el = this.$selectItem.filter(':enabled')
  2473. .filter(Utils.sprintf('[data-index="%s"]', i)).prop('checked', checked)
  2474. row[this.header.stateField] = checked
  2475. rows.push(row)
  2476. this.trigger(checked ? 'check' : 'uncheck', row, $el)
  2477. }
  2478. })
  2479. this.updateSelected()
  2480. this.trigger(checked ? 'check-some' : 'uncheck-some', rows)
  2481. }
  2482. destroy () {
  2483. this.$el.insertBefore(this.$container)
  2484. $(this.options.toolbar).insertBefore(this.$el)
  2485. this.$container.next().remove()
  2486. this.$container.remove()
  2487. this.$el.html(this.$el_.html())
  2488. .css('margin-top', '0')
  2489. .attr('class', this.$el_.attr('class') || '') // reset the class
  2490. }
  2491. showLoading () {
  2492. this.$tableLoading.show()
  2493. }
  2494. hideLoading () {
  2495. this.$tableLoading.hide()
  2496. }
  2497. togglePagination () {
  2498. this.options.pagination = !this.options.pagination
  2499. const button = this.$toolbar.find('button[name="paginationSwitch"] i')
  2500. if (this.options.pagination) {
  2501. button.attr('class', `${this.options.iconsPrefix} ${this.options.icons.paginationSwitchDown}`)
  2502. } else {
  2503. button.attr('class', `${this.options.iconsPrefix} ${this.options.icons.paginationSwitchUp}`)
  2504. }
  2505. this.updatePagination()
  2506. }
  2507. toggleFullscreen () {
  2508. this.$el.closest('.bootstrap-table').toggleClass('fullscreen')
  2509. }
  2510. refresh (params) {
  2511. if (params && params.url) {
  2512. this.options.url = params.url
  2513. }
  2514. if (params && params.pageNumber) {
  2515. this.options.pageNumber = params.pageNumber
  2516. }
  2517. if (params && params.pageSize) {
  2518. this.options.pageSize = params.pageSize
  2519. }
  2520. this.initServer(params && params.silent,
  2521. params && params.query, params && params.url)
  2522. this.trigger('refresh', params)
  2523. }
  2524. resetWidth () {
  2525. if (this.options.showHeader && this.options.height) {
  2526. this.fitHeader()
  2527. }
  2528. if (this.options.showFooter && !this.options.cardView) {
  2529. this.fitFooter()
  2530. }
  2531. }
  2532. showColumn (field) {
  2533. this.toggleColumn(this.fieldsColumnsIndex[field], true, true)
  2534. }
  2535. hideColumn (field) {
  2536. this.toggleColumn(this.fieldsColumnsIndex[field], false, true)
  2537. }
  2538. getHiddenColumns () {
  2539. return this.columns.filter(({visible}) => !visible)
  2540. }
  2541. getVisibleColumns () {
  2542. return this.columns.filter(({visible}) => visible)
  2543. }
  2544. toggleAllColumns (visible) {
  2545. for (const column of this.columns) {
  2546. column.visible = visible
  2547. }
  2548. this.initHeader()
  2549. this.initSearch()
  2550. this.initPagination()
  2551. this.initBody()
  2552. if (this.options.showColumns) {
  2553. const $items = this.$toolbar.find('.keep-open input').prop('disabled', false)
  2554. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  2555. $items.filter(':checked').prop('disabled', true)
  2556. }
  2557. }
  2558. }
  2559. showAllColumns () {
  2560. this.toggleAllColumns(true)
  2561. }
  2562. hideAllColumns () {
  2563. this.toggleAllColumns(false)
  2564. }
  2565. filterBy (columns) {
  2566. this.filterColumns = $.isEmptyObject(columns) ? {} : columns
  2567. this.options.pageNumber = 1
  2568. this.initSearch()
  2569. this.updatePagination()
  2570. }
  2571. scrollTo (_value) {
  2572. if (typeof _value === 'undefined') {
  2573. return this.$tableBody.scrollTop()
  2574. }
  2575. let value = _value
  2576. if (typeof _value === 'string' && _value === 'bottom') {
  2577. value = this.$tableBody[0].scrollHeight
  2578. }
  2579. this.$tableBody.scrollTop(value)
  2580. }
  2581. getScrollPosition () {
  2582. return this.scrollTo()
  2583. }
  2584. selectPage (page) {
  2585. if (page > 0 && page <= this.options.totalPages) {
  2586. this.options.pageNumber = page
  2587. this.updatePagination()
  2588. }
  2589. }
  2590. prevPage () {
  2591. if (this.options.pageNumber > 1) {
  2592. this.options.pageNumber--
  2593. this.updatePagination()
  2594. }
  2595. }
  2596. nextPage () {
  2597. if (this.options.pageNumber < this.options.totalPages) {
  2598. this.options.pageNumber++
  2599. this.updatePagination()
  2600. }
  2601. }
  2602. toggleView () {
  2603. this.options.cardView = !this.options.cardView
  2604. this.initHeader()
  2605. // Fixed remove toolbar when click cardView button.
  2606. // this.initToolbar();
  2607. const $icon = this.$toolbar.find('button[name="toggle"] i')
  2608. if (this.options.cardView) {
  2609. $icon.removeClass(this.options.icons.toggleOff)
  2610. $icon.addClass(this.options.icons.toggleOn)
  2611. } else {
  2612. $icon.removeClass(this.options.icons.toggleOn)
  2613. $icon.addClass(this.options.icons.toggleOff)
  2614. }
  2615. this.initBody()
  2616. this.trigger('toggle', this.options.cardView)
  2617. }
  2618. refreshOptions (options) {
  2619. // If the objects are equivalent then avoid the call of destroy / init methods
  2620. if (Utils.compareObjects(this.options, options, true)) {
  2621. return
  2622. }
  2623. this.options = $.extend(this.options, options)
  2624. this.trigger('refresh-options', this.options)
  2625. this.destroy()
  2626. this.init()
  2627. }
  2628. resetSearch (text) {
  2629. const $search = this.$toolbar.find('.search input')
  2630. $search.val(text || '')
  2631. this.onSearch({currentTarget: $search})
  2632. }
  2633. expandRow_ (expand, index) {
  2634. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"]', index))
  2635. if ($tr.next().is('tr.detail-view') === (!expand)) {
  2636. $tr.find('> td > .detail-icon').click()
  2637. }
  2638. }
  2639. expandRow (index) {
  2640. this.expandRow_(true, index)
  2641. }
  2642. collapseRow (index) {
  2643. this.expandRow_(false, index)
  2644. }
  2645. expandAllRows (isSubTable) {
  2646. if (isSubTable) {
  2647. const $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"]', 0))
  2648. let detailIcon = null
  2649. let executeInterval = false
  2650. let idInterval = -1
  2651. if (!$tr.next().is('tr.detail-view')) {
  2652. $tr.find('> td > .detail-icon').click()
  2653. executeInterval = true
  2654. } else if (!$tr.next().next().is('tr.detail-view')) {
  2655. $tr.next().find('.detail-icon').click()
  2656. executeInterval = true
  2657. }
  2658. if (executeInterval) {
  2659. try {
  2660. idInterval = setInterval(() => {
  2661. detailIcon = this.$body.find('tr.detail-view').last().find('.detail-icon')
  2662. if (detailIcon.length > 0) {
  2663. detailIcon.click()
  2664. } else {
  2665. clearInterval(idInterval)
  2666. }
  2667. }, 1)
  2668. } catch (ex) {
  2669. clearInterval(idInterval)
  2670. }
  2671. }
  2672. } else {
  2673. const trs = this.$body.children()
  2674. for (let i = 0; i < trs.length; i++) {
  2675. this.expandRow_(true, $(trs[i]).data('index'))
  2676. }
  2677. }
  2678. }
  2679. collapseAllRows (isSubTable) {
  2680. if (isSubTable) {
  2681. this.expandRow_(false, 0)
  2682. } else {
  2683. const trs = this.$body.children()
  2684. for (let i = 0; i < trs.length; i++) {
  2685. this.expandRow_(false, $(trs[i]).data('index'))
  2686. }
  2687. }
  2688. }
  2689. updateFormatText (name, text) {
  2690. if (this.options[Utils.sprintf('format%s', name)]) {
  2691. if (typeof text === 'string') {
  2692. this.options[Utils.sprintf('format%s', name)] = () => text
  2693. } else if (typeof text === 'function') {
  2694. this.options[Utils.sprintf('format%s', name)] = text
  2695. }
  2696. }
  2697. this.initToolbar()
  2698. this.initPagination()
  2699. this.initBody()
  2700. }
  2701. }
  2702. BootstrapTable.DEFAULTS = DEFAULTS
  2703. BootstrapTable.LOCALES = LOCALES
  2704. BootstrapTable.COLUMN_DEFAULTS = COLUMN_DEFAULTS
  2705. BootstrapTable.EVENTS = EVENTS
  2706. // BOOTSTRAP TABLE PLUGIN DEFINITION
  2707. // =======================
  2708. const allowedMethods = [
  2709. 'getOptions',
  2710. 'getSelections', 'getAllSelections', 'getData',
  2711. 'load', 'append', 'prepend', 'remove', 'removeAll',
  2712. 'insertRow', 'updateRow', 'updateCell',
  2713. 'updateByUniqueId', 'removeByUniqueId',
  2714. 'getRowByUniqueId', 'showRow', 'hideRow', 'getHiddenRows',
  2715. 'mergeCells', 'refreshColumnTitle',
  2716. 'checkAll', 'uncheckAll', 'checkInvert',
  2717. 'check', 'uncheck',
  2718. 'checkBy', 'uncheckBy',
  2719. 'refresh',
  2720. 'resetView',
  2721. 'resetWidth',
  2722. 'destroy',
  2723. 'showLoading', 'hideLoading',
  2724. 'showColumn', 'hideColumn',
  2725. 'getHiddenColumns', 'getVisibleColumns',
  2726. 'showAllColumns', 'hideAllColumns',
  2727. 'filterBy',
  2728. 'scrollTo',
  2729. 'getScrollPosition',
  2730. 'selectPage', 'prevPage', 'nextPage',
  2731. 'togglePagination',
  2732. 'toggleView',
  2733. 'refreshOptions',
  2734. 'resetSearch',
  2735. 'expandRow', 'collapseRow',
  2736. 'expandAllRows', 'collapseAllRows',
  2737. 'updateFormatText', 'updateCellById'
  2738. ]
  2739. $.BootstrapTable = BootstrapTable
  2740. $.fn.bootstrapTable = function (option, ...args) {
  2741. let value
  2742. this.each((i, el) => {
  2743. let data = $(el).data('bootstrap.table')
  2744. const options = $.extend({}, BootstrapTable.DEFAULTS, $(el).data(),
  2745. typeof option === 'object' && option)
  2746. if (typeof option === 'string') {
  2747. if (!allowedMethods.includes(option)) {
  2748. throw new Error(`Unknown method: ${option}`)
  2749. }
  2750. if (!data) {
  2751. return
  2752. }
  2753. value = data[option](...args)
  2754. if (option === 'destroy') {
  2755. $(el).removeData('bootstrap.table')
  2756. }
  2757. }
  2758. if (!data) {
  2759. $(el).data('bootstrap.table', (data = new $.BootstrapTable(el, options)))
  2760. }
  2761. })
  2762. return typeof value === 'undefined' ? this : value
  2763. }
  2764. $.fn.bootstrapTable.Constructor = BootstrapTable
  2765. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS
  2766. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS
  2767. $.fn.bootstrapTable.locales = BootstrapTable.LOCALES
  2768. $.fn.bootstrapTable.methods = allowedMethods
  2769. $.fn.bootstrapTable.utils = Utils
  2770. // BOOTSTRAP TABLE INIT
  2771. // =======================
  2772. $(() => {
  2773. $('[data-toggle="table"]').bootstrapTable()
  2774. })
  2775. })(jQuery)