bootstrap-table-filter-control.js 18 KB

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