bootstrap-table-filter-control.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /**
  2. * @author: Dennis Hernández
  3. * @webSite: http://djhvscf.github.io/Blog
  4. * @version: v2.3.0
  5. */
  6. import * as UtilsFilterControl from './utils'
  7. const Utils = $.fn.bootstrapTable.utils
  8. $.extend($.fn.bootstrapTable.defaults, {
  9. filterControl: false,
  10. filterControlVisible: true,
  11. onColumnSearch (field, text) {
  12. return false
  13. },
  14. onCreatedControls () {
  15. return true
  16. },
  17. alignmentSelectControlOptions: undefined,
  18. filterTemplate: {
  19. input (that, field, placeholder, value) {
  20. return Utils.sprintf(
  21. '<input type="text" class="form-control bootstrap-table-filter-control-%s search-input" style="width: 100%;" placeholder="%s" value="%s">',
  22. field,
  23. 'undefined' === typeof placeholder ? '' : placeholder,
  24. 'undefined' === typeof value ? '' : value
  25. )
  26. },
  27. select ({options}, field) {
  28. return Utils.sprintf(
  29. '<select class="form-control bootstrap-table-filter-control-%s" style="width: 100%;" dir="%s"></select>',
  30. field,
  31. UtilsFilterControl.getDirectionOfSelectOptions(
  32. options.alignmentSelectControlOptions
  33. )
  34. )
  35. },
  36. datepicker (that, field, value) {
  37. return Utils.sprintf(
  38. '<input type="text" class="form-control date-filter-control bootstrap-table-filter-control-%s" style="width: 100%;" value="%s">',
  39. field,
  40. 'undefined' === typeof value ? '' : value
  41. )
  42. }
  43. },
  44. disableControlWhenSearch: false,
  45. searchOnEnterKey: false,
  46. showFilterControlSwitch: false,
  47. // internal variables
  48. valuesFilterControl: []
  49. })
  50. $.extend($.fn.bootstrapTable.columnDefaults, {
  51. filterControl: undefined,
  52. filterDataCollector: undefined,
  53. filterData: undefined,
  54. filterDatepickerOptions: undefined,
  55. filterStrictSearch: false,
  56. filterStartsWithSearch: false,
  57. filterControlPlaceholder: '',
  58. filterDefault: '',
  59. filterOrderBy: 'asc' // asc || desc
  60. })
  61. $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
  62. 'column-search.bs.table': 'onColumnSearch',
  63. 'created-controls.bs.table': 'onCreatedControls'
  64. })
  65. $.extend($.fn.bootstrapTable.defaults.icons, {
  66. clear: {
  67. bootstrap3: 'glyphicon-trash icon-clear'
  68. }[$.fn.bootstrapTable.theme] || 'fa-trash',
  69. filterControlSwitchHide: {
  70. bootstrap3: 'glyphicon-zoom-out icon-zoom-out',
  71. materialize: 'zoom_out'
  72. }[$.fn.bootstrapTable.theme] || 'fa-search-minus',
  73. filterControlSwitchShow: {
  74. bootstrap3: 'glyphicon-zoom-in icon-zoom-in',
  75. materialize: 'zoom_in'
  76. }[$.fn.bootstrapTable.theme] || 'fa-search-plus'
  77. })
  78. $.extend($.fn.bootstrapTable.locales, {
  79. formatFilterControlSwitch () {
  80. return 'Hide/Show controls'
  81. },
  82. formatFilterControlSwitchHide () {
  83. return 'Hide controls'
  84. },
  85. formatFilterControlSwitchShow () {
  86. return 'Show controls'
  87. }
  88. })
  89. $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales)
  90. $.extend($.fn.bootstrapTable.defaults, {
  91. formatClearSearch () {
  92. return 'Clear filters'
  93. }
  94. })
  95. $.fn.bootstrapTable.methods.push('triggerSearch')
  96. $.fn.bootstrapTable.methods.push('clearFilterControl')
  97. $.fn.bootstrapTable.methods.push('toggleFilterControl')
  98. $.BootstrapTable = class extends $.BootstrapTable {
  99. init () {
  100. // Make sure that the filterControl option is set
  101. if (this.options.filterControl) {
  102. const that = this
  103. // Make sure that the internal variables are set correctly
  104. this.options.valuesFilterControl = []
  105. this.$el
  106. .on('reset-view.bs.table', () => {
  107. // Create controls on $tableHeader if the height is set
  108. if (!that.options.height) {
  109. return
  110. }
  111. // Avoid recreate the controls
  112. const $controlContainer = UtilsFilterControl.getControlContainer(that)
  113. if (
  114. $controlContainer.find('select').length > 0 ||
  115. $controlContainer.find('input').length > 0
  116. ) {
  117. return
  118. }
  119. UtilsFilterControl.createControls(that, $controlContainer)
  120. })
  121. .on('post-header.bs.table', () => {
  122. UtilsFilterControl.setValues(that)
  123. })
  124. .on('post-body.bs.table', () => {
  125. if (that.options.height && !that.options.filterControlContainer) {
  126. UtilsFilterControl.fixHeaderCSS(that)
  127. }
  128. this.$tableLoading.css('top', this.$header.outerHeight() + 1)
  129. })
  130. .on('column-switch.bs.table', () => {
  131. UtilsFilterControl.setValues(that)
  132. })
  133. .on('load-success.bs.table', () => {
  134. that.enableControls(true)
  135. })
  136. .on('load-error.bs.table', () => {
  137. that.enableControls(true)
  138. })
  139. }
  140. super.init()
  141. }
  142. initHeader () {
  143. super.initHeader()
  144. if (!this.options.filterControl) {
  145. return
  146. }
  147. UtilsFilterControl.createControls(this, UtilsFilterControl.getControlContainer(this))
  148. }
  149. initBody () {
  150. super.initBody()
  151. UtilsFilterControl.initFilterSelectControls(this)
  152. }
  153. initSearch () {
  154. const that = this
  155. const fp = $.isEmptyObject(that.filterColumnsPartial)
  156. ? null
  157. : that.filterColumnsPartial
  158. super.initSearch()
  159. if (this.options.sidePagination === 'server' || fp === null) {
  160. return
  161. }
  162. // Check partial column filter
  163. that.data = fp
  164. ? that.data.filter((item, i) => {
  165. const itemIsExpected = []
  166. const keys1 = Object.keys(item)
  167. const keys2 = Object.keys(fp)
  168. const keys = keys1.concat(keys2.filter(item => !keys1.includes(item)))
  169. keys.forEach(key => {
  170. const thisColumn = that.columns[that.fieldsColumnsIndex[key]]
  171. const fval = (fp[key] || '').toLowerCase()
  172. let value = Utils.getItemField(item, key, false)
  173. let tmpItemIsExpected
  174. if (fval === '') {
  175. tmpItemIsExpected = true
  176. } else {
  177. // Fix #142: search use formatted data
  178. if (thisColumn && thisColumn.searchFormatter) {
  179. value = $.fn.bootstrapTable.utils.calculateObjectValue(
  180. that.header,
  181. that.header.formatters[$.inArray(key, that.header.fields)],
  182. [value, item, i],
  183. value
  184. )
  185. }
  186. if ($.inArray(key, that.header.fields) !== -1) {
  187. if (value === undefined || value === null) {
  188. tmpItemIsExpected = false
  189. } else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  190. if (thisColumn.filterStrictSearch) {
  191. tmpItemIsExpected = value.toString().toLowerCase() === fval.toString().toLowerCase()
  192. } else if (thisColumn.filterStartsWithSearch) {
  193. tmpItemIsExpected = (`${value}`).toLowerCase().indexOf(fval) === 0
  194. } else {
  195. tmpItemIsExpected = (`${value}`).toLowerCase().includes(fval)
  196. }
  197. const largerSmallerEqualsRegex = /(?:(<=|=>|=<|>=|>|<)(?:\s+)?(\d+)?|(\d+)?(\s+)?(<=|=>|=<|>=|>|<))/gm
  198. const matches = largerSmallerEqualsRegex.exec(fval)
  199. if (matches) {
  200. const operator = matches[1] || `${matches[5]}l`
  201. const comparisonValue = matches[2] || matches[3]
  202. const int = parseInt(value, 10)
  203. const comparisonInt = parseInt(comparisonValue, 10)
  204. switch (operator) {
  205. case '>':
  206. case '<l':
  207. tmpItemIsExpected = int > comparisonInt
  208. break
  209. case '<':
  210. case '>l':
  211. tmpItemIsExpected = int < comparisonInt
  212. break
  213. case '<=':
  214. case '=<':
  215. case '>=l':
  216. case '=>l':
  217. tmpItemIsExpected = int <= comparisonInt
  218. break
  219. case '>=':
  220. case '=>':
  221. case '<=l':
  222. case '=<l':
  223. tmpItemIsExpected = int >= comparisonInt
  224. break
  225. default:
  226. break
  227. }
  228. }
  229. if (thisColumn.filterCustomSearch) {
  230. const customSearchResult = Utils.calculateObjectValue(that, thisColumn.filterCustomSearch, [fval, value, key, that.options.data], true)
  231. if (customSearchResult !== null) {
  232. tmpItemIsExpected = customSearchResult
  233. }
  234. }
  235. }
  236. }
  237. }
  238. itemIsExpected.push(tmpItemIsExpected)
  239. })
  240. return !itemIsExpected.includes(false)
  241. })
  242. : that.data
  243. }
  244. initColumnSearch (filterColumnsDefaults) {
  245. UtilsFilterControl.copyValues(this)
  246. if (filterColumnsDefaults) {
  247. this.filterColumnsPartial = filterColumnsDefaults
  248. this.updatePagination()
  249. for (const filter in filterColumnsDefaults) {
  250. this.trigger('column-search', filter, filterColumnsDefaults[filter])
  251. }
  252. }
  253. }
  254. onColumnSearch ({currentTarget, keyCode}) {
  255. if ($.inArray(keyCode, [37, 38, 39, 40]) > -1) {
  256. return
  257. }
  258. UtilsFilterControl.copyValues(this)
  259. const text = $.trim($(currentTarget).val())
  260. const $field = $(currentTarget)
  261. .closest('[data-field]')
  262. .data('field')
  263. if ($.isEmptyObject(this.filterColumnsPartial)) {
  264. this.filterColumnsPartial = {}
  265. }
  266. if (text) {
  267. this.filterColumnsPartial[$field] = text
  268. } else {
  269. delete this.filterColumnsPartial[$field]
  270. }
  271. this.options.pageNumber = 1
  272. this.enableControls(false)
  273. this.onSearch({currentTarget}, false)
  274. this.trigger('column-search', $field, text)
  275. }
  276. initToolbar () {
  277. this.showToolbar = this.showToolbar || this.options.showFilterControlSwitch
  278. this.showSearchClearButton = this.options.filterControl && this.options.showSearchClearButton
  279. super.initToolbar()
  280. if (this.options.showFilterControlSwitch) {
  281. const $btnGroup = this.$toolbar.find('>.columns')
  282. let $btnFilterControlSwitch = $btnGroup.find('.filter-control-switch')
  283. if (!$btnFilterControlSwitch.length) {
  284. $btnFilterControlSwitch = $(`
  285. <button class="filter-control-switch ${this.constants.buttonsClass}"
  286. type="button" title="${this.options.formatFilterControlSwitch()}">
  287. ${this.options.showButtonIcons ? Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.filterControlVisible ? this.options.icons.filterControlSwitchHide : this.options.icons.filterControlSwitchShow) : ''}
  288. ${this.options.showButtonText ? this.options.filterControlVisible ? this.options.formatFilterControlSwitchHide() : this.options.formatFilterControlSwitchShow() : ''}
  289. </button>
  290. `).appendTo($btnGroup)
  291. $btnFilterControlSwitch.on('click', $.proxy(this.toggleFilterControl, this))
  292. }
  293. }
  294. }
  295. resetSearch (text) {
  296. if (this.options.filterControl && this.options.showSearchClearButton) {
  297. this.clearFilterControl()
  298. }
  299. super.resetSearch(text)
  300. }
  301. clearFilterControl () {
  302. if (this.options.filterControl) {
  303. const that = this
  304. const cookies = UtilsFilterControl.collectBootstrapCookies()
  305. const header = UtilsFilterControl.getCurrentHeader(that)
  306. const table = header.closest('table')
  307. const controls = header.find(UtilsFilterControl.getCurrentSearchControls(that))
  308. const search = that.$toolbar.find('.search input')
  309. let hasValues = false
  310. let timeoutId = 0
  311. $.each(that.options.valuesFilterControl, (i, item) => {
  312. hasValues = hasValues ? true : item.value !== ''
  313. item.value = ''
  314. })
  315. $.each(that.options.filterControls, (i, item) => {
  316. item.text = ''
  317. })
  318. UtilsFilterControl.setValues(that)
  319. // clear cookies once the filters are clean
  320. clearTimeout(timeoutId)
  321. timeoutId = setTimeout(() => {
  322. if (cookies && cookies.length > 0) {
  323. $.each(cookies, (i, item) => {
  324. if (that.deleteCookie !== undefined) {
  325. that.deleteCookie(item)
  326. }
  327. })
  328. }
  329. }, that.options.searchTimeOut)
  330. // If there is not any value in the controls exit this method
  331. if (!hasValues) {
  332. return
  333. }
  334. // Clear each type of filter if it exists.
  335. // Requires the body to reload each time a type of filter is found because we never know
  336. // which ones are going to be present.
  337. if (controls.length > 0) {
  338. this.filterColumnsPartial = {}
  339. $(controls[0]).trigger(
  340. controls[0].tagName === 'INPUT' ? 'keyup' : 'change', {keyCode: 13}
  341. )
  342. } else {
  343. return
  344. }
  345. if (search.length > 0) {
  346. that.resetSearch()
  347. }
  348. // use the default sort order if it exists. do nothing if it does not
  349. if (
  350. that.options.sortName !== table.data('sortName') ||
  351. that.options.sortOrder !== table.data('sortOrder')
  352. ) {
  353. const sorter = header.find(
  354. Utils.sprintf(
  355. '[data-field="%s"]',
  356. $(controls[0])
  357. .closest('table')
  358. .data('sortName')
  359. )
  360. )
  361. if (sorter.length > 0) {
  362. that.onSort({type: 'keypress', currentTarget: sorter})
  363. $(sorter)
  364. .find('.sortable')
  365. .trigger('click')
  366. }
  367. }
  368. }
  369. }
  370. triggerSearch () {
  371. const searchControls = UtilsFilterControl.getSearchControls(this)
  372. searchControls.each(function () {
  373. const el = $(this)
  374. if (el.is('select')) {
  375. el.change()
  376. } else {
  377. el.keyup()
  378. }
  379. })
  380. }
  381. enableControls (enable) {
  382. if (
  383. this.options.disableControlWhenSearch &&
  384. this.options.sidePagination === 'server'
  385. ) {
  386. const searchControls = UtilsFilterControl.getSearchControls(this)
  387. if (!enable) {
  388. searchControls.prop('disabled', 'disabled')
  389. } else {
  390. searchControls.removeProp('disabled')
  391. }
  392. }
  393. }
  394. toggleFilterControl () {
  395. this.options.filterControlVisible = !this.options.filterControlVisible
  396. const $filterControls = UtilsFilterControl.getControlContainer(this).find('.filter-control, .no-filter-control')
  397. if (this.options.filterControlVisible) {
  398. $filterControls.show()
  399. } else {
  400. $filterControls.hide()
  401. this.clearFilterControl()
  402. }
  403. const icon = this.options.showButtonIcons ? this.options.filterControlVisible ? this.options.icons.filterControlSwitchHide : this.options.icons.filterControlSwitchShow : ''
  404. const text = this.options.showButtonText ? this.options.filterControlVisible ? this.options.formatFilterControlSwitchHide() : this.options.formatFilterControlSwitchShow() : ''
  405. this.$toolbar.find('>.columns').find('.filter-control-switch')
  406. .html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, icon) + ' ' + text)
  407. }
  408. }