utils.js 18 KB

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