bootstrap-table-cookie.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. /**
  2. * @author: Dennis Hernández
  3. * @webSite: http://djhvscf.github.io/Blog
  4. * @update zhixin wen <wenzhixin2010@gmail.com>
  5. */
  6. const Utils = $.fn.bootstrapTable.utils
  7. const UtilsCookie = {
  8. cookieIds: {
  9. sortOrder: 'bs.table.sortOrder',
  10. sortName: 'bs.table.sortName',
  11. pageNumber: 'bs.table.pageNumber',
  12. pageList: 'bs.table.pageList',
  13. columns: 'bs.table.columns',
  14. searchText: 'bs.table.searchText',
  15. reorderColumns: 'bs.table.reorderColumns',
  16. filterControl: 'bs.table.filterControl',
  17. filterBy: 'bs.table.filterBy'
  18. },
  19. getCurrentHeader (that) {
  20. let header = that.$header
  21. if (that.options.height) {
  22. header = that.$tableHeader
  23. }
  24. return header
  25. },
  26. getCurrentSearchControls (that) {
  27. let searchControls = 'select, input'
  28. if (that.options.height) {
  29. searchControls = 'table select, table input'
  30. }
  31. return searchControls
  32. },
  33. cookieEnabled () {
  34. return !!(navigator.cookieEnabled)
  35. },
  36. inArrayCookiesEnabled (cookieName, cookiesEnabled) {
  37. let index = -1
  38. for (let i = 0; i < cookiesEnabled.length; i++) {
  39. if (cookieName.toLowerCase() === cookiesEnabled[i].toLowerCase()) {
  40. index = i
  41. break
  42. }
  43. }
  44. return index
  45. },
  46. setCookie (that, cookieName, cookieValue) {
  47. if ((!that.options.cookie) || (!UtilsCookie.cookieEnabled()) || (that.options.cookieIdTable === '')) {
  48. return
  49. }
  50. if (UtilsCookie.inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
  51. return
  52. }
  53. cookieName = `${that.options.cookieIdTable}.${cookieName}`
  54. switch (that.options.cookieStorage) {
  55. case 'cookieStorage':
  56. document.cookie = [
  57. cookieName, '=', encodeURIComponent(cookieValue),
  58. `; expires=${UtilsCookie.calculateExpiration(that.options.cookieExpire)}`,
  59. that.options.cookiePath ? `; path=${that.options.cookiePath}` : '',
  60. that.options.cookieDomain ? `; domain=${that.options.cookieDomain}` : '',
  61. that.options.cookieSecure ? '; secure' : ''
  62. ].join('')
  63. break
  64. case 'localStorage':
  65. localStorage.setItem(cookieName, cookieValue)
  66. break
  67. case 'sessionStorage':
  68. sessionStorage.setItem(cookieName, cookieValue)
  69. break
  70. case 'customStorage':
  71. if (
  72. !that.options.cookieCustomStorageSet
  73. || !that.options.cookieCustomStorageGet
  74. || !that.options.cookieCustomStorageDelete
  75. ) {
  76. throw new Error('The following options must be set while using the customStorage: cookieCustomStorageSet, cookieCustomStorageGet and cookieCustomStorageDelete')
  77. }
  78. Utils.calculateObjectValue(that.options, that.options.cookieCustomStorageSet, [cookieName, cookieValue], '')
  79. break
  80. default:
  81. return false
  82. }
  83. return true
  84. },
  85. getCookie (that, tableName, cookieName) {
  86. if (!cookieName) {
  87. return null
  88. }
  89. if (UtilsCookie.inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
  90. return null
  91. }
  92. cookieName = `${tableName}.${cookieName}`
  93. switch (that.options.cookieStorage) {
  94. case 'cookieStorage':
  95. const value = `; ${document.cookie}`
  96. const parts = value.split(`; ${cookieName}=`)
  97. return parts.length === 2 ? decodeURIComponent(parts.pop().split(';').shift()) : null
  98. case 'localStorage':
  99. return localStorage.getItem(cookieName)
  100. case 'sessionStorage':
  101. return sessionStorage.getItem(cookieName)
  102. case 'customStorage':
  103. if (
  104. !that.options.cookieCustomStorageSet
  105. || !that.options.cookieCustomStorageGet
  106. || !that.options.cookieCustomStorageDelete
  107. ) {
  108. throw new Error('The following options must be set while using the customStorage: cookieCustomStorageSet, cookieCustomStorageGet and cookieCustomStorageDelete')
  109. }
  110. return Utils.calculateObjectValue(that.options, that.options.cookieCustomStorageGet, [cookieName], '')
  111. default:
  112. return null
  113. }
  114. },
  115. deleteCookie (that, tableName, cookieName) {
  116. cookieName = `${tableName}.${cookieName}`
  117. switch (that.options.cookieStorage) {
  118. case 'cookieStorage':
  119. document.cookie = [
  120. encodeURIComponent(cookieName), '=',
  121. '; expires=Thu, 01 Jan 1970 00:00:00 GMT',
  122. that.options.cookiePath ? `; path=${that.options.cookiePath}` : '',
  123. that.options.cookieDomain ? `; domain=${that.options.cookieDomain}` : ''
  124. ].join('')
  125. break
  126. case 'localStorage':
  127. localStorage.removeItem(cookieName)
  128. break
  129. case 'sessionStorage':
  130. sessionStorage.removeItem(cookieName)
  131. break
  132. case 'customStorage':
  133. if (
  134. !that.options.cookieCustomStorageSet
  135. || !that.options.cookieCustomStorageGet
  136. || !that.options.cookieCustomStorageDelete
  137. ) {
  138. throw new Error('The following options must be set while using the customStorage: cookieCustomStorageSet, cookieCustomStorageGet and cookieCustomStorageDelete')
  139. }
  140. Utils.calculateObjectValue(that.options, that.options.cookieCustomStorageDelete, [cookieName], '')
  141. break
  142. default:
  143. return false
  144. }
  145. return true
  146. },
  147. calculateExpiration (cookieExpire) {
  148. const time = cookieExpire.replace(/[0-9]*/, '') // s,mi,h,d,m,y
  149. cookieExpire = cookieExpire.replace(/[A-Za-z]{1,2}/, '') // number
  150. switch (time.toLowerCase()) {
  151. case 's':
  152. cookieExpire = +cookieExpire
  153. break
  154. case 'mi':
  155. cookieExpire *= 60
  156. break
  157. case 'h':
  158. cookieExpire = cookieExpire * 60 * 60
  159. break
  160. case 'd':
  161. cookieExpire = cookieExpire * 24 * 60 * 60
  162. break
  163. case 'm':
  164. cookieExpire = cookieExpire * 30 * 24 * 60 * 60
  165. break
  166. case 'y':
  167. cookieExpire = cookieExpire * 365 * 24 * 60 * 60
  168. break
  169. default:
  170. cookieExpire = undefined
  171. break
  172. }
  173. if (!cookieExpire) {
  174. return ''
  175. }
  176. const d = new Date()
  177. d.setTime(d.getTime() + cookieExpire * 1000)
  178. return d.toGMTString()
  179. },
  180. initCookieFilters (bootstrapTable) {
  181. setTimeout(() => {
  182. const parsedCookieFilters = JSON.parse(UtilsCookie.getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, UtilsCookie.cookieIds.filterControl))
  183. if (!bootstrapTable.options.filterControlValuesLoaded && parsedCookieFilters) {
  184. const cachedFilters = {}
  185. const header = UtilsCookie.getCurrentHeader(bootstrapTable)
  186. const searchControls = UtilsCookie.getCurrentSearchControls(bootstrapTable)
  187. const applyCookieFilters = (element, filteredCookies) => {
  188. filteredCookies.forEach(cookie => {
  189. if (cookie.text !== '' && element.tagName === 'INPUT') {
  190. element.value = cookie.text
  191. cachedFilters[cookie.field] = cookie.text
  192. } else if (cookie.text !== '' && element.tagName === 'SELECT' && bootstrapTable.options.filterControlContainer) {
  193. element.value = cookie.text
  194. cachedFilters[cookie.field] = cookie.text
  195. } else if (cookie.text !== '' && element.tagName === 'SELECT') {
  196. const option = document.createElement('option')
  197. option.value = cookie.text
  198. option.text = cookie.text
  199. element.add(option, element[1])
  200. element.selectedIndex = 1
  201. cachedFilters[cookie.field] = cookie.text
  202. }
  203. })
  204. }
  205. let filterContainer = header
  206. if (bootstrapTable.options.filterControlContainer) {
  207. filterContainer = $(`${bootstrapTable.options.filterControlContainer}`)
  208. }
  209. filterContainer.find(searchControls).each(function () {
  210. const field = $(this).closest('[data-field]').data('field')
  211. const filteredCookies = parsedCookieFilters.filter(cookie => cookie.field === field)
  212. applyCookieFilters(this, filteredCookies)
  213. })
  214. bootstrapTable.initColumnSearch(cachedFilters)
  215. bootstrapTable.options.filterControlValuesLoaded = true
  216. bootstrapTable.initServer()
  217. }
  218. }, 250)
  219. }
  220. }
  221. $.extend($.fn.bootstrapTable.defaults, {
  222. cookie: false,
  223. cookieExpire: '2h',
  224. cookiePath: null,
  225. cookieDomain: null,
  226. cookieSecure: null,
  227. cookieIdTable: '',
  228. cookiesEnabled: [
  229. 'bs.table.sortOrder', 'bs.table.sortName',
  230. 'bs.table.pageNumber', 'bs.table.pageList',
  231. 'bs.table.columns', 'bs.table.searchText',
  232. 'bs.table.filterControl', 'bs.table.filterBy',
  233. 'bs.table.reorderColumns'
  234. ],
  235. cookieStorage: 'cookieStorage', // localStorage, sessionStorage, customStorage
  236. cookieCustomStorageGet: null,
  237. cookieCustomStorageSet: null,
  238. cookieCustomStorageDelete: null,
  239. // internal variable
  240. filterControls: [],
  241. filterControlValuesLoaded: false
  242. })
  243. $.fn.bootstrapTable.methods.push('getCookies')
  244. $.fn.bootstrapTable.methods.push('deleteCookie')
  245. $.extend($.fn.bootstrapTable.utils, {
  246. setCookie: UtilsCookie.setCookie,
  247. getCookie: UtilsCookie.getCookie
  248. })
  249. $.BootstrapTable = class extends $.BootstrapTable {
  250. init () {
  251. if (this.options.cookie) {
  252. // FilterBy logic
  253. const filterByCookieValue = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.filterBy)
  254. if (typeof filterByCookieValue === 'boolean' && !filterByCookieValue) {
  255. throw new Error('The cookie value of filterBy must be a json!')
  256. }
  257. let filterByCookie = {}
  258. try {
  259. filterByCookie = JSON.parse(filterByCookieValue)
  260. } catch (e) {
  261. throw new Error('Could not parse the json of the filterBy cookie!')
  262. }
  263. this.filterColumns = filterByCookie ? filterByCookie : {}
  264. // FilterControl logic
  265. this.options.filterControls = []
  266. this.options.filterControlValuesLoaded = false
  267. this.options.cookiesEnabled = typeof this.options.cookiesEnabled === 'string' ?
  268. this.options.cookiesEnabled.replace('[', '').replace(']', '')
  269. .replace(/'/g, '').replace(/ /g, '').toLowerCase().split(',') :
  270. this.options.cookiesEnabled
  271. if (this.options.filterControl) {
  272. const that = this
  273. this.$el.on('column-search.bs.table', (e, field, text) => {
  274. let isNewField = true
  275. for (let i = 0; i < that.options.filterControls.length; i++) {
  276. if (that.options.filterControls[i].field === field) {
  277. that.options.filterControls[i].text = text
  278. isNewField = false
  279. break
  280. }
  281. }
  282. if (isNewField) {
  283. that.options.filterControls.push({
  284. field,
  285. text
  286. })
  287. }
  288. UtilsCookie.setCookie(that, UtilsCookie.cookieIds.filterControl, JSON.stringify(that.options.filterControls))
  289. }).on('created-controls.bs.table', UtilsCookie.initCookieFilters(that))
  290. }
  291. }
  292. super.init()
  293. }
  294. initServer (...args) {
  295. if (
  296. this.options.cookie &&
  297. this.options.filterControl &&
  298. !this.options.filterControlValuesLoaded
  299. ) {
  300. const cookie = JSON.parse(UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.filterControl))
  301. if (cookie) {
  302. return
  303. }
  304. }
  305. super.initServer(...args)
  306. }
  307. initTable (...args) {
  308. super.initTable(...args)
  309. this.initCookie()
  310. }
  311. onSort (...args) {
  312. super.onSort(...args)
  313. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.sortOrder, this.options.sortOrder)
  314. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.sortName, this.options.sortName)
  315. }
  316. onPageNumber (...args) {
  317. super.onPageNumber(...args)
  318. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber)
  319. }
  320. onPageListChange (...args) {
  321. super.onPageListChange(...args)
  322. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageList, this.options.pageSize)
  323. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber)
  324. }
  325. onPagePre (...args) {
  326. super.onPagePre(...args)
  327. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber)
  328. }
  329. onPageNext (...args) {
  330. super.onPageNext(...args)
  331. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber)
  332. }
  333. _toggleColumn (...args) {
  334. super._toggleColumn(...args)
  335. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.columns, JSON.stringify(this.getVisibleColumns()))
  336. }
  337. _toggleAllColumns (...args) {
  338. super._toggleAllColumns(...args)
  339. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.columns, JSON.stringify(this.getVisibleColumns()))
  340. }
  341. selectPage (page) {
  342. super.selectPage(page)
  343. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, page)
  344. }
  345. onSearch (event) {
  346. super.onSearch(event)
  347. if (this.options.search) {
  348. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.searchText, this.searchText)
  349. }
  350. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber)
  351. }
  352. initHeader (...args) {
  353. if (this.options.reorderableColumns) {
  354. this.columnsSortOrder = JSON.parse(UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.reorderColumns))
  355. }
  356. super.initHeader(...args)
  357. }
  358. persistReorderColumnsState (that) {
  359. UtilsCookie.setCookie(that, UtilsCookie.cookieIds.reorderColumns, JSON.stringify(that.columnsSortOrder))
  360. }
  361. filterBy (...args) {
  362. super.filterBy(...args)
  363. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.filterBy, JSON.stringify(this.filterColumns))
  364. }
  365. initCookie () {
  366. if (!this.options.cookie) {
  367. return
  368. }
  369. if ((this.options.cookieIdTable === '') || (this.options.cookieExpire === '') || (!UtilsCookie.cookieEnabled())) {
  370. console.error('Configuration error. Please review the cookieIdTable and the cookieExpire property. If the properties are correct, then this browser does not support cookies.')
  371. this.options.cookie = false // Make sure that the cookie extension is disabled
  372. return
  373. }
  374. const sortOrderCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.sortOrder)
  375. const sortOrderNameCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.sortName)
  376. const pageNumberCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.pageNumber)
  377. const pageListCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.pageList)
  378. const searchTextCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.searchText)
  379. const columnsCookieValue = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.columns)
  380. if (typeof columnsCookieValue === 'boolean' && !columnsCookieValue) {
  381. throw new Error('The cookie value of filterBy must be a json!')
  382. }
  383. let columnsCookie = {}
  384. try {
  385. columnsCookie = JSON.parse(columnsCookieValue)
  386. } catch (e) {
  387. throw new Error('Could not parse the json of the columns cookie!', columnsCookieValue)
  388. }
  389. // sortOrder
  390. this.options.sortOrder = sortOrderCookie ? sortOrderCookie : this.options.sortOrder
  391. // sortName
  392. this.options.sortName = sortOrderNameCookie ? sortOrderNameCookie : this.options.sortName
  393. // pageNumber
  394. this.options.pageNumber = pageNumberCookie ? +pageNumberCookie : this.options.pageNumber
  395. // pageSize
  396. this.options.pageSize = pageListCookie ? pageListCookie === this.options.formatAllRows() ? pageListCookie : +pageListCookie : this.options.pageSize
  397. // searchText
  398. this.options.searchText = searchTextCookie ? searchTextCookie : ''
  399. if (columnsCookie) {
  400. for (const column of this.columns) {
  401. column.visible = columnsCookie.filter((c) => { return c.field === column.field }).length > 0 || !column.switchable
  402. }
  403. }
  404. }
  405. getCookies () {
  406. const bootstrapTable = this
  407. const cookies = {}
  408. $.each(UtilsCookie.cookieIds, (key, value) => {
  409. cookies[key] = UtilsCookie.getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, value)
  410. if (key === 'columns') {
  411. cookies[key] = JSON.parse(cookies[key])
  412. }
  413. })
  414. return cookies
  415. }
  416. deleteCookie (cookieName) {
  417. if ((cookieName === '') || (!UtilsCookie.cookieEnabled())) {
  418. return
  419. }
  420. UtilsCookie.deleteCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds[cookieName])
  421. }
  422. }