bootstrap-table.js 102 KB

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