bootstrap-table.js 97 KB

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