浏览代码

Added the state save option

Dennis Hernández 10 年之前
父节点
当前提交
5c0e295d10

+ 5 - 0
docs/_i18n/en/documentation/methods.md

@@ -208,5 +208,10 @@ The calling method syntax: `$('#table').bootstrapTable('method', parameter);`.
         <td>none</td>
         <td>Toggle the card/table view.</td>
     </tr>
+	<tr>
+        <td>deleteCookie</td>
+        <td>cookie name</td>
+        <td>Delete a cookie created. You must use: 'sortOrder', 'sortName', 'pageNumber' or 'pageList'.</td>
+    </tr>
     </tbody>
 </table>

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

@@ -396,6 +396,28 @@ The table options is defined in `jQuery.fn.bootstrapTable.defaults`.
         <td>false</td>
         <td>True to enable the key events. For now when the user presses the "S" or "s" key the search button will be focused.</td>
     </tr>
+	<tr>
+        <td>stateSave</td>
+        <td>data-state-save</td>
+        <td>Boolean</td>
+        <td>false</td>
+        <td>True to save the state of a table (its paging position, ordering state, records per page).</td>
+    </tr>
+	<tr>
+        <td>stateSaveExpire</td>
+        <td>data-state-save-expire</td>
+        <td>String</td>
+        <td>'2h'</td>
+        <td>You must set this property if stateSave is enable to know when will expire the cookie created. Must use this format: 'number{letter}' like '2h', in the letter position
+		you can use: 's','mi','h','d','m','y', these means: 'seconds', 'minutes', 'hours', 'days', 'months', 'years'.</td>
+    </tr>
+	<tr>
+        <td>stateSaveIdTable</td>
+        <td>data-state-save-id-table</td>
+        <td>String</td>
+        <td>''</td>
+        <td>You must set this property if stateSave is enable to sets an unique cookie with an identifier for each table in your page or project. You must set this property because we need create cookies with an identifier.</td>
+    </tr>
     <tr>
         <td>rowStyle</td>
         <td>data-row-style</td>

+ 5 - 0
docs/_i18n/es/documentation/methods.md

@@ -208,5 +208,10 @@ Sintaxis para llamar a un método: `$('#table').bootstrapTable('method', paramet
         <td>none</td>
         <td>Alterna la vista entre tabla y tarjeta.</td>
     </tr>
+	<tr>
+        <td>deleteCookie</td>
+        <td>cookie name</td>
+        <td>Elimina una cookie creada. Debe usar: 'sortOrder', 'sortName', 'pageNumber' o 'pageList'.</td>
+    </tr>
     </tbody>
 </table>

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

@@ -391,6 +391,28 @@ Las opciones de la tabla están definidas en `jQuery.fn.bootstrapTable.defaults`
         <td>True para habilitar los eventos del teclado. Por ahora cuando el 
 		usuario presiona la tecla "S" o "s" el campo de búsqueda tendrá el focus.</td>
     </tr>
+	<tr>
+        <td>stateSave</td>
+        <td>data-state-save</td>
+        <td>Boolean</td>
+        <td>false</td>
+        <td>True para guardar el estado de la tabla (la posición de la paginación, ordenamiento, filas por página).</td>
+    </tr>
+	<tr>
+        <td>stateSaveExpire</td>
+        <td>data-state-save-expire</td>
+        <td>String</td>
+        <td>'2h'</td>
+        <td>Indique la propiedad para saber cuando expirará la cookie creada. Use este formato: 'numero{letra}' por ejemplo: '2h', en la posicióon de la letra
+		se puede usar: 's','mi','h','d','m','y', esto significa: 'segundos', 'minutos', 'horas', 'días', 'meses', 'años'.</td>
+    </tr>
+	<tr>
+        <td>stateSaveIdTable</td>
+        <td>data-state-save-id-table</td>
+        <td>String</td>
+        <td>''</td>
+        <td>Debe indicar la propiedad si la stateSave está habilitado. Este será el identificador para cookie guardada por tabla en su página o proyecto.</td>
+    </tr>
     <tr>
         <td>rowStyle</td>
         <td>data-row-style</td>

+ 146 - 2
src/bootstrap-table.js

@@ -7,7 +7,18 @@
 !function ($) {
     'use strict';
 
-    var cellHeight = 37; // update css if changed
+    var cellHeight = 37, // update css if changed
+        idStateSave = '',
+        idSortOrderStateSave = 'bs.table.sortOrder',
+        idSortNameStateSave = 'bs.table.sortName',
+        idPageNumberStateSave = 'bs.table.pageNumber',
+        idPageListStateSave = 'bs.table.pageList',
+        idsStateSaveArray = {
+                                'sortOrder': idSortOrderStateSave,
+                                'sortName': idSortNameStateSave,
+                                'pageNumber': idPageNumberStateSave,
+                                'pageList': idPageListStateSave
+                            };
     // TOOLS DEFINITION
     // ======================
 
@@ -113,6 +124,78 @@
         return text;
     };
 
+    var cookieEnabled = function (){
+        var cookieEnabled = (navigator.cookieEnabled) ? true : false;
+
+        if (typeof navigator.cookieEnabled === "undefined" && !cookieEnabled)
+        {
+            document.cookie = "testcookie";
+            cookieEnabled = (document.cookie.indexOf("testcookie") !== -1) ? true : false;
+        }
+        return (cookieEnabled);
+    };
+
+    var setCookie = function (cookieName, sValue, vEnd, sPath, sDomain, bSecure) {
+        cookieName = idStateSave + cookieName;
+        if (!cookieName || /^(?:expires|max\-age|path|domain|secure)$/i.test(cookieName)) {
+            return false;
+        }
+        var sExpires = "",
+            time = '';
+
+        time = vEnd.replace(/[0-9]/,''); //s,mi,h,d,m,y
+        vEnd = vEnd.replace(/[A-Za-z]/,''); //number
+
+        switch (time.toLowerCase()) {
+            case 's':
+                vEnd = +vEnd;
+                break;
+            case 'mi':
+                vEnd = vEnd * 60;
+                break;
+            case 'h':
+                vEnd = vEnd * 60 * 60;
+            case 'd':
+                vEnd = vEnd * 24 * 60 * 60;
+                break;
+            case 'm':
+                vEnd = vEnd * 30 * 24 * 60 * 60;
+                break;
+            case 'y':
+                vEnd = vEnd * 365 * 30 * 24 * 60 * 60;
+                break;
+        }
+
+        sExpires = "; max-age=" + vEnd;
+
+        document.cookie = encodeURIComponent(cookieName) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
+        return true;
+    };
+
+    var getCookie = function (cookieName) {
+        cookieName = idStateSave + cookieName;
+        if (!cookieName) {
+            return null;
+        }
+        return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(cookieName).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
+    };
+
+    var hasCookie = function (cookieName) {
+        if (!cookieName) {
+            return false;
+        }
+        return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(cookieName).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
+    };
+
+    var deleteCookie = function (cookieName, sPath, sDomain) {
+        cookieName = idStateSave + cookieName;
+        if (!hasCookie(cookieName)) {
+            return false;
+        }
+        document.cookie = encodeURIComponent(cookieName) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
+        return true;
+    };
+
     // BOOTSTRAP TABLE CLASS DEFINITION
     // ======================
 
@@ -183,6 +266,9 @@
         searchTimeOut: 500,
         keyEvents: false,
         searchText: '',
+        stateSave: false,
+        stateSaveExpire: '2h',
+        stateSaveIdTable: '',
         iconSize: undefined,
         iconsPrefix: 'glyphicon', // glyphicon of fa (font awesome)
         icons: {
@@ -334,6 +420,7 @@
     };
 
     BootstrapTable.prototype.init = function () {
+        this.initStateSave();
         this.initContainer();
         this.initTable();
         this.initHeader();
@@ -708,6 +795,10 @@
             this.initServer();
             return;
         }
+        if (this.options.stateSave && cookieEnabled()) {
+            setCookie(idSortOrderStateSave, this.options.sortOrder, this.options.stateSaveExpire);
+            setCookie(idSortNameStateSave, this.options.sortName, this.options.stateSaveExpire);
+        }
         this.initSort();
         this.initBody();
     };
@@ -1108,6 +1199,9 @@
         this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase() ?
                                     this.options.formatAllRows() : +$this.text();
         this.$toolbar.find('.page-size').text(this.options.pageSize);
+        if (this.options.stateSave && cookieEnabled()) {
+            setCookie(idPageListStateSave, this.options.pageSize, this.options.stateSaveExpire);
+        }
         this.updatePagination(event);
     };
 
@@ -1136,6 +1230,9 @@
             return;
         }
         this.options.pageNumber = +$(event.currentTarget).text();
+        if (this.options.stateSave && cookieEnabled()) {
+            setCookie(idPageNumberStateSave, this.options.pageNumber, this.options.stateSaveExpire);
+        }
         this.updatePagination(event);
     };
 
@@ -1457,6 +1554,40 @@
       }
     };
 
+    BootstrapTable.prototype.initStateSave = function () {
+        if (!this.options.stateSave) {
+            return;
+        }
+
+        if (!cookieEnabled()) {
+            return;
+        }
+
+        if (this.options.stateSaveIdTable === '') {
+            return;
+        }
+
+        idStateSave = this.options.stateSaveIdTable + '.';
+
+        var sortOrderStateSave = getCookie(idSortOrderStateSave),
+            sortOrderStateName = getCookie(idSortNameStateSave),
+            pageNumberStateSave = getCookie(idPageNumberStateSave),
+            pageListStateSave = getCookie(idPageListStateSave);
+
+        if (sortOrderStateSave !== undefined && sortOrderStateSave !== null) {
+            this.options.sortOrder = sortOrderStateSave,
+            this.options.sortName = sortOrderStateName;
+        }
+
+        if (pageNumberStateSave !== undefined && pageNumberStateSave !== null) {
+            this.options.pageNumber = +pageNumberStateSave;
+        }
+
+        if (pageListStateSave !== undefined && pageListStateSave !== null) {
+            this.options.pageSize = pageListStateSave === this.options.formatAllRows() ? pageListStateSave : +pageListStateSave;
+        }
+    };
+
     BootstrapTable.prototype.getCaretHtml = function () {
         return ['<span class="order' + (this.options.sortOrder === 'desc' ? '' : ' dropup') + '">',
             '<span class="caret" style="margin: 10px 5px;"></span>',
@@ -1906,6 +2037,18 @@
         this.initBody();
     };
 
+    BootstrapTable.prototype.deleteCookie = function (cookieName) {
+        if (cookieName === '') {
+            return;
+        }
+
+        if (!cookieEnabled()) {
+            return;
+        }
+
+        deleteCookie(idsStateSaveArray[cookieName]);
+    }
+
     // BOOTSTRAP TABLE PLUGIN DEFINITION
     // =======================
 
@@ -1928,7 +2071,8 @@
         'scrollTo',
         'selectPage', 'prevPage', 'nextPage',
         'togglePagination',
-        'toggleView'
+        'toggleView',
+        'deleteCookie'
     ];
 
     $.fn.bootstrapTable = function (option, _relatedTarget) {