Browse Source

Merge pull request #4094 from wenzhixin/Filter-Control_Cookies_Improves

Filter control cookies improvements
文翼 7 years ago
parent
commit
5f32b5b70a

+ 1 - 1
.eslintrc.js

@@ -63,7 +63,7 @@ module.exports = {
     'arrow-spacing': ['error', { 'before': true, 'after': true }],
     'no-useless-constructor': 'warn',
     'comma-dangle': ['error', 'never'],
-    'no-param-reassign': 'warn',
+    'no-param-reassign': 'off',
     "space-before-function-paren": ["error", "always"]
   },
   'globals': {

+ 21 - 0
docs/_i18n/en/documentation/table-options.md

@@ -531,6 +531,27 @@ The table options are defined in `jQuery.fn.bootstrapTable.defaults`.
     <td>Indicate the icon or text to be shown in the pagination detail, the next button.</td>
   </tr>
   <tr>
+      <td>paginationSuccessivelySize</td>
+      <td>data-pagination-successively-size</td>
+      <td>Number</td>
+      <td>5</td>
+      <td>Maximum successive number of pages in a row.</td>
+  </tr>
+  <tr>
+      <td>paginationPagesBySide</td>
+      <td>data-pagination-pages-by-side</td>
+      <td>Number</td>
+      <td>1</td>
+      <td>The number of pages on each side (right, left) of the current page.</td>
+  </tr>
+   <tr>
+      <td>paginationUseIntermediate</td>
+      <td>data-pagination-use-intermediate</td>
+      <td>Boolean</td>
+      <td>false</td>
+      <td>Calculate and show intermediate pages for quick access</td>
+  </tr>
+  <tr>
     <td>clickToSelect</td>
     <td>data-click-to-select</td>
     <td>Boolean</td>

+ 21 - 0
docs/_i18n/es/documentation/table-options.md

@@ -449,6 +449,27 @@ Las opciones de la tabla están definidas en `jQuery.fn.bootstrapTable.defaults`
     <td>'&gt;'</td>
     <td>Indica el icono o el texto a mostrar en la paginación, el botón next del detalle de la paginación.</td>
   </tr>
+    <tr>
+      <td>paginationSuccessivelySize</td>
+      <td>data-pagination-successively-size</td>
+      <td>Number</td>
+      <td>5</td>
+      <td>Número máximo sucesivo de páginas en una fila.</td>
+  </tr>
+  <tr>
+      <td>paginationPagesBySide</td>
+      <td>data-pagination-pages-by-side</td>
+      <td>Number</td>
+      <td>1</td>
+      <td>Número de páginas en cada lado (derecha, izquierda) de la página actual.</td>
+  </tr>
+   <tr>
+      <td>paginationUseIntermediate</td>
+      <td>data-pagination-use-intermediate</td>
+      <td>Boolean</td>
+      <td>false</td>
+      <td>Calcula y muestra páginas intermedias para un acceso rápido.</td>
+  </tr>
   <tr>
     <td>clickToSelect</td>
     <td>data-click-to-select</td>

+ 21 - 0
docs/_i18n/zh-cn/documentation/table-options.md

@@ -476,6 +476,27 @@
     <td>'&gt;'</td>
     <td>指定分页条中下一页按钮的图标或文字。</td>
   </tr>
+    <tr>
+      <td>paginationSuccessivelySize</td>
+      <td>data-pagination-successively-size</td>
+      <td>Number</td>
+      <td>5</td>
+      <td>连续的最大连续页数。</td>
+  </tr>
+  <tr>
+      <td>paginationPagesBySide</td>
+      <td>data-pagination-pages-by-side</td>
+      <td>Number</td>
+      <td>1</td>
+      <td>当前页面每侧(右侧,左侧)的页数。</td>
+  </tr>
+   <tr>
+      <td>paginationUseIntermediate</td>
+      <td>data-pagination-use-intermediate</td>
+      <td>Boolean</td>
+      <td>false</td>
+      <td>计算并显示中间页面以便快速访问。</td>
+  </tr>
   <tr>
     <td>clickToSelect</td>
     <td>data-click-to-select</td>

+ 1 - 1
package.json

@@ -19,7 +19,7 @@
   },
   "scripts": {
     "postinstall": "opencollective postinstall || exit 0",
-    "lint": "eslint src/bootstrap-table.js src/locale src/extensions/export src/extensions/editable src/extensions/toolbar src/extension/filter-control",
+    "lint": "eslint src/bootstrap-table.js src/locale src/extensions/export src/extensions/editable src/extensions/toolbar src/extension/filter-control src/extensions/cookie",
     "js:build:min": "NODE_ENV=production babel src -d dist -q && find dist -name '*.js' | sed -e 'p;s/.js/.min.js/' | xargs -n2 mv",
     "js:build:base": "babel src -d dist -q",
     "js:build:concat": "babel src/locale -o dist/bootstrap-table-locale-all.js && NODE_ENV=production babel src/locale -o dist/bootstrap-table-locale-all.min.js",

+ 12 - 0
src/bootstrap-table.css

@@ -157,6 +157,18 @@
     line-height: 1.428571429;
 }
 
+.fixed-table-pagination ul.pagination li.page-intermediate a {
+    color:#c8c8c8;
+}
+
+.fixed-table-pagination ul.pagination li.page-intermediate a:before {
+    content: '\2B05';
+}
+
+.fixed-table-pagination ul.pagination li.page-intermediate a:after {
+    content: '\27A1';
+}
+
 .fixed-table-pagination .pagination-info {
     line-height: 34px;
     margin-right: 5px;

+ 72 - 56
src/bootstrap-table.js

@@ -316,6 +316,9 @@
     paginationDetailHAlign: 'left', // right, left
     paginationPreText: '&lsaquo;',
     paginationNextText: '&rsaquo;',
+    paginationSuccessivelySize: 5, // Maximum successively number of pages in a row
+    paginationPagesBySide: 1, // Number of pages on each side (right, left) of the current page.
+    paginationUseIntermediate: false, // Calculate intermediate pages for quick access
     search: false,
     searchOnEnterKey: false,
     strictSearch: false,
@@ -1449,83 +1452,96 @@
           Utils.sprintf('<li class="page-item page-pre"><a class="page-link" href="#">%s</a></li>',
             this.options.paginationPreText))
 
-        if (this.totalPages < 5) {
+        if (this.totalPages < this.options.paginationSuccessivelySize) {
           from = 1
           to = this.totalPages
         } else {
-          from = this.options.pageNumber - 2
-          to = from + 4
-          if (from < 1) {
-            from = 1
-            to = 5
-          }
-          if (to > this.totalPages) {
-            to = this.totalPages
-            from = to - 4
-          }
+          from = this.options.pageNumber - this.options.paginationPagesBySide
+          to = from + (this.options.paginationPagesBySide * 2)
         }
 
-        if (this.totalPages >= 6) {
-          if (this.options.pageNumber >= 3) {
-            html.push(
-              Utils.sprintf('<li class="page-item page-first%s">',
-                this.options.pageNumber === 1 ? ' active' : ''),
-              '<a class="page-link" href="#">', 1, '</a>',
-              '</li>')
+        if (this.options.pageNumber < (this.options.paginationSuccessivelySize - 1)) {
+          to = this.options.paginationSuccessivelySize
+        }
 
-            from++
-          }
+        if (to > this.totalPages) {
+          to = this.totalPages
+        }
 
-          if (this.options.pageNumber >= 4) {
-            if (this.options.pageNumber === 4 || this.totalPages === 6 || this.totalPages === 7) {
-              from--
-            } else {
-              html.push('<li class="page-item page-first-separator disabled">',
-                '<a class="page-link" href="#">...</a>',
-                '</li>')
-            }
+        if (this.options.paginationSuccessivelySize > this.totalPages - from) {
+          from = from - (this.options.paginationSuccessivelySize - (this.totalPages - from)) + 1
+        }
 
-            to--
-          }
+        if (from < 1) {
+          from = 1
         }
 
-        if (this.totalPages >= 7) {
-          if (this.options.pageNumber >= (this.totalPages - 2)) {
-            from--
-          }
+        if (to > this.totalPages) {
+          to = this.totalPages
         }
 
-        if (this.totalPages === 6) {
-          if (this.options.pageNumber >= (this.totalPages - 2)) {
-            to++
+        if (from > 1) {
+          var max = this.options.paginationPagesBySide
+          if (max >= from) max = from - 1
+          for (i = 1; i <= max; i++) {
+            html.push('<li data-page-number="' + i + '" class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
+              '<a href="javascript:void(0)">', i, '</a>',
+              '</li>')
           }
-        } else if (this.totalPages >= 7) {
-          if (this.totalPages === 7 || this.options.pageNumber >= (this.totalPages - 3)) {
-            to++
+          if ((from - 1) === max + 1) {
+            i = from - 1
+            html.push('<li data-page-number="' + i + '" class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
+              '<a href="javascript:void(0)">', i, '</a>',
+              '</li>')
+          } else {
+            if ((from - 1) > max) {
+              if (((from - 10) > 5) && (this.options.paginationUseIntermediate)) {
+                i = Math.round(((from - 3) / 2) + 3)
+                html.push('<li data-page-number="' + i + '" class="page-intermediate page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
+                  '<a href="javascript:void(0)">', i, '</a>',
+                  '</li>')
+              } else {
+                html.push('<li class="page-first-separator disabled">',
+                  '<a href="javascript:void(0)">&#8230;</a>',
+                  '</li>')
+              }
+            }
           }
         }
 
         for (i = from; i <= to; i++) {
-          html.push(Utils.sprintf('<li class="page-item%s">',
-            i === this.options.pageNumber ? ' active' : ''),
-          '<a class="page-link" href="#">', i, '</a>',
-          '</li>')
+          html.push('<li data-page-number="' + i + '" class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
+            '<a href="javascript:void(0)">', i, '</a>',
+            '</li>')
         }
 
-        if (this.totalPages >= 8) {
-          if (this.options.pageNumber <= (this.totalPages - 4)) {
-            html.push('<li class="page-item page-last-separator disabled">',
-              '<a class="page-link" href="#">...</a>',
+        if (this.totalPages > to) {
+          var min = this.totalPages - (this.options.paginationPagesBySide - 1)
+          if (to >= min) min = to + 1
+          if ((to + 1) === min - 1) {
+            i = to + 1
+            html.push('<li data-page-number="' + i + '" class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
+              '<a href="javascript:void(0)">', i, '</a>',
               '</li>')
+          } else {
+            if (min > (to + 1)) {
+              if (((this.totalPages - to) > 10) && (this.options.paginationUseIntermediate)) {
+                i = Math.round(((this.totalPages - 3 - to) / 2) + to)
+                html.push('<li data-page-number="' + i + '" class="page-intermediate page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
+                  '<a href="javascript:void(0)">', i, '</a>',
+                  '</li>')
+              } else {
+                html.push('<li class="page-first-separator disabled">',
+                  '<a href="javascript:void(0)">&#8230;</a>',
+                  '</li>')
+              }
+            }
           }
-        }
 
-        if (this.totalPages >= 6) {
-          if (this.options.pageNumber <= (this.totalPages - 3)) {
-            html.push(Utils.sprintf('<li class="page-item page-last%s">',
-              this.totalPages === this.options.pageNumber ? ' active' : ''),
-            '<a class="page-link" href="#">', this.totalPages, '</a>',
-            '</li>')
+          for (i = min; i <= this.totalPages; i++) {
+            html.push('<li data-page-number="' + i + '" class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
+              '<a href="javascript:void(0)">', i, '</a>',
+              '</li>')
           }
         }
 
@@ -1541,7 +1557,7 @@
         $pageList = this.$pagination.find('.page-list a')
         $pre = this.$pagination.find('.page-pre')
         $next = this.$pagination.find('.page-next')
-        $number = this.$pagination.find('.page-item').not('.page-next, .page-pre')
+        $number = this.$pagination.find('.page-number, .page-item').not('.page-next, .page-pre')
 
         if (this.options.smartDisplay) {
           if (this.totalPages <= 1) {

+ 396 - 397
src/extensions/cookie/bootstrap-table-cookie.js

@@ -1,413 +1,412 @@
 /**
  * @author: Dennis Hernández
  * @webSite: http://djhvscf.github.io/Blog
- * @version: v1.2.3
+ * @version: v1.2.4
  *
  * @update zhixin wen <wenzhixin2010@gmail.com>
  */
 
-(function ($) {
-    'use strict';
-
-    var cookieIds = {
-        sortOrder: 'bs.table.sortOrder',
-        sortName: 'bs.table.sortName',
-        pageNumber: 'bs.table.pageNumber',
-        pageList: 'bs.table.pageList',
-        columns: 'bs.table.columns',
-        searchText: 'bs.table.searchText',
-        filterControl: 'bs.table.filterControl'
-    };
-
-    var getCurrentHeader = function (that) {
-        var header = that.$header;
-        if (that.options.height) {
-            header = that.$tableHeader;
+($ => {
+  const UtilsCookie = {
+    cookieIds: {
+      sortOrder: 'bs.table.sortOrder',
+      sortName: 'bs.table.sortName',
+      pageNumber: 'bs.table.pageNumber',
+      pageList: 'bs.table.pageList',
+      columns: 'bs.table.columns',
+      searchText: 'bs.table.searchText',
+      filterControl: 'bs.table.filterControl',
+      filterBy: 'bs.table.filterBy'
+    },
+    getCurrentHeader (that) {
+      let header = that.$header
+      if (that.options.height) {
+        header = that.$tableHeader
+      }
+
+      return header
+    },
+    getCurrentSearchControls (that) {
+      let searchControls = 'select, input'
+      if (that.options.height) {
+        searchControls = 'table select, table input'
+      }
+
+      return searchControls
+    },
+    cookieEnabled () {
+      return !!(navigator.cookieEnabled)
+    },
+    inArrayCookiesEnabled (cookieName, cookiesEnabled) {
+      let index = -1
+
+      for (let i = 0; i < cookiesEnabled.length; i++) {
+        if (cookieName.toLowerCase() === cookiesEnabled[i].toLowerCase()) {
+          index = i
+          break
         }
-
-        return header;
-    };
-
-    var getCurrentSearchControls = function (that) {
-        var searchControls = 'select, input';
-        if (that.options.height) {
-            searchControls = 'table select, table input';
+      }
+
+      return index
+    },
+    setCookie (that, cookieName, cookieValue) {
+      if ((!that.options.cookie) || (!UtilsCookie.cookieEnabled()) || (that.options.cookieIdTable === '')) {
+        return
+      }
+
+      if (UtilsCookie.inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
+        return
+      }
+
+      cookieName = that.options.cookieIdTable + '.' + cookieName
+
+      switch (that.options.cookieStorage) {
+        case 'cookieStorage':
+          document.cookie = [
+            cookieName, '=', 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' : ''
+          ].join('')
+          break
+        case 'localStorage':
+          localStorage.setItem(cookieName, cookieValue)
+          break
+        case 'sessionStorage':
+          sessionStorage.setItem(cookieName, cookieValue)
+          break
+        default:
+          return false
+      }
+
+      return true
+    },
+    getCookie (that, tableName, cookieName) {
+      if (!cookieName) {
+        return null
+      }
+
+      if (UtilsCookie.inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
+        return null
+      }
+
+      cookieName = tableName + '.' + cookieName
+
+      switch (that.options.cookieStorage) {
+        case 'cookieStorage':
+          const value = '; ' + document.cookie
+          const parts = value.split('; ' + cookieName + '=')
+          return parts.length === 2 ? parts.pop().split(';').shift() : null
+        case 'localStorage':
+          return localStorage.getItem(cookieName)
+        case 'sessionStorage':
+          return sessionStorage.getItem(cookieName)
+        default:
+          return null
+      }
+    },
+    deleteCookie (that, tableName, cookieName) {
+      cookieName = tableName + '.' + 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 : ''
+          ].join('')
+          break
+        case 'localStorage':
+          localStorage.removeItem(cookieName)
+          break
+        case 'sessionStorage':
+          sessionStorage.removeItem(cookieName)
+          break
+        default:
+          return false
+      }
+      return true
+    },
+    calculateExpiration (cookieExpire) {
+      const time = cookieExpire.replace(/[0-9]*/, '') // s,mi,h,d,m,y
+      cookieExpire = cookieExpire.replace(/[A-Za-z]{1,2}/, '') // number
+
+      switch (time.toLowerCase()) {
+        case 's':
+          cookieExpire = +cookieExpire
+          break
+        case 'mi':
+          cookieExpire *= 60
+          break
+        case 'h':
+          cookieExpire = cookieExpire * 60 * 60
+          break
+        case 'd':
+          cookieExpire = cookieExpire * 24 * 60 * 60
+          break
+        case 'm':
+          cookieExpire = cookieExpire * 30 * 24 * 60 * 60
+          break
+        case 'y':
+          cookieExpire = cookieExpire * 365 * 24 * 60 * 60
+          break
+        default:
+          cookieExpire = undefined
+          break
+      }
+      if (!cookieExpire) {
+        return ''
+      }
+      const d = new Date()
+      d.setTime(d.getTime() + cookieExpire * 1000)
+      return d.toGMTString()
+    },
+    initCookieFilters (bootstrapTable) {
+      setTimeout(function () {
+        const parsedCookieFilters = JSON.parse(UtilsCookie.getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, UtilsCookie.cookieIds.filterControl))
+
+        if (!bootstrapTable.options.filterControlValuesLoaded && parsedCookieFilters) {
+
+          const cachedFilters = {}
+          const header = UtilsCookie.getCurrentHeader(bootstrapTable)
+          const searchControls = UtilsCookie.getCurrentSearchControls(bootstrapTable)
+
+          const applyCookieFilters = function (element, filteredCookies) {
+            $(filteredCookies).each(function (i, cookie) {
+              if (cookie.text !== '') {
+                $(element).val(cookie.text)
+                cachedFilters[cookie.field] = cookie.text
+              }
+            })
+          }
+
+          header.find(searchControls).each(function () {
+            const field = $(this).closest('[data-field]').data('field')
+            const filteredCookies = $.grep(parsedCookieFilters, function (cookie) {
+              return cookie.field === field
+            })
+
+            applyCookieFilters(this, filteredCookies)
+          })
+
+          bootstrapTable.initColumnSearch(cachedFilters)
+          bootstrapTable.options.filterControlValuesLoaded = true
+          bootstrapTable.initServer()
         }
-
-        return searchControls;
-    };
-
-    var cookieEnabled = function () {
-        return !!(navigator.cookieEnabled);
-    };
-
-    var inArrayCookiesEnabled = function (cookieName, cookiesEnabled) {
-        var index = -1;
-
-        for (var i = 0; i < cookiesEnabled.length; i++) {
-            if (cookieName.toLowerCase() === cookiesEnabled[i].toLowerCase()) {
-                index = i;
-                break;
+      }, 250)
+    }
+  }
+
+  $.extend($.fn.bootstrapTable.defaults, {
+    cookie: false,
+    cookieExpire: '2h',
+    cookiePath: null,
+    cookieDomain: null,
+    cookieSecure: null,
+    cookieIdTable: '',
+    cookiesEnabled: [
+      'bs.table.sortOrder', 'bs.table.sortName',
+      'bs.table.pageNumber', 'bs.table.pageList',
+      'bs.table.columns', 'bs.table.searchText',
+      'bs.table.filterControl', 'bs.table.filterBy'
+    ],
+    cookieStorage: 'cookieStorage', // localStorage, sessionStorage
+    // internal variable
+    filterControls: [],
+    filterControlValuesLoaded: false
+  })
+
+  $.fn.bootstrapTable.methods.push('getCookies')
+  $.fn.bootstrapTable.methods.push('deleteCookie')
+
+  $.extend($.fn.bootstrapTable.utils, {
+    setCookie: UtilsCookie.setCookie,
+    getCookie: UtilsCookie.getCookie
+  })
+
+  $.BootstrapTable = class extends $.BootstrapTable {
+    init () {
+      // FilterBy logic
+      const filterByCookie = JSON.parse(UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.filterBy))
+      this.filterColumns = filterByCookie ? filterByCookie : {}
+
+      // FilterControl logic
+      this.options.filterControls = []
+      this.options.filterControlValuesLoaded = false
+
+      this.options.cookiesEnabled = typeof this.options.cookiesEnabled === 'string' ?
+        this.options.cookiesEnabled.replace('[', '').replace(']', '')
+          .replace(/ /g, '').toLowerCase().split(',') :
+        this.options.cookiesEnabled
+
+      if (this.options.filterControl) {
+        const that = this
+        this.$el.on('column-search.bs.table', function (e, field, text) {
+          let isNewField = true
+
+          for (let i = 0; i < that.options.filterControls.length; i++) {
+            if (that.options.filterControls[i].field === field) {
+              that.options.filterControls[i].text = text
+              isNewField = false
+              break
             }
+          }
+          if (isNewField) {
+            that.options.filterControls.push({
+              field: field,
+              text: text
+            })
+          }
+
+          UtilsCookie.setCookie(that, UtilsCookie.cookieIds.filterControl, JSON.stringify(that.options.filterControls))
+        }).on('created-controls.bs.table', UtilsCookie.initCookieFilters(that))
+      }
+      super.init()
+    }
+
+    initServer () {
+      const bootstrapTable = this
+      if (bootstrapTable.options.cookie && bootstrapTable.options.filterControl && !bootstrapTable.options.filterControlValuesLoaded) {
+        const cookie = JSON.parse(UtilsCookie.getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, UtilsCookie.cookieIds.filterControl))
+        if (cookie) {
+          return
         }
-
-        return index;
-    };
-
-    var setCookie = function (that, cookieName, cookieValue) {
-        if ((!that.options.cookie) || (!cookieEnabled()) || (that.options.cookieIdTable === '')) {
-            return;
-        }
-
-        if (inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
-            return;
-        }
-
-        cookieName = that.options.cookieIdTable + '.' + cookieName;
-
-        switch(that.options.cookieStorage) {
-            case 'cookieStorage':
-                document.cookie = [
-                    cookieName, '=', cookieValue,
-                    '; expires=' + calculateExpiration(that.options.cookieExpire),
-                    that.options.cookiePath ? '; path=' + that.options.cookiePath : '',
-                    that.options.cookieDomain ? '; domain=' + that.options.cookieDomain : '',
-                    that.options.cookieSecure ? '; secure' : ''
-                ].join('');
-            case 'localStorage':
-                localStorage.setItem(cookieName, cookieValue);
-                break;
-            case 'sessionStorage':
-                sessionStorage.setItem(cookieName, cookieValue);
-                break;
-            default:
-                return false;
-        }
-
-        return true;
-    };
-
-    var getCookie = function (that, tableName, cookieName) {
-        if (!cookieName) {
-            return null;
-        }
-
-        if (inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
-            return null;
-        }
-
-        cookieName = tableName + '.' + cookieName;
-
-        switch(that.options.cookieStorage) {
-            case 'cookieStorage':
-                var value = '; ' + document.cookie;
-                var parts = value.split('; ' + cookieName + '=');
-                return parts.length === 2 ? parts.pop().split(';').shift() : null;
-            case 'localStorage':
-                return localStorage.getItem(cookieName);
-            case 'sessionStorage':
-                return sessionStorage.getItem(cookieName);
-            default:
-                return null;
-        }
-    };
-
-    var deleteCookie = function (that, tableName, cookieName) {
-        cookieName = tableName + '.' + 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 : '',
-                ].join('');
-                break;
-            case 'localStorage':
-                localStorage.removeItem(cookieName);
-                break;
-            case 'sessionStorage':
-                sessionStorage.removeItem(cookieName);
-                break;
-
-        }
-        return true;
-    };
-
-    var calculateExpiration = function(cookieExpire) {
-        var time = cookieExpire.replace(/[0-9]*/, ''); //s,mi,h,d,m,y
-        cookieExpire = cookieExpire.replace(/[A-Za-z]{1,2}/, ''); //number
-
-        switch (time.toLowerCase()) {
-            case 's':
-                cookieExpire = +cookieExpire;
-                break;
-            case 'mi':
-                cookieExpire = cookieExpire * 60;
-                break;
-            case 'h':
-                cookieExpire = cookieExpire * 60 * 60;
-                break;
-            case 'd':
-                cookieExpire = cookieExpire * 24 * 60 * 60;
-                break;
-            case 'm':
-                cookieExpire = cookieExpire * 30 * 24 * 60 * 60;
-                break;
-            case 'y':
-                cookieExpire = cookieExpire * 365 * 24 * 60 * 60;
-                break;
-            default:
-                cookieExpire = undefined;
-                break;
+      }
+      super.initServer()
+    }
+
+    initTable () {
+      super.initTable()
+      this.initCookie()
+    }
+
+    onSort () {
+      const event = arguments[0]
+      super.onSort(event)
+      UtilsCookie.setCookie(this, UtilsCookie.cookieIds.sortOrder, this.options.sortOrder)
+      UtilsCookie.setCookie(this, UtilsCookie.cookieIds.sortName, this.options.sortName)
+    }
+
+    onPageNumber () {
+      const event = arguments[0]
+      super.onPageNumber(event)
+      UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber)
+      return false
+    }
+
+    onPageListChange () {
+      const event = arguments[0]
+      super.onPageListChange(event)
+      UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageList, this.options.pageSize)
+      UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber)
+      return false
+    }
+
+    onPagePre () {
+      const event = arguments[0]
+      super.onPagePre(event)
+      UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber)
+      return false
+    }
+
+    onPageNext () {
+      const event = arguments[0]
+      super.onPageNext(event)
+      UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber)
+      return false
+    }
+
+    toggleColumn () {
+      super.toggleColumn()
+
+      const visibleColumns = []
+
+      $.each(this.columns, function (i, column) {
+        if (column.visible) {
+          visibleColumns.push(column.field)
         }
-        if (!cookieExpire) {
-            return '';
-        }
-        var d = new Date();
-        d.setTime(d.getTime() + cookieExpire * 1000);
-        return d.toGMTString();
-    };
-
-    var initCookieFilters = function (bootstrapTable) {
-        setTimeout(function () {
-            var parsedCookieFilters = JSON.parse(getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, cookieIds.filterControl));
-
-            if (!bootstrapTable.options.filterControlValuesLoaded && parsedCookieFilters) {
-
-                var cachedFilters = {},
-                    header = getCurrentHeader(bootstrapTable),
-                    searchControls = getCurrentSearchControls(bootstrapTable),
-
-                    applyCookieFilters = function (element, filteredCookies) {
-                        $(filteredCookies).each(function (i, cookie) {
-                            if (cookie.text !== '') {
-                                $(element).val(cookie.text);
-                                cachedFilters[cookie.field] = cookie.text;
-                            }
-                        });
-                    };
-
-                header.find(searchControls).each(function () {
-                    var field = $(this).closest('[data-field]').data('field'),
-                        filteredCookies = $.grep(parsedCookieFilters, function (cookie) {
-                            return cookie.field === field;
-                        });
-
-                    applyCookieFilters(this, filteredCookies);
-                });
-
-                bootstrapTable.initColumnSearch(cachedFilters);
-                bootstrapTable.options.filterControlValuesLoaded = true;
-                bootstrapTable.initServer();
-            }
-        }, 250);
-    };
-
-    $.extend($.fn.bootstrapTable.defaults, {
-        cookie: false,
-        cookieExpire: '2h',
-        cookiePath: null,
-        cookieDomain: null,
-        cookieSecure: null,
-        cookieIdTable: '',
-        cookiesEnabled: [
-            'bs.table.sortOrder', 'bs.table.sortName',
-            'bs.table.pageNumber', 'bs.table.pageList',
-            'bs.table.columns', 'bs.table.searchText',
-            'bs.table.filterControl'
-        ],
-        cookieStorage: 'cookieStorage', //localStorage, sessionStorage
-        //internal variable
-        filterControls: [],
-        filterControlValuesLoaded: false
-    });
-
-    $.fn.bootstrapTable.methods.push('getCookies');
-    $.fn.bootstrapTable.methods.push('deleteCookie');
-
-    $.extend($.fn.bootstrapTable.utils, {
-        setCookie: setCookie,
-        getCookie: getCookie
-    });
-
-    var BootstrapTable = $.fn.bootstrapTable.Constructor,
-        _init = BootstrapTable.prototype.init,
-        _initTable = BootstrapTable.prototype.initTable,
-        _initServer = BootstrapTable.prototype.initServer,
-        _onSort = BootstrapTable.prototype.onSort,
-        _onPageNumber = BootstrapTable.prototype.onPageNumber,
-        _onPageListChange = BootstrapTable.prototype.onPageListChange,
-        _onPagePre = BootstrapTable.prototype.onPagePre,
-        _onPageNext = BootstrapTable.prototype.onPageNext,
-        _toggleColumn = BootstrapTable.prototype.toggleColumn,
-        _selectPage = BootstrapTable.prototype.selectPage,
-        _onSearch = BootstrapTable.prototype.onSearch;
-
-    BootstrapTable.prototype.init = function () {
-        this.options.filterControls = [];
-        this.options.filterControlValuesLoaded = false;
-
-        this.options.cookiesEnabled = typeof this.options.cookiesEnabled === 'string' ?
-            this.options.cookiesEnabled.replace('[', '').replace(']', '')
-                .replace(/ /g, '').toLowerCase().split(',') :
-            this.options.cookiesEnabled;
-
-        if (this.options.filterControl) {
-            var that = this;
-            this.$el.on('column-search.bs.table', function (e, field, text) {
-                var isNewField = true;
-
-                for (var i = 0; i < that.options.filterControls.length; i++) {
-                    if (that.options.filterControls[i].field === field) {
-                        that.options.filterControls[i].text = text;
-                        isNewField = false;
-                        break;
-                    }
-                }
-                if (isNewField) {
-                    that.options.filterControls.push({
-                        field: field,
-                        text: text
-                    });
-                }
-
-                setCookie(that, cookieIds.filterControl, JSON.stringify(that.options.filterControls));
-            }).on('created-controls.bs.table', initCookieFilters(that));
-        }
-        _init.apply(this, Array.prototype.slice.apply(arguments));
-    };
-
-    BootstrapTable.prototype.initServer = function () {
-        var bootstrapTable = this;
-        if (bootstrapTable.options.cookie && bootstrapTable.options.filterControl && !bootstrapTable.options.filterControlValuesLoaded) {
-            var cookie = JSON.parse(getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, cookieIds.filterControl));
-            if (cookie)
-                return;
-        }
-        _initServer.apply(this, Array.prototype.slice.apply(arguments));
-    };
-
-
-    BootstrapTable.prototype.initTable = function () {
-        _initTable.apply(this, Array.prototype.slice.apply(arguments));
-        this.initCookie();
-    };
-
-    BootstrapTable.prototype.initCookie = function () {
-        if (!this.options.cookie) {
-            return;
-        }
-
-        if ((this.options.cookieIdTable === '') || (this.options.cookieExpire === '') || (!cookieEnabled())) {
-            console.error("Configuration error. Please review the cookieIdTable, cookieExpire properties, if those properties are ok, then this browser does not support the cookies");
-            this.options.cookie = false; //Make sure that the cookie extension is disabled
-            return;
-        }
-
-        var sortOrderCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortOrder),
-            sortOrderNameCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortName),
-            pageNumberCookie = getCookie(this, this.options.cookieIdTable, cookieIds.pageNumber),
-            pageListCookie = getCookie(this, this.options.cookieIdTable, cookieIds.pageList),
-            columnsCookie = JSON.parse(getCookie(this, this.options.cookieIdTable, cookieIds.columns)),
-            searchTextCookie = getCookie(this, this.options.cookieIdTable, cookieIds.searchText);
-
-        //sortOrder
-        this.options.sortOrder = sortOrderCookie ? sortOrderCookie : this.options.sortOrder;
-        //sortName
-        this.options.sortName = sortOrderNameCookie ? sortOrderNameCookie : this.options.sortName;
-        //pageNumber
-        this.options.pageNumber = pageNumberCookie ? +pageNumberCookie : this.options.pageNumber;
-        //pageSize
-        this.options.pageSize = pageListCookie ? pageListCookie === this.options.formatAllRows() ? pageListCookie : +pageListCookie : this.options.pageSize;
-        //searchText
-        this.options.searchText = searchTextCookie ? searchTextCookie : '';
-
-        if (columnsCookie) {
-            $.each(this.columns, function (i, column) {
-                column.visible = $.inArray(column.field, columnsCookie) !== -1;
-            });
-        }
-    };
-
-    BootstrapTable.prototype.onSort = function () {
-        _onSort.apply(this, Array.prototype.slice.apply(arguments));
-        setCookie(this, cookieIds.sortOrder, this.options.sortOrder);
-        setCookie(this, cookieIds.sortName, this.options.sortName);
-    };
-
-    BootstrapTable.prototype.onPageNumber = function () {
-        _onPageNumber.apply(this, Array.prototype.slice.apply(arguments));
-        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
-        return false;
-    };
-
-    BootstrapTable.prototype.onPageListChange = function () {
-        _onPageListChange.apply(this, Array.prototype.slice.apply(arguments));
-        setCookie(this, cookieIds.pageList, this.options.pageSize);
-        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
-        return false;
-    };
-
-    BootstrapTable.prototype.onPagePre = function () {
-        _onPagePre.apply(this, Array.prototype.slice.apply(arguments));
-        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
-        return false;
-    };
-
-    BootstrapTable.prototype.onPageNext = function () {
-        _onPageNext.apply(this, Array.prototype.slice.apply(arguments));
-        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
-        return false;
-    };
-
-    BootstrapTable.prototype.toggleColumn = function () {
-        _toggleColumn.apply(this, Array.prototype.slice.apply(arguments));
-
-        var visibleColumns = [];
-
+      })
+
+      UtilsCookie.setCookie(this, UtilsCookie.cookieIds.columns, JSON.stringify(visibleColumns))
+    }
+
+    selectPage (page) {
+      super.selectPage()
+      UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, page)
+    }
+
+    onSearch () {
+      const target = Array.prototype.slice.apply(arguments)
+      super.onSearch(this, target)
+
+      if ($(target[0].currentTarget).parent().hasClass('search')) {
+        UtilsCookie.setCookie(this, UtilsCookie.cookieIds.searchText, this.searchText)
+      }
+      UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber)
+    }
+
+    filterBy () {
+      super.filterBy()
+      UtilsCookie.setCookie(this, UtilsCookie.cookieIds.filterBy, JSON.stringify(this.filterColumns))
+    }
+
+    initCookie () {
+      if (!this.options.cookie) {
+        return
+      }
+
+      if ((this.options.cookieIdTable === '') || (this.options.cookieExpire === '') || (!UtilsCookie.cookieEnabled())) {
+        console.error('Configuration error. Please review the cookieIdTable and the cookieExpire property. If the properties are correct, then this browser does not support cookies.')
+        this.options.cookie = false // Make sure that the cookie extension is disabled
+        return
+      }
+
+      const sortOrderCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.sortOrder)
+      const sortOrderNameCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.sortName)
+      const pageNumberCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.pageNumber)
+      const pageListCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.pageList)
+      const columnsCookie = JSON.parse(UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.columns))
+      const searchTextCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.searchText)
+
+      // sortOrder
+      this.options.sortOrder = sortOrderCookie ? sortOrderCookie : this.options.sortOrder
+      // sortName
+      this.options.sortName = sortOrderNameCookie ? sortOrderNameCookie : this.options.sortName
+      // pageNumber
+      this.options.pageNumber = pageNumberCookie ? +pageNumberCookie : this.options.pageNumber
+      // pageSize
+      this.options.pageSize = pageListCookie ? pageListCookie === this.options.formatAllRows() ? pageListCookie : +pageListCookie : this.options.pageSize
+      // searchText
+      this.options.searchText = searchTextCookie ? searchTextCookie : ''
+
+      if (columnsCookie) {
         $.each(this.columns, function (i, column) {
-            if (column.visible) {
-                visibleColumns.push(column.field);
-            }
-        });
-
-        setCookie(this, cookieIds.columns, JSON.stringify(visibleColumns));
-    };
-
-    BootstrapTable.prototype.selectPage = function (page) {
-        _selectPage.apply(this, Array.prototype.slice.apply(arguments));
-        setCookie(this, cookieIds.pageNumber, page);
-    };
-
-    BootstrapTable.prototype.onSearch = function () {
-        var target = Array.prototype.slice.apply(arguments);
-        _onSearch.apply(this, target);
-
-        if ($(target[0].currentTarget).parent().hasClass('search')) {
-            setCookie(this, cookieIds.searchText, this.searchText);
+          column.visible = $.inArray(column.field, columnsCookie) !== -1
+        })
+      }
+    }
+
+    getCookies () {
+      const bootstrapTable = this
+      const cookies = {}
+      $.each(UtilsCookie.cookieIds, function (key, value) {
+        cookies[key] = UtilsCookie.getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, value)
+        if (key === 'columns') {
+          cookies[key] = JSON.parse(cookies[key])
         }
-        setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
-    };
-
-    BootstrapTable.prototype.getCookies = function () {
-        var bootstrapTable = this;
-        var cookies = {};
-        $.each(cookieIds, function(key, value) {
-            cookies[key] = getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, value);
-            if (key === 'columns') {
-                cookies[key] = JSON.parse(cookies[key]);
-            }
-        });
-        return cookies;
-    };
+      })
+      return cookies
+    }
 
-    BootstrapTable.prototype.deleteCookie = function (cookieName) {
-        if ((cookieName === '') || (!cookieEnabled())) {
-            return;
-        }
+    deleteCookie (cookieName) {
+      if ((cookieName === '') || (!UtilsCookie.cookieEnabled())) {
+        return
+      }
+
+      UtilsCookie.deleteCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds[cookieName])
+    }
+  }
 
-        deleteCookie(this, this.options.cookieIdTable, cookieIds[cookieName]);
-    };
-})(jQuery);
+})(jQuery)

+ 15 - 14
src/extensions/filter-control/bootstrap-table-filter-control.js

@@ -79,10 +79,10 @@
       // If we get here, the value is valid to add
       return false
     },
-    fixHeaderCSS ({$tableHeader}) {
+    fixHeaderCSS ({ $tableHeader }) {
       $tableHeader.css('height', '77px')
     },
-    getCurrentHeader ({$header, options, $tableHeader}) {
+    getCurrentHeader ({ $header, options, $tableHeader }) {
       let header = $header
       if (options.height) {
         header = $tableHeader
@@ -90,7 +90,7 @@
 
       return header
     },
-    getCurrentSearchControls ({options}) {
+    getCurrentSearchControls ({ options }) {
       let searchControls = 'select, input'
       if (options.height) {
         searchControls = 'table select, table input'
@@ -196,14 +196,14 @@
     escapeID (id) {
       return String(id).replace(/(:|\.|\[|\]|,)/g, '\\$1')
     },
-    isColumnSearchableViaSelect ({filterControl, searchable}) {
+    isColumnSearchableViaSelect ({ filterControl, searchable }) {
       return filterControl &&
-      filterControl.toLowerCase() === 'select' &&
-      searchable
+        filterControl.toLowerCase() === 'select' &&
+        searchable
     },
-    isFilterDataNotGiven ({filterData}) {
+    isFilterDataNotGiven ({ filterData }) {
       return filterData === undefined ||
-      filterData.toLowerCase() === 'column'
+        filterData.toLowerCase() === 'column'
     },
     hasSelectControlElement (selectControl) {
       return selectControl && selectControl.length > 0
@@ -228,7 +228,7 @@
         ) {
           if (selectControl.get(selectControl.length - 1).options.length === 0) {
             // Added the default option
-            UtilsFilterControl.addOptionToSelectControl(selectControl, '', '')
+            UtilsFilterControl.addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder)
           }
 
           const uniqueValues = {}
@@ -329,7 +329,7 @@
               `.bootstrap-table-filter-control-${UtilsFilterControl.escapeID(column.field)}`
             )
 
-            UtilsFilterControl.addOptionToSelectControl(selectControl, '', '')
+            UtilsFilterControl.addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder)
             filterDataType(filterDataSource, selectControl)
           } else {
             throw new SyntaxError(
@@ -436,7 +436,7 @@
         })
 
         if (header.find('.date-filter-control').length > 0) {
-          $.each(that.columns, (i, {filterControl, field, filterDatepickerOptions}) => {
+          $.each(that.columns, (i, { filterControl, field, filterDatepickerOptions }) => {
             if (
               filterControl !== undefined &&
               filterControl.toLowerCase() === 'datepicker'
@@ -446,8 +446,8 @@
                   `.date-filter-control.bootstrap-table-filter-control-${field}`
                 )
                 .datepicker(filterDatepickerOptions)
-                .on('changeDate', ({currentTarget}) => {
-                  $(Utils.sprintf('#%s', currentTarget.id)).val(
+                .on('changeDate', ({ currentTarget }) => {
+                  $(currentTarget).val(
                     currentTarget.value
                   )
                   // Fired the keyup event
@@ -526,7 +526,7 @@
           placeholder
         )
       },
-      select ({options}, field, isVisible) {
+      select ({ options }, field, isVisible) {
         return Utils.sprintf(
           '<select class="form-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s" dir="%s"></select>',
           field,
@@ -577,6 +577,7 @@
   $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales)
 
   $.fn.bootstrapTable.methods.push('triggerSearch')
+  $.fn.bootstrapTable.methods.push('clearFilterControl')
 
   $.BootstrapTable = class extends $.BootstrapTable {
     init () {