utils.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. /* eslint-disable no-use-before-define */
  2. const Utils = $.fn.bootstrapTable.utils
  3. const searchControls = 'select, input:not([type="checkbox"]):not([type="radio"])'
  4. export function getOptionsFromSelectControl (selectControl) {
  5. return selectControl.get(selectControl.length - 1).options
  6. }
  7. export function getControlContainer (that) {
  8. if (that.options.filterControlContainer) {
  9. return $(`${that.options.filterControlContainer}`)
  10. }
  11. if (that.options.height && that.options.initialized) {
  12. return $('.fixed-table-header table thead')
  13. }
  14. return that.$header
  15. }
  16. export function isKeyAllowed (keyCode) {
  17. return $.inArray(keyCode, [37, 38, 39, 40]) > -1
  18. }
  19. export function getSearchControls (that) {
  20. return getControlContainer(that).find(searchControls)
  21. }
  22. export function hideUnusedSelectOptions (selectControl, uniqueValues) {
  23. const options = getOptionsFromSelectControl(selectControl)
  24. for (let i = 0; i < options.length; i++) {
  25. if (options[i].value !== '') {
  26. if (!uniqueValues.hasOwnProperty(options[i].value)) {
  27. selectControl.find(Utils.sprintf('option[value=\'%s\']', options[i].value)).hide()
  28. } else {
  29. selectControl.find(Utils.sprintf('option[value=\'%s\']', options[i].value)).show()
  30. }
  31. }
  32. }
  33. }
  34. export function existOptionInSelectControl (selectControl, value) {
  35. const options = getOptionsFromSelectControl(selectControl)
  36. for (let i = 0; i < options.length; i++) {
  37. if (options[i].value === Utils.unescapeHTML(value.toString())) {
  38. // The value is not valid to add
  39. return true
  40. }
  41. }
  42. // If we get here, the value is valid to add
  43. return false
  44. }
  45. export function addOptionToSelectControl (selectControl, _value, text, selected) {
  46. const value = (_value === undefined || _value === null) ? '' : _value.toString().trim()
  47. const $selectControl = $(selectControl.get(selectControl.length - 1))
  48. if (!existOptionInSelectControl(selectControl, value)) {
  49. const option = $(`<option value="${value}">${text}</option>`)
  50. if (value === selected) {
  51. option.attr('selected', true)
  52. }
  53. $selectControl.append(option)
  54. }
  55. }
  56. export function sortSelectControl (selectControl, orderBy) {
  57. const $selectControl = $(selectControl.get(selectControl.length - 1))
  58. const $opts = $selectControl.find('option:gt(0)')
  59. if (orderBy !== 'server') {
  60. $opts.sort((a, b) => {
  61. return Utils.sort(a.textContent, b.textContent, orderBy === 'desc' ? -1 : 1)
  62. })
  63. }
  64. $selectControl.find('option:gt(0)').remove()
  65. $selectControl.append($opts)
  66. }
  67. export function fixHeaderCSS ({ $tableHeader }, pixels = '89px') {
  68. $tableHeader.css('height', pixels)
  69. }
  70. export function getElementClass ($element) {
  71. return $element.attr('class').replace('form-control', '').replace('focus-temp', '').replace('search-input', '').trim()
  72. }
  73. export function getCursorPosition (el) {
  74. if ($(el).is('input[type=search]')) {
  75. let pos = 0
  76. if ('selectionStart' in el) {
  77. pos = el.selectionStart
  78. } else if ('selection' in document) {
  79. el.focus()
  80. const Sel = document.selection.createRange()
  81. const SelLength = document.selection.createRange().text.length
  82. Sel.moveStart('character', -el.value.length)
  83. pos = Sel.text.length - SelLength
  84. }
  85. return pos
  86. }
  87. return -1
  88. }
  89. export function cacheValues (that) {
  90. const searchControls = getSearchControls(that)
  91. that.options.valuesFilterControl = []
  92. searchControls.each(function () {
  93. let $field = $(this)
  94. if (that.options.height && !that.options.filterControlContainer) {
  95. const fieldClass = getElementClass($field)
  96. $field = $(`.fixed-table-header .${fieldClass}`)
  97. } else {
  98. const fieldClass = getElementClass($field)
  99. $field = $(`${that.options.filterControlContainer} .${fieldClass}`)
  100. }
  101. that.options.valuesFilterControl.push({
  102. field: $field.closest('[data-field]').data('field'),
  103. value: $field.val(),
  104. position: getCursorPosition($field.get(0)),
  105. hasFocus: $field.is(':focus')
  106. })
  107. })
  108. }
  109. export function setCaretPosition (elem, caretPos) {
  110. try {
  111. if (elem) {
  112. if (elem.createTextRange) {
  113. const range = elem.createTextRange()
  114. range.move('character', caretPos)
  115. range.select()
  116. } else {
  117. elem.setSelectionRange(caretPos, caretPos)
  118. }
  119. }
  120. }
  121. catch (ex) {
  122. // ignored
  123. }
  124. }
  125. export function setValues (that) {
  126. let field = null
  127. let result = []
  128. const searchControls = getSearchControls(that)
  129. if (that.options.valuesFilterControl.length > 0) {
  130. // Callback to apply after settings fields values
  131. const callbacks = []
  132. searchControls.each((i, el) => {
  133. const $this = $(el)
  134. field = $this.closest('[data-field]').data('field')
  135. result = that.options.valuesFilterControl.filter(valueObj => valueObj.field === field)
  136. if (result.length > 0) {
  137. if (result[0].hasFocus || result[0].value) {
  138. const fieldToFocusCallback = ((element, cacheElementInfo) => {
  139. // Closure here to capture the field information
  140. const closedCallback = () => {
  141. if (cacheElementInfo.hasFocus) {
  142. element.focus()
  143. }
  144. element.value = cacheElementInfo.value
  145. setCaretPosition(element, cacheElementInfo.position)
  146. }
  147. return closedCallback
  148. })($this.get(0), result[0])
  149. callbacks.push(fieldToFocusCallback)
  150. }
  151. }
  152. })
  153. // Callback call.
  154. if (callbacks.length > 0) {
  155. callbacks.forEach(callback => callback())
  156. }
  157. }
  158. }
  159. export function collectBootstrapCookies () {
  160. const cookies = []
  161. const foundCookies = document.cookie.match(/(?:bs.table.)(\w*)/g)
  162. const foundLocalStorage = localStorage
  163. if (foundCookies) {
  164. $.each(foundCookies, (i, _cookie) => {
  165. let cookie = _cookie
  166. if (/./.test(cookie)) {
  167. cookie = cookie.split('.').pop()
  168. }
  169. if ($.inArray(cookie, cookies) === -1) {
  170. cookies.push(cookie)
  171. }
  172. })
  173. }
  174. if (foundLocalStorage) {
  175. for (let i = 0; i < foundLocalStorage.length; i++) {
  176. let cookie = foundLocalStorage.key(i)
  177. if (/./.test(cookie)) {
  178. cookie = cookie.split('.').pop()
  179. }
  180. if (!cookies.includes(cookie)) {
  181. cookies.push(cookie)
  182. }
  183. }
  184. }
  185. return cookies
  186. }
  187. export function escapeID (id) {
  188. // eslint-disable-next-line no-useless-escape
  189. return String(id).replace(/([:.\[\],])/g, '\\$1')
  190. }
  191. export function isColumnSearchableViaSelect ({ filterControl, searchable }) {
  192. return filterControl && filterControl.toLowerCase() === 'select' && searchable
  193. }
  194. export function isFilterDataNotGiven ({ filterData }) {
  195. return filterData === undefined ||
  196. filterData.toLowerCase() === 'column'
  197. }
  198. export function hasSelectControlElement (selectControl) {
  199. return selectControl && selectControl.length > 0 && selectControl.get(selectControl.length - 1).options.length === 0
  200. }
  201. export function initFilterSelectControls (that) {
  202. const data = that.options.data
  203. $.each(that.header.fields, (j, field) => {
  204. const column = that.columns[that.fieldsColumnsIndex[field]]
  205. const selectControl = getControlContainer(that).find(`select.bootstrap-table-filter-control-${escapeID(column.field)}`)
  206. if (isColumnSearchableViaSelect(column) && isFilterDataNotGiven(column) && hasSelectControlElement(selectControl)) {
  207. if (selectControl.get(selectControl.length - 1).options.length === 0) {
  208. // Added the default option, must use a non-breaking space(&nbsp;) to pass the W3C validator
  209. addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder || '&nbsp;', column.filterDefault)
  210. }
  211. const uniqueValues = {}
  212. for (let i = 0; i < data.length; i++) {
  213. // Added a new value
  214. let fieldValue = Utils.getItemField(data[i], field, false)
  215. const formatter = that.options.editable && column.editable ? column._formatter : that.header.formatters[j]
  216. let formattedValue = Utils.calculateObjectValue(that.header, formatter, [fieldValue, data[i], i], fieldValue)
  217. if (column.filterDataCollector) {
  218. formattedValue = Utils.calculateObjectValue(that.header, column.filterDataCollector, [fieldValue, data[i], formattedValue], formattedValue)
  219. }
  220. if (column.searchFormatter) {
  221. fieldValue = formattedValue
  222. }
  223. uniqueValues[formattedValue] = fieldValue
  224. if (typeof formattedValue === 'object' && formattedValue !== null) {
  225. formattedValue.forEach(value => {
  226. addOptionToSelectControl(selectControl, value, value, column.filterDefault)
  227. })
  228. continue
  229. }
  230. // eslint-disable-next-line guard-for-in
  231. for (const key in uniqueValues) {
  232. addOptionToSelectControl(selectControl, uniqueValues[key], key, column.filterDefault)
  233. }
  234. }
  235. sortSelectControl(selectControl, column.filterOrderBy)
  236. if (that.options.hideUnusedSelectOptions) {
  237. hideUnusedSelectOptions(selectControl, uniqueValues)
  238. }
  239. }
  240. })
  241. }
  242. export function getFilterDataMethod (objFilterDataMethod, searchTerm) {
  243. const keys = Object.keys(objFilterDataMethod)
  244. for (let i = 0; i < keys.length; i++) {
  245. if (keys[i] === searchTerm) {
  246. return objFilterDataMethod[searchTerm]
  247. }
  248. }
  249. return null
  250. }
  251. export function createControls (that, header) {
  252. let addedFilterControl = false
  253. let html
  254. $.each(that.columns, (_, column) => {
  255. html = []
  256. if (!column.visible) {
  257. return
  258. }
  259. if (!column.filterControl && !that.options.filterControlContainer) {
  260. html.push('<div class="no-filter-control"></div>')
  261. } else if (that.options.filterControlContainer) {
  262. // Use a filter control container instead of th
  263. const $filterControls = $(`.bootstrap-table-filter-control-${column.field}`)
  264. $.each($filterControls, (_, filterControl) => {
  265. const $filterControl = $(filterControl)
  266. if (!$filterControl.is('[type=radio]')) {
  267. const placeholder = column.filterControlPlaceholder || ''
  268. $filterControl.attr('placeholder', placeholder).val(column.filterDefault)
  269. }
  270. $filterControl.attr('data-field', column.field)
  271. })
  272. addedFilterControl = true
  273. } else {
  274. // Create the control based on the html defined in the filterTemplate array.
  275. const nameControl = column.filterControl.toLowerCase()
  276. html.push('<div class="filter-control">')
  277. addedFilterControl = true
  278. if (column.searchable && that.options.filterTemplate[nameControl]) {
  279. html.push(
  280. that.options.filterTemplate[nameControl](
  281. that,
  282. column.field,
  283. column.filterControlPlaceholder ?
  284. column.filterControlPlaceholder :
  285. '',
  286. column.filterDefault
  287. )
  288. )
  289. }
  290. }
  291. // Filtering by default when it is set.
  292. if (column.filterControl && '' !== column.filterDefault && 'undefined' !== typeof column.filterDefault) {
  293. if ($.isEmptyObject(that.filterColumnsPartial)) {
  294. that.filterColumnsPartial = {}
  295. }
  296. that.filterColumnsPartial[column.field] = column.filterDefault
  297. }
  298. $.each(header.find('th'), (_, th) => {
  299. const $th = $(th)
  300. if ($th.data('field') === column.field) {
  301. $th.find('.fht-cell').append(html.join(''))
  302. return false
  303. }
  304. })
  305. if (column.filterData && column.filterData.toLowerCase() !== 'column') {
  306. const filterDataType = getFilterDataMethod(filterDataMethods, column.filterData.substring(0, column.filterData.indexOf(':')))
  307. let filterDataSource
  308. let selectControl
  309. if (filterDataType) {
  310. filterDataSource = column.filterData.substring(column.filterData.indexOf(':') + 1, column.filterData.length)
  311. selectControl = header.find(`.bootstrap-table-filter-control-${escapeID(column.field)}`)
  312. addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder, column.filterDefault)
  313. filterDataType(filterDataSource, selectControl, that.options.filterOrderBy, column.filterDefault)
  314. } else {
  315. throw new SyntaxError(
  316. 'Error. You should use any of these allowed filter data methods: var, obj, json, url, func.' +
  317. ' Use like this: var: {key: "value"}'
  318. )
  319. }
  320. }
  321. })
  322. if (addedFilterControl) {
  323. header.off('keyup', 'input').on('keyup', 'input', ({ currentTarget, keyCode }, obj) => {
  324. keyCode = obj ? obj.keyCode : keyCode
  325. if (that.options.searchOnEnterKey && keyCode !== 13) {
  326. return
  327. }
  328. if (isKeyAllowed(keyCode)) {
  329. return
  330. }
  331. const $currentTarget = $(currentTarget)
  332. if ($currentTarget.is(':checkbox') || $currentTarget.is(':radio')) {
  333. return
  334. }
  335. clearTimeout(currentTarget.timeoutId || 0)
  336. currentTarget.timeoutId = setTimeout(() => {
  337. that.onColumnSearch({ currentTarget, keyCode })
  338. }, that.options.searchTimeOut)
  339. })
  340. header.off('change', 'select:not(".ms-offscreen")').on('change', 'select:not(".ms-offscreen")', ({ currentTarget, keyCode }) => {
  341. const $selectControl = $(currentTarget)
  342. const value = $selectControl.val()
  343. if (value && value.length > 0 && value.trim()) {
  344. $selectControl.find('option[selected]').removeAttr('selected')
  345. $selectControl.find(`option[value="${ value }"]`).attr('selected', true)
  346. } else {
  347. $selectControl.find('option[selected]').removeAttr('selected')
  348. }
  349. clearTimeout(currentTarget.timeoutId || 0)
  350. currentTarget.timeoutId = setTimeout(() => {
  351. that.onColumnSearch({ currentTarget, keyCode })
  352. }, that.options.searchTimeOut)
  353. })
  354. header.off('mouseup', 'input:not([type=radio])').on('mouseup', 'input:not([type=radio])', ({ currentTarget, keyCode }) => {
  355. const $input = $(currentTarget)
  356. const oldValue = $input.val()
  357. if (oldValue === '') {
  358. return
  359. }
  360. setTimeout(() => {
  361. const newValue = $input.val()
  362. if (newValue === '') {
  363. clearTimeout(currentTarget.timeoutId || 0)
  364. currentTarget.timeoutId = setTimeout(() => {
  365. that.onColumnSearch({ currentTarget, keyCode })
  366. }, that.options.searchTimeOut)
  367. }
  368. }, 1)
  369. })
  370. header.off('change', 'input[type=radio]').on('change', 'input[type=radio]', ({ currentTarget, keyCode }) => {
  371. clearTimeout(currentTarget.timeoutId || 0)
  372. currentTarget.timeoutId = setTimeout(() => {
  373. that.onColumnSearch({ currentTarget, keyCode })
  374. }, that.options.searchTimeOut)
  375. })
  376. // See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date
  377. if (header.find('.date-filter-control').length > 0) {
  378. $.each(that.columns, (i, { filterDefault, filterControl, field, filterDatepickerOptions }) => {
  379. if (filterControl !== undefined && filterControl.toLowerCase() === 'datepicker') {
  380. const $datepicker = header.find(`.date-filter-control.bootstrap-table-filter-control-${field}`)
  381. if (filterDefault) {
  382. $datepicker.value(filterDefault)
  383. }
  384. if (filterDatepickerOptions.min) {
  385. $datepicker.attr('min', filterDatepickerOptions.min)
  386. }
  387. if (filterDatepickerOptions.max) {
  388. $datepicker.attr('max', filterDatepickerOptions.max)
  389. }
  390. if (filterDatepickerOptions.step) {
  391. $datepicker.attr('step', filterDatepickerOptions.step)
  392. }
  393. if (filterDatepickerOptions.pattern) {
  394. $datepicker.attr('pattern', filterDatepickerOptions.pattern)
  395. }
  396. $datepicker.on('change', ({ currentTarget }) => {
  397. clearTimeout(currentTarget.timeoutId || 0)
  398. currentTarget.timeoutId = setTimeout(() => {
  399. that.onColumnSearch({ currentTarget })
  400. }, that.options.searchTimeOut)
  401. })
  402. }
  403. })
  404. }
  405. if (that.options.sidePagination !== 'server') {
  406. that.triggerSearch()
  407. }
  408. if (!that.options.filterControlVisible) {
  409. header.find('.filter-control, .no-filter-control').hide()
  410. }
  411. } else {
  412. header.find('.filter-control, .no-filter-control').hide()
  413. }
  414. that.trigger('created-controls')
  415. }
  416. export function getDirectionOfSelectOptions (_alignment) {
  417. const alignment = _alignment === undefined ? 'left' : _alignment.toLowerCase()
  418. switch (alignment) {
  419. case 'left':
  420. return 'ltr'
  421. case 'right':
  422. return 'rtl'
  423. case 'auto':
  424. return 'auto'
  425. default:
  426. return 'ltr'
  427. }
  428. }
  429. export function syncHeaders (that) {
  430. if (!that.options.height) {
  431. return
  432. }
  433. const fixedHeader = $('.fixed-table-header table thead')
  434. if (fixedHeader.length === 0) {
  435. return
  436. }
  437. that.$header.children().find('th[data-field]').each((_, element) => {
  438. if (element.classList[0] !== 'bs-checkbox') {
  439. const $element = $(element)
  440. const $field = $element.data('field')
  441. const $fixedField = $(`th[data-field='${$field}']`).not($element)
  442. const input = $element.find('input')
  443. const fixedInput = $fixedField.find('input')
  444. if (input.length > 0 && fixedInput.length > 0) {
  445. if (input.val() !== fixedInput.val()) {
  446. input.val(fixedInput.val())
  447. }
  448. }
  449. }
  450. })
  451. }
  452. const filterDataMethods = {
  453. func (filterDataSource, selectControl, filterOrderBy, selected) {
  454. const variableValues = window[filterDataSource].apply()
  455. // eslint-disable-next-line guard-for-in
  456. for (const key in variableValues) {
  457. addOptionToSelectControl(selectControl, key, variableValues[key], selected)
  458. }
  459. sortSelectControl(selectControl, filterOrderBy)
  460. },
  461. obj (filterDataSource, selectControl, filterOrderBy, selected) {
  462. const objectKeys = filterDataSource.split('.')
  463. const variableName = objectKeys.shift()
  464. let variableValues = window[variableName]
  465. if (objectKeys.length > 0) {
  466. objectKeys.forEach(key => {
  467. variableValues = variableValues[key]
  468. })
  469. }
  470. // eslint-disable-next-line guard-for-in
  471. for (const key in variableValues) {
  472. addOptionToSelectControl(selectControl, key, variableValues[key], selected)
  473. }
  474. sortSelectControl(selectControl, filterOrderBy)
  475. },
  476. var (filterDataSource, selectControl, filterOrderBy, selected) {
  477. const variableValues = window[filterDataSource]
  478. const isArray = Array.isArray(variableValues)
  479. for (const key in variableValues) {
  480. if (isArray) {
  481. addOptionToSelectControl(selectControl, variableValues[key], variableValues[key], selected)
  482. } else {
  483. addOptionToSelectControl(selectControl, key, variableValues[key], selected)
  484. }
  485. }
  486. sortSelectControl(selectControl, filterOrderBy)
  487. },
  488. url (filterDataSource, selectControl, filterOrderBy, selected) {
  489. $.ajax({
  490. url: filterDataSource,
  491. dataType: 'json',
  492. success (data) {
  493. // eslint-disable-next-line guard-for-in
  494. for (const key in data) {
  495. addOptionToSelectControl(selectControl, key, data[key], selected)
  496. }
  497. sortSelectControl(selectControl, filterOrderBy)
  498. }
  499. })
  500. },
  501. json (filterDataSource, selectControl, filterOrderBy, selected) {
  502. const variableValues = JSON.parse(filterDataSource)
  503. // eslint-disable-next-line guard-for-in
  504. for (const key in variableValues) {
  505. addOptionToSelectControl(selectControl, key, variableValues[key], selected)
  506. }
  507. sortSelectControl(selectControl, filterOrderBy)
  508. }
  509. }