bootstrap-table-cookie.js 13 KB

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