bootstrap-table-filter-control.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. /**
  2. * @author: Dennis Hernández
  3. * @webSite: http://djhvscf.github.io/Blog
  4. * @version: v3.0.0
  5. */
  6. import * as UtilsFilterControl from './utils.js'
  7. const Utils = $.fn.bootstrapTable.utils
  8. $.extend($.fn.bootstrapTable.defaults, {
  9. filterControl: false,
  10. filterControlVisible: true,
  11. filterControlMultipleSearch: false,
  12. filterControlMultipleSearchDelimiter: ',',
  13. // eslint-disable-next-line no-unused-vars
  14. onColumnSearch (field, text) {
  15. return false
  16. },
  17. onCreatedControls () {
  18. return false
  19. },
  20. alignmentSelectControlOptions: undefined,
  21. filterTemplate: {
  22. input (that, column, placeholder, value) {
  23. return Utils.sprintf(
  24. '<input type="search" class="%s bootstrap-table-filter-control-%s search-input" style="width: 100%;" placeholder="%s" value="%s">',
  25. UtilsFilterControl.getInputClass(that),
  26. column.field,
  27. 'undefined' === typeof placeholder ? '' : placeholder,
  28. 'undefined' === typeof value ? '' : value
  29. )
  30. },
  31. select (that, column) {
  32. return Utils.sprintf(
  33. '<select class="%s bootstrap-table-filter-control-%s %s" %s style="width: 100%;" dir="%s"></select>',
  34. UtilsFilterControl.getInputClass(that, true),
  35. column.field,
  36. '',
  37. '',
  38. UtilsFilterControl.getDirectionOfSelectOptions(
  39. that.options.alignmentSelectControlOptions
  40. )
  41. )
  42. },
  43. datepicker (that, column, value) {
  44. return Utils.sprintf(
  45. '<input type="date" class="%s date-filter-control bootstrap-table-filter-control-%s" style="width: 100%;" value="%s">',
  46. UtilsFilterControl.getInputClass(that),
  47. column.field,
  48. 'undefined' === typeof value ? '' : value
  49. )
  50. }
  51. },
  52. searchOnEnterKey: false,
  53. showFilterControlSwitch: false,
  54. sortSelectOptions: false,
  55. // internal variables
  56. _valuesFilterControl: [],
  57. _initialized: false,
  58. _isRendering: false,
  59. _usingMultipleSelect: false
  60. })
  61. $.extend($.fn.bootstrapTable.columnDefaults, {
  62. filterControl: undefined, // input, select, datepicker
  63. filterControlMultipleSelect: false,
  64. filterControlMultipleSelectOptions: {},
  65. filterDataCollector: undefined,
  66. filterData: undefined,
  67. filterDatepickerOptions: {},
  68. filterStrictSearch: false,
  69. filterStartsWithSearch: false,
  70. filterControlPlaceholder: '',
  71. filterDefault: '',
  72. filterOrderBy: 'asc', // asc || desc
  73. filterCustomSearch: undefined
  74. })
  75. $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
  76. 'column-search.bs.table': 'onColumnSearch',
  77. 'created-controls.bs.table': 'onCreatedControls'
  78. })
  79. $.extend($.fn.bootstrapTable.defaults.icons, {
  80. filterControlSwitchHide: {
  81. bootstrap3: 'glyphicon-zoom-out icon-zoom-out',
  82. bootstrap5: 'bi-zoom-out',
  83. materialize: 'zoom_out'
  84. }[$.fn.bootstrapTable.theme] || 'fa-search-minus',
  85. filterControlSwitchShow: {
  86. bootstrap3: 'glyphicon-zoom-in icon-zoom-in',
  87. bootstrap5: 'bi-zoom-in',
  88. materialize: 'zoom_in'
  89. }[$.fn.bootstrapTable.theme] || 'fa-search-plus'
  90. })
  91. $.extend($.fn.bootstrapTable.locales, {
  92. formatFilterControlSwitch () {
  93. return 'Hide/Show controls'
  94. },
  95. formatFilterControlSwitchHide () {
  96. return 'Hide controls'
  97. },
  98. formatFilterControlSwitchShow () {
  99. return 'Show controls'
  100. }
  101. })
  102. $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales)
  103. $.extend($.fn.bootstrapTable.defaults, {
  104. formatClearSearch () {
  105. return 'Clear filters'
  106. }
  107. })
  108. $.fn.bootstrapTable.methods.push('triggerSearch')
  109. $.fn.bootstrapTable.methods.push('clearFilterControl')
  110. $.fn.bootstrapTable.methods.push('toggleFilterControl')
  111. $.BootstrapTable = class extends $.BootstrapTable {
  112. init () {
  113. // Make sure that the filterControl option is set
  114. if (this.options.filterControl) {
  115. // Make sure that the internal variables are set correctly
  116. this._valuesFilterControl = []
  117. this._initialized = false
  118. this._usingMultipleSelect = false
  119. this._isRendering = false
  120. this.$el
  121. .on('reset-view.bs.table', Utils.debounce(() => {
  122. UtilsFilterControl.initFilterSelectControls(this)
  123. UtilsFilterControl.setValues(this)
  124. }, 3))
  125. .on('toggle.bs.table', Utils.debounce((_, cardView) => {
  126. this._initialized = false
  127. if (!cardView) {
  128. UtilsFilterControl.initFilterSelectControls(this)
  129. UtilsFilterControl.setValues(this)
  130. this._initialized = true
  131. }
  132. }, 1))
  133. .on('post-header.bs.table', Utils.debounce(() => {
  134. UtilsFilterControl.initFilterSelectControls(this)
  135. UtilsFilterControl.setValues(this)
  136. }, 3))
  137. .on('column-switch.bs.table', Utils.debounce(() => {
  138. UtilsFilterControl.setValues(this)
  139. if (this.options.height) {
  140. this.fitHeader()
  141. }
  142. }, 1))
  143. .on('post-body.bs.table', Utils.debounce(() => {
  144. if (this.options.height && !this.options.filterControlContainer && this.options.filterControlVisible) {
  145. UtilsFilterControl.fixHeaderCSS(this)
  146. }
  147. this.$tableLoading.css('top', this.$header.outerHeight() + 1)
  148. }, 1))
  149. .on('all.bs.table', () => {
  150. UtilsFilterControl.syncHeaders(this)
  151. })
  152. }
  153. super.init()
  154. }
  155. initBody () {
  156. super.initBody()
  157. if (!this.options.filterControl) {
  158. return
  159. }
  160. Utils.debounce(() => {
  161. UtilsFilterControl.initFilterSelectControls(this)
  162. UtilsFilterControl.setValues(this)
  163. }, 3)()
  164. }
  165. load (data) {
  166. super.load(data)
  167. if (!this.options.filterControl) {
  168. return
  169. }
  170. UtilsFilterControl.createControls(this, UtilsFilterControl.getControlContainer(this))
  171. UtilsFilterControl.setValues(this)
  172. }
  173. initHeader () {
  174. super.initHeader()
  175. if (!this.options.filterControl) {
  176. return
  177. }
  178. UtilsFilterControl.createControls(this, UtilsFilterControl.getControlContainer(this))
  179. this._initialized = true
  180. }
  181. initSearch () {
  182. const that = this
  183. const filterPartial = $.isEmptyObject(that.filterColumnsPartial) ? null : that.filterColumnsPartial
  184. super.initSearch()
  185. if (this.options.sidePagination === 'server' || filterPartial === null) {
  186. return
  187. }
  188. // Check partial column filter
  189. that.data = filterPartial ?
  190. that.data.filter((item, i) => {
  191. const itemIsExpected = []
  192. const keys1 = Object.keys(item)
  193. const keys2 = Object.keys(filterPartial)
  194. const keys = keys1.concat(keys2.filter(item => !keys1.includes(item)))
  195. keys.forEach(key => {
  196. const thisColumn = that.columns[that.fieldsColumnsIndex[key]]
  197. const rawFilterValue = (filterPartial[key] || '')
  198. let filterValue = rawFilterValue.toLowerCase()
  199. let value = Utils.unescapeHTML(Utils.getItemField(item, key, false))
  200. let tmpItemIsExpected
  201. if (this.options.searchAccentNeutralise) {
  202. filterValue = Utils.normalizeAccent(filterValue)
  203. }
  204. let filterValues = [filterValue]
  205. if (
  206. this.options.filterControlMultipleSearch
  207. ) {
  208. filterValues = filterValue.split(this.options.filterControlMultipleSearchDelimiter)
  209. }
  210. filterValues.forEach(filterValue => {
  211. if (tmpItemIsExpected === true) {
  212. return
  213. }
  214. filterValue = filterValue.trim()
  215. if (filterValue === '') {
  216. tmpItemIsExpected = true
  217. } else {
  218. // Fix #142: search use formatted data
  219. if (thisColumn) {
  220. if (thisColumn.searchFormatter || thisColumn._forceFormatter) {
  221. value = $.fn.bootstrapTable.utils.calculateObjectValue(
  222. that.header,
  223. that.header.formatters[$.inArray(key, that.header.fields)],
  224. [value, item, i],
  225. value
  226. )
  227. }
  228. }
  229. if ($.inArray(key, that.header.fields) !== -1) {
  230. if (value === undefined || value === null) {
  231. tmpItemIsExpected = false
  232. } else if (typeof value === 'object' && thisColumn.filterCustomSearch) {
  233. itemIsExpected.push(that.isValueExpected(rawFilterValue, value, thisColumn, key))
  234. } else if (typeof value === 'object' && Array.isArray(value)) {
  235. value.forEach(objectValue => {
  236. if (tmpItemIsExpected) {
  237. return
  238. }
  239. tmpItemIsExpected = that.isValueExpected(filterValue, objectValue, thisColumn, key)
  240. })
  241. } else if (typeof value === 'object' && !Array.isArray(value)) {
  242. Object.values(value).forEach(objectValue => {
  243. if (tmpItemIsExpected) {
  244. return
  245. }
  246. tmpItemIsExpected = that.isValueExpected(filterValue, objectValue, thisColumn, key)
  247. })
  248. } else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  249. tmpItemIsExpected = that.isValueExpected(filterValue, value, thisColumn, key)
  250. }
  251. }
  252. }
  253. })
  254. itemIsExpected.push(tmpItemIsExpected)
  255. })
  256. return !itemIsExpected.includes(false)
  257. }) :
  258. that.data
  259. that.unsortedData = [...that.data]
  260. }
  261. isValueExpected (searchValue, value, column, key) {
  262. let tmpItemIsExpected = false
  263. if (
  264. column.filterStrictSearch ||
  265. (column.filterControl === 'select' && column.passed.filterStrictSearch !== false)
  266. ) {
  267. tmpItemIsExpected = value.toString().toLowerCase() === searchValue.toString().toLowerCase()
  268. } else if (column.filterStartsWithSearch) {
  269. tmpItemIsExpected = (`${value}`).toLowerCase().indexOf(searchValue) === 0
  270. } else if (column.filterControl === 'datepicker') {
  271. tmpItemIsExpected = new Date(value).getTime() === new Date(searchValue).getTime()
  272. } else if (this.options.regexSearch) {
  273. tmpItemIsExpected = Utils.regexCompare(value, searchValue)
  274. } else {
  275. tmpItemIsExpected = (`${value}`).toLowerCase().includes(searchValue)
  276. }
  277. const largerSmallerEqualsRegex = /(?:(<=|=>|=<|>=|>|<)(?:\s+)?(\d+)?|(\d+)?(\s+)?(<=|=>|=<|>=|>|<))/gm
  278. const matches = largerSmallerEqualsRegex.exec(searchValue)
  279. if (matches) {
  280. const operator = matches[1] || `${matches[5]}l`
  281. const comparisonValue = matches[2] || matches[3]
  282. const int = parseInt(value, 10)
  283. const comparisonInt = parseInt(comparisonValue, 10)
  284. switch (operator) {
  285. case '>':
  286. case '<l':
  287. tmpItemIsExpected = int > comparisonInt
  288. break
  289. case '<':
  290. case '>l':
  291. tmpItemIsExpected = int < comparisonInt
  292. break
  293. case '<=':
  294. case '=<':
  295. case '>=l':
  296. case '=>l':
  297. tmpItemIsExpected = int <= comparisonInt
  298. break
  299. case '>=':
  300. case '=>':
  301. case '<=l':
  302. case '=<l':
  303. tmpItemIsExpected = int >= comparisonInt
  304. break
  305. default:
  306. break
  307. }
  308. }
  309. if (column.filterCustomSearch) {
  310. const customSearchResult = Utils.calculateObjectValue(this, column.filterCustomSearch, [searchValue, value, key, this.options.data], true)
  311. if (customSearchResult !== null) {
  312. tmpItemIsExpected = customSearchResult
  313. }
  314. }
  315. return tmpItemIsExpected
  316. }
  317. initColumnSearch (filterColumnsDefaults) {
  318. UtilsFilterControl.cacheValues(this)
  319. if (filterColumnsDefaults) {
  320. this.filterColumnsPartial = filterColumnsDefaults
  321. this.updatePagination()
  322. // eslint-disable-next-line guard-for-in
  323. for (const filter in filterColumnsDefaults) {
  324. this.trigger('column-search', filter, filterColumnsDefaults[filter])
  325. }
  326. }
  327. }
  328. initToolbar () {
  329. this.showToolbar = this.showToolbar || this.options.showFilterControlSwitch
  330. this.showSearchClearButton = this.options.filterControl && this.options.showSearchClearButton
  331. if (this.options.showFilterControlSwitch) {
  332. this.buttons = Object.assign(this.buttons, {
  333. filterControlSwitch: {
  334. text: this.options.filterControlVisible ? this.options.formatFilterControlSwitchHide() : this.options.formatFilterControlSwitchShow(),
  335. icon: this.options.filterControlVisible ? this.options.icons.filterControlSwitchHide : this.options.icons.filterControlSwitchShow,
  336. event: this.toggleFilterControl,
  337. attributes: {
  338. 'aria-label': this.options.formatFilterControlSwitch(),
  339. title: this.options.formatFilterControlSwitch()
  340. }
  341. }
  342. })
  343. }
  344. super.initToolbar()
  345. }
  346. resetSearch (text) {
  347. if (this.options.filterControl && this.options.showSearchClearButton) {
  348. this.clearFilterControl()
  349. }
  350. super.resetSearch(text)
  351. }
  352. clearFilterControl () {
  353. if (!this.options.filterControl) {
  354. return
  355. }
  356. const that = this
  357. const table = this.$el.closest('table')
  358. const cookies = UtilsFilterControl.collectBootstrapTableFilterCookies()
  359. const controls = UtilsFilterControl.getSearchControls(that)
  360. // const search = Utils.getSearchInput(this)
  361. let hasValues = false
  362. // Clear cache values
  363. $.each(that._valuesFilterControl, (i, item) => {
  364. hasValues = hasValues ? true : item.value !== ''
  365. item.value = ''
  366. })
  367. // Clear controls in UI
  368. $.each(controls, (i, item) => {
  369. item.value = ''
  370. })
  371. // Cache controls again
  372. UtilsFilterControl.setValues(that)
  373. // clear cookies once the filters are clean
  374. Utils.debounce(() => {
  375. if (cookies && cookies.length > 0) {
  376. $.each(cookies, (i, item) => {
  377. if (that.deleteCookie !== undefined) {
  378. that.deleteCookie(item)
  379. }
  380. })
  381. }
  382. }, that.options.searchTimeOut)()
  383. // If there is not any value in the controls exit this method
  384. if (!hasValues) {
  385. return
  386. }
  387. // Clear each type of filter if it exists.
  388. // Requires the body to reload each time a type of filter is found because we never know
  389. // which ones are going to be present.
  390. if (controls.length > 0) {
  391. this.filterColumnsPartial = {}
  392. controls.eq(0).trigger(this.tagName === 'INPUT' ? 'keyup' : 'change', { keyCode: 13 })
  393. /* controls.each(function () {
  394. $(this).trigger(this.tagName === 'INPUT' ? 'keyup' : 'change', { keyCode: 13 })
  395. })*/
  396. } else {
  397. return
  398. }
  399. /* if (search.length > 0) {
  400. that.resetSearch('fc')
  401. }*/
  402. // use the default sort order if it exists. do nothing if it does not
  403. if (that.options.sortName !== table.data('sortName') || that.options.sortOrder !== table.data('sortOrder')) {
  404. const sorter = this.$header.find(Utils.sprintf('[data-field="%s"]', $(controls[0]).closest('table').data('sortName')))
  405. if (sorter.length > 0) {
  406. that.onSort({ type: 'keypress', currentTarget: sorter })
  407. $(sorter).find('.sortable').trigger('click')
  408. }
  409. }
  410. }
  411. // EVENTS
  412. onColumnSearch ({ currentTarget, keyCode }) {
  413. if (UtilsFilterControl.isKeyAllowed(keyCode)) {
  414. return
  415. }
  416. UtilsFilterControl.cacheValues(this)
  417. // Cookie extension support
  418. if (!this.options.cookie) {
  419. this.options.pageNumber = 1
  420. } else {
  421. // Force call the initServer method in Cookie extension
  422. this._filterControlValuesLoaded = true
  423. }
  424. if ($.isEmptyObject(this.filterColumnsPartial)) {
  425. this.filterColumnsPartial = {}
  426. }
  427. // If searchOnEnterKey is set to true, then we need to iterate over all controls and grab their values.
  428. const controls = this.options.searchOnEnterKey ? UtilsFilterControl.getSearchControls(this).toArray() : [currentTarget]
  429. controls.forEach(element => {
  430. const $element = $(element)
  431. const elementValue = $element.val()
  432. const text = elementValue ? elementValue.trim() : ''
  433. const $field = $element.closest('[data-field]').data('field')
  434. this.trigger('column-search', $field, text)
  435. if (text) {
  436. this.filterColumnsPartial[$field] = text
  437. } else {
  438. delete this.filterColumnsPartial[$field]
  439. }
  440. })
  441. this.onSearch({ currentTarget }, false)
  442. }
  443. toggleFilterControl () {
  444. this.options.filterControlVisible = !this.options.filterControlVisible
  445. // Controls in original header or container.
  446. const $filterControls = UtilsFilterControl.getControlContainer(this).find('.filter-control, .no-filter-control')
  447. if (this.options.filterControlVisible) {
  448. $filterControls.show()
  449. } else {
  450. $filterControls.hide()
  451. this.clearFilterControl()
  452. }
  453. // Controls in fixed header
  454. if (this.options.height) {
  455. const $fixedControls = $('.fixed-table-header table thead').find('.filter-control, .no-filter-control')
  456. $fixedControls.toggle(this.options.filterControlVisible)
  457. UtilsFilterControl.fixHeaderCSS(this)
  458. }
  459. const icon = this.options.showButtonIcons ? this.options.filterControlVisible ? this.options.icons.filterControlSwitchHide : this.options.icons.filterControlSwitchShow : ''
  460. const text = this.options.showButtonText ? this.options.filterControlVisible ? this.options.formatFilterControlSwitchHide() : this.options.formatFilterControlSwitchShow() : ''
  461. this.$toolbar.find('>.columns').find('.filter-control-switch')
  462. .html(`${Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, icon) } ${ text}`)
  463. }
  464. triggerSearch () {
  465. const searchControls = UtilsFilterControl.getSearchControls(this)
  466. searchControls.each(function () {
  467. const $element = $(this)
  468. if ($element.is('select')) {
  469. $element.trigger('change')
  470. } else {
  471. $element.trigger('keyup')
  472. }
  473. })
  474. }
  475. _toggleColumn (index, checked, needUpdate) {
  476. this._initialized = false
  477. super._toggleColumn(index, checked, needUpdate)
  478. UtilsFilterControl.syncHeaders(this)
  479. }
  480. }