utils.js 20 KB

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