ソースを参照

Improve cookie extension and fix resetSearch

djhvscf 4 年 前
コミット
81d6251663

+ 1 - 1
src/bootstrap-table.js

@@ -3072,7 +3072,7 @@ class BootstrapTable {
     const $search = Utils.getSearchInput(this)
 
     $search.val(text || '')
-    this.onSearch({ currentTarget: $search })
+    this.onSearch({ currentTarget: $search }, false)
   }
 
   filterBy (columns, options) {

+ 92 - 92
src/extensions/cookie/bootstrap-table-cookie.js

@@ -51,39 +51,7 @@ const UtilsCookie = {
 
     cookieName = `${that.options.cookieIdTable}.${cookieName}`
 
-    switch (that.options.cookieStorage) {
-      case 'cookieStorage':
-        document.cookie = [
-          cookieName, '=', encodeURIComponent(cookieValue),
-          `; expires=${UtilsCookie.calculateExpiration(that.options.cookieExpire)}`,
-          that.options.cookiePath ? `; path=${that.options.cookiePath}` : '',
-          that.options.cookieDomain ? `; domain=${that.options.cookieDomain}` : '',
-          that.options.cookieSecure ? '; secure' : '',
-          `;SameSite=${ that.options.cookieSameSite}`
-        ].join('')
-        break
-      case 'localStorage':
-        localStorage.setItem(cookieName, cookieValue)
-        break
-      case 'sessionStorage':
-        sessionStorage.setItem(cookieName, cookieValue)
-        break
-      case 'customStorage':
-        if (
-          !that.options.cookieCustomStorageSet ||
-          !that.options.cookieCustomStorageGet ||
-          !that.options.cookieCustomStorageDelete
-        ) {
-          throw new Error('The following options must be set while using the customStorage: cookieCustomStorageSet, cookieCustomStorageGet and cookieCustomStorageDelete')
-        }
-
-        Utils.calculateObjectValue(that.options, that.options.cookieCustomStorageSet, [cookieName, cookieValue], '')
-        break
-      default:
-        return false
-    }
-
-    return true
+    return that._storage.setItem(cookieName, cookieValue)
   },
   getCookie (that, tableName, cookieName) {
     if (!cookieName) {
@@ -96,64 +64,12 @@ const UtilsCookie = {
 
     cookieName = `${tableName}.${cookieName}`
 
-    switch (that.options.cookieStorage) {
-      case 'cookieStorage':
-        const value = `; ${document.cookie}`
-        const parts = value.split(`; ${cookieName}=`)
-
-        return parts.length === 2 ? decodeURIComponent(parts.pop().split(';').shift()) : null
-      case 'localStorage':
-        return localStorage.getItem(cookieName)
-      case 'sessionStorage':
-        return sessionStorage.getItem(cookieName)
-      case 'customStorage':
-        if (
-          !that.options.cookieCustomStorageSet ||
-          !that.options.cookieCustomStorageGet ||
-          !that.options.cookieCustomStorageDelete
-        ) {
-          throw new Error('The following options must be set while using the customStorage: cookieCustomStorageSet, cookieCustomStorageGet and cookieCustomStorageDelete')
-        }
-
-        return Utils.calculateObjectValue(that.options, that.options.cookieCustomStorageGet, [cookieName], '')
-      default:
-        return null
-    }
+    return that._storage.getItem(cookieName)
   },
   deleteCookie (that, cookieName) {
     cookieName = `${that.options.cookieIdTable}.${cookieName}`
 
-    switch (that.options.cookieStorage) {
-      case 'cookieStorage':
-        document.cookie = [
-          encodeURIComponent(cookieName), '=',
-          '; expires=Thu, 01 Jan 1970 00:00:00 GMT',
-          that.options.cookiePath ? `; path=${that.options.cookiePath}` : '',
-          that.options.cookieDomain ? `; domain=${that.options.cookieDomain}` : '',
-          `;SameSite=${ that.options.cookieSameSite}`
-        ].join('')
-        break
-      case 'localStorage':
-        localStorage.removeItem(cookieName)
-        break
-      case 'sessionStorage':
-        sessionStorage.removeItem(cookieName)
-        break
-      case 'customStorage':
-        if (
-          !that.options.cookieCustomStorageSet ||
-          !that.options.cookieCustomStorageGet ||
-          !that.options.cookieCustomStorageDelete
-        ) {
-          throw new Error('The following options must be set while using the customStorage: cookieCustomStorageSet, cookieCustomStorageGet and cookieCustomStorageDelete')
-        }
-
-        Utils.calculateObjectValue(that.options, that.options.cookieCustomStorageDelete, [cookieName], '')
-        break
-      default:
-        return false
-    }
-    return true
+    return that._storage.removeItem(cookieName)
   },
   calculateExpiration (cookieExpire) {
     const time = cookieExpire.replace(/[0-9]*/, '') // s,mi,h,d,m,y
@@ -278,7 +194,12 @@ $.extend($.fn.bootstrapTable.defaults, {
   cookieCustomStorageDelete: null,
   // internal variable
   _filterControls: [],
-  _filterControlValuesLoaded: false
+  _filterControlValuesLoaded: false,
+  _storage: {
+    setItem: undefined,
+    getItem: undefined,
+    removeItem: undefined
+  }
 })
 
 $.fn.bootstrapTable.methods.push('getCookies')
@@ -295,6 +216,9 @@ $.BootstrapTable = class extends $.BootstrapTable {
       if (this.options.cookieStorage === 'cookieStorage' && !UtilsCookie.isCookieSupportedByBrowser()) {
         throw new Error('Cookies are not enabled in this browser.')
       }
+
+      this.configureStorage()
+
       // FilterBy logic
       const filterByCookieValue = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.filterBy)
 
@@ -364,9 +288,6 @@ $.BootstrapTable = class extends $.BootstrapTable {
 
   initTable (...args) {
     super.initTable(...args)
-    if (!this.options.cookie) {
-      return
-    }
     this.initCookie()
   }
 
@@ -445,7 +366,7 @@ $.BootstrapTable = class extends $.BootstrapTable {
   }
 
   onSearch (event) {
-    super.onSearch(event, false)
+    super.onSearch(event, arguments.length > 1 ? arguments[1] : true)
     if (!this.options.cookie) {
       return
     }
@@ -559,4 +480,83 @@ $.BootstrapTable = class extends $.BootstrapTable {
 
     UtilsCookie.deleteCookie(this, UtilsCookie.cookieIds[cookieName])
   }
+
+  configureStorage () {
+    const that = this
+
+    this._storage = {}
+    switch (this.options.cookieStorage) {
+      case 'cookieStorage':
+        this._storage.setItem = function (cookieName, cookieValue) {
+          document.cookie = [
+            cookieName, '=', encodeURIComponent(cookieValue),
+            `; expires=${UtilsCookie.calculateExpiration(that.options.cookieExpire)}`,
+            that.options.cookiePath ? `; path=${that.options.cookiePath}` : '',
+            that.options.cookieDomain ? `; domain=${that.options.cookieDomain}` : '',
+            that.options.cookieSecure ? '; secure' : '',
+            `;SameSite=${ that.options.cookieSameSite}`
+          ].join('')
+        }
+        this._storage.getItem = function (cookieName) {
+          const value = `; ${document.cookie}`
+          const parts = value.split(`; ${cookieName}=`)
+
+          return parts.length === 2 ? decodeURIComponent(parts.pop().split(';').shift()) : null
+        }
+        this._storage.removeItem = function (cookieName) {
+          document.cookie = [
+            encodeURIComponent(cookieName), '=',
+            '; expires=Thu, 01 Jan 1970 00:00:00 GMT',
+            that.options.cookiePath ? `; path=${that.options.cookiePath}` : '',
+            that.options.cookieDomain ? `; domain=${that.options.cookieDomain}` : '',
+            `;SameSite=${ that.options.cookieSameSite}`
+          ].join('')
+        }
+        break
+      case 'localStorage':
+        this._storage.setItem = function (cookieName, cookieValue) {
+          localStorage.setItem(cookieName, cookieValue)
+        }
+        this._storage.getItem = function (cookieName) {
+          return localStorage.getItem(cookieName)
+        }
+        this._storage.removeItem = function (cookieName) {
+          localStorage.removeItem(cookieName)
+        }
+        break
+      case 'sessionStorage':
+        this._storage.setItem = function (cookieName, cookieValue) {
+          sessionStorage.setItem(cookieName, cookieValue)
+        }
+        this._storage.getItem = function (cookieName) {
+          return sessionStorage.getItem(cookieName)
+        }
+        this._storage.removeItem = function (cookieName) {
+          sessionStorage.removeItem(cookieName)
+        }
+        break
+      case 'customStorage':
+        if (
+          !this.options.cookieCustomStorageSet ||
+          !this.options.cookieCustomStorageGet ||
+          !this.options.cookieCustomStorageDelete
+        ) {
+          throw new Error('The following options must be set while using the customStorage: cookieCustomStorageSet, cookieCustomStorageGet and cookieCustomStorageDelete')
+        }
+
+        this._storage.setItem = function (cookieName, cookieValue) {
+          Utils.calculateObjectValue(that.options, that.options.cookieCustomStorageSet, [cookieName, cookieValue], '')
+        }
+        this._storage.getItem = function (cookieName) {
+          return Utils.calculateObjectValue(that.options, that.options.cookieCustomStorageGet, [cookieName], '')
+        }
+        this._storage.removeItem = function (cookieName) {
+          Utils.calculateObjectValue(that.options, that.options.cookieCustomStorageDelete, [cookieName], '')
+        }
+
+        break
+      default:
+        throw new Error('Storage method not supported.')
+    }
+  }
 }

+ 19 - 20
src/extensions/filter-control/bootstrap-table-filter-control.js

@@ -22,7 +22,7 @@ $.extend($.fn.bootstrapTable.defaults, {
     input (that, column, placeholder, value) {
       return Utils.sprintf(
         '<input type="search" class="%s bootstrap-table-filter-control-%s search-input" style="width: 100%;" placeholder="%s" value="%s">',
-        UtilsFilterControl.GetFormControlClass(that.options),
+        UtilsFilterControl.getFormControlClass(that.options),
         column.field,
         'undefined' === typeof placeholder ? '' : placeholder,
         'undefined' === typeof value ? '' : value
@@ -32,7 +32,7 @@ $.extend($.fn.bootstrapTable.defaults, {
     select ({ options }, column) {
       return Utils.sprintf(
         '<select class="%s bootstrap-table-filter-control-%s %s" %s style="width: 100%;" dir="%s"></select>',
-        UtilsFilterControl.GetFormControlClass(options),
+        UtilsFilterControl.getFormControlClass(options),
         column.field,
         column.filterControlMultipleSelect ? 'fc-multipleselect' : '',
         column.filterControlMultipleSelectMultiple ? 'multiple="multiple"' : '',
@@ -45,7 +45,7 @@ $.extend($.fn.bootstrapTable.defaults, {
     datepicker (that, column, value) {
       return Utils.sprintf(
         '<input type="date" class="%s date-filter-control bootstrap-table-filter-control-%s" style="width: 100%;" value="%s">',
-        UtilsFilterControl.GetFormControlClass(that.options),
+        UtilsFilterControl.getFormControlClass(that.options),
         column.field,
         'undefined' === typeof value ? '' : value
       )
@@ -372,33 +372,31 @@ $.BootstrapTable = class extends $.BootstrapTable {
     }
 
     const that = this
-    const cookies = UtilsFilterControl.collectBootstrapCookies()
     const table = this.$el.closest('table')
     const controls = UtilsFilterControl.getSearchControls(that)
-    const search = Utils.getSearchInput(this)
+    // const search = Utils.getSearchInput(this)
     let hasValues = false
     let timeoutId = 0
 
+    // Clear cache values
     $.each(that._valuesFilterControl, (i, item) => {
       hasValues = hasValues ? true : item.value !== ''
       item.value = ''
     })
 
-    $.each(that.options.filterControls, (i, item) => {
-      item.text = ''
+    // Clear controls in UI
+    $.each(controls, (i, item) => {
+      item.value = ''
     })
 
+    // Cache controls again
     UtilsFilterControl.setValues(that)
 
-    // clear cookies once the filters are clean
+    // clear cookies once the filters are clean. Should clear only Filtercontrol cookie
     clearTimeout(timeoutId)
     timeoutId = setTimeout(() => {
-      if (cookies && cookies.length > 0) {
-        $.each(cookies, (i, item) => {
-          if (that.deleteCookie !== undefined) {
-            that.deleteCookie(item)
-          }
-        })
+      if (that.options.cookie) {
+        that.deleteCookie('filterControl')
       }
     }, that.options.searchTimeOut)
 
@@ -412,16 +410,17 @@ $.BootstrapTable = class extends $.BootstrapTable {
     // which ones are going to be present.
     if (controls.length > 0) {
       this.filterColumnsPartial = {}
-      $(controls[0]).trigger(
-        controls[0].tagName === 'INPUT' ? 'keyup' : 'change', { keyCode: 13 }
-      )
+      controls.eq(0).trigger(this.tagName === 'INPUT' ? 'keyup' : 'change', { keyCode: 13 })
+      /* controls.each(function () {
+        $(this).trigger(this.tagName === 'INPUT' ? 'keyup' : 'change', { keyCode: 13 })
+      })*/
     } else {
       return
     }
 
-    if (search.length > 0) {
-      that.resetSearch()
-    }
+    /* if (search.length > 0) {
+      that.resetSearch('fc')
+    }*/
 
     // use the default sort order if it exists. do nothing if it does not
     if (that.options.sortName !== table.data('sortName') || that.options.sortOrder !== table.data('sortOrder')) {

+ 5 - 40
src/extensions/filter-control/utils.js

@@ -2,7 +2,7 @@
 const Utils = $.fn.bootstrapTable.utils
 const searchControls = 'select, input:not([type="checkbox"]):not([type="radio"])'
 
-export function GetFormControlClass (options) {
+export function getFormControlClass (options) {
   return options.iconSize ? Utils.sprintf('form-control-%s', options.iconSize) : 'form-control'
 }
 
@@ -130,15 +130,14 @@ export function cacheValues (that) {
 
   searchControls.each(function () {
     let $field = $(this)
+    const fieldClass = getElementClass($field)
 
     if (that.options.height && !that.options.filterControlContainer) {
-      const fieldClass = getElementClass($field)
-
       $field = $(`.fixed-table-header .${fieldClass}`)
-    } else {
-      const fieldClass = getElementClass($field)
-
+    } else if (that.options.filterControlContainer) {
       $field = $(`${that.options.filterControlContainer} .${fieldClass}`)
+    } else {
+      $field = $(`.${fieldClass}`)
     }
 
     that._valuesFilterControl.push({
@@ -211,40 +210,6 @@ export function setValues (that) {
   }
 }
 
-export function collectBootstrapCookies () {
-  const cookies = []
-  const foundCookies = document.cookie.match(/(?:bs.table.)(\w*)/g)
-  const foundLocalStorage = localStorage
-
-  if (foundCookies) {
-    $.each(foundCookies, (i, _cookie) => {
-      let cookie = _cookie
-
-      if (/./.test(cookie)) {
-        cookie = cookie.split('.').pop()
-      }
-
-      if ($.inArray(cookie, cookies) === -1) {
-        cookies.push(cookie)
-      }
-    })
-  }
-  if (foundLocalStorage) {
-    for (let i = 0; i < foundLocalStorage.length; i++) {
-      let cookie = foundLocalStorage.key(i)
-
-      if (/./.test(cookie)) {
-        cookie = cookie.split('.').pop()
-      }
-
-      if (!cookies.includes(cookie)) {
-        cookies.push(cookie)
-      }
-    }
-  }
-  return cookies
-}
-
 export function escapeID (id) {
   // eslint-disable-next-line no-useless-escape
   return String(id).replace(/([:.\[\],])/g, '\\$1')