Skip to content

Commit

Permalink
Fixed snipe#4784 - cookie not always being set correctly for ajax tables
Browse files Browse the repository at this point in the history
  • Loading branch information
snipe committed Jan 11, 2018
1 parent bab0bda commit c6a9563
Show file tree
Hide file tree
Showing 3 changed files with 166 additions and 71 deletions.
205 changes: 154 additions & 51 deletions public/js/extensions/cookie/bootstrap-table-cookie.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* @author: Dennis Hernández
* @webSite: http://djhvscf.github.io/Blog
* @version: v1.2.0
* @version: v1.2.2
*
* @update zhixin wen <wenzhixin2010@gmail.com>
*/
Expand Down Expand Up @@ -64,11 +64,27 @@
}

cookieName = that.options.cookieIdTable + '.' + cookieName;
if (!cookieName || /^(?:expires|max\-age|path|domain|secure)$/i.test(cookieName)) {
return false;

switch(that.options.cookieStorage) {
case 'cookieStorage':
document.cookie = [
cookieName, '=', cookieValue,
'; expires=' + 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;
}

document.cookie = encodeURIComponent(cookieName) + '=' + encodeURIComponent(cookieValue) + calculateExpiration(that.options.cookieExpire) + (that.options.cookieDomain ? '; domain=' + that.options.cookieDomain : '') + (that.options.cookiePath ? '; path=' + that.options.cookiePath : '') + (that.cookieSecure ? '; secure' : '');
return true;
};

Expand All @@ -83,28 +99,44 @@

cookieName = tableName + '.' + cookieName;

return decodeURIComponent(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURIComponent(cookieName).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null;
};

var hasCookie = function (cookieName) {
if (!cookieName) {
return false;
switch(that.options.cookieStorage) {
case 'cookieStorage':
return decodeURIComponent(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURIComponent(cookieName).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null;
case 'localStorage':
return localStorage.getItem(cookieName);
case 'sessionStorage':
return sessionStorage.getItem(cookieName);
default:
return null;
}
return (new RegExp('(?:^|;\\s*)' + encodeURIComponent(cookieName).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=')).test(document.cookie);
};

var deleteCookie = function (tableName, cookieName, sPath, sDomain) {
var deleteCookie = function (that, tableName, cookieName) {
cookieName = tableName + '.' + cookieName;
if (!hasCookie(cookieName)) {
return false;

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;

}
document.cookie = encodeURIComponent(cookieName) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (sDomain ? '; domain=' + sDomain : '') + (sPath ? '; path=' + sPath : '');
return true;
};

var calculateExpiration = function(cookieExpire) {
var time = cookieExpire.replace(/[0-9]*/, ''); //s,mi,h,d,m,y
cookieExpire = cookieExpire.replace(/[A-Za-z]/, ''); //number
cookieExpire = cookieExpire.replace(/[A-Za-z]{1,2}}/, ''); //number

switch (time.toLowerCase()) {
case 's':
Expand All @@ -123,7 +155,7 @@
cookieExpire = cookieExpire * 30 * 24 * 60 * 60;
break;
case 'y':
cookieExpire = cookieExpire * 365 * 30 * 24 * 60 * 60;
cookieExpire = cookieExpire * 365 * 24 * 60 * 60;
break;
default:
cookieExpire = undefined;
Expand All @@ -133,24 +165,69 @@
return cookieExpire === undefined ? '' : '; max-age=' + cookieExpire;
};

var initCookieFilters = function (bootstrapTable) {
setTimeout(function () {
var parsedCookieFilters = JSON.parse(getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, cookieIds.filterControl));

if (!bootstrapTable.options.filterControlValuesLoaded && parsedCookieFilters) {
bootstrapTable.options.filterControlValuesLoaded = true;

var cachedFilters = {},
header = getCurrentHeader(bootstrapTable),
searchControls = getCurrentSearchControls(bootstrapTable),

applyCookieFilters = function (element, filteredCookies) {
$(filteredCookies).each(function (i, cookie) {
$(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);
}
}, 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'],
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,
Expand All @@ -167,9 +244,10 @@
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;
this.options.cookiesEnabled.replace('[', '').replace(']', '')
.replace(/ /g, '').toLowerCase().split(',') :
this.options.cookiesEnabled;

if (this.options.filterControl) {
var that = this;
Expand All @@ -191,36 +269,46 @@
}

setCookie(that, cookieIds.filterControl, JSON.stringify(that.options.filterControls));
}).on('post-body.bs.table', function () {
setTimeout(function () {
if (!that.options.filterControlValuesLoaded) {
that.options.filterControlValuesLoaded = true;
var filterControl = JSON.parse(getCookie(that, that.options.cookieIdTable, cookieIds.filterControl));
if (filterControl) {
var field = null,
result = [],
header = getCurrentHeader(that),
searchControls = getCurrentSearchControls(that);

header.find(searchControls).each(function (index, ele) {
field = $(this).parent().parent().parent().data('field');
result = $.grep(filterControl, function (valueObj) {
return valueObj.field === field;
});

if (result.length > 0) {
$(this).val(result[0].text);
that.onColumnSearch({currentTarget: $(this)});
}
});
}
}
}, 250);
});
}).on('post-body.bs.table', initCookieFilters(that));
}
_init.apply(this, Array.prototype.slice.apply(arguments));
};

BootstrapTable.prototype.initServer = function () {
var bootstrapTable = this,
selectsWithoutDefaults = [],

columnHasSelectControl = function (column) {
return column.filterControl && column.filterControl === 'select';
},

columnHasDefaultSelectValues = function (column) {
return column.filterData && column.filterData !== 'column';
},

cookiesPresent = function() {
var cookie = JSON.parse(getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, cookieIds.filterControl));
return bootstrapTable.options.cookie && cookie;
};

selectsWithoutDefaults = $.grep(bootstrapTable.columns, function(column) {
return columnHasSelectControl(column) && !columnHasDefaultSelectValues(column);
});

// reset variable to original initServer function, so that future calls to initServer
// use the original function from this point on.
BootstrapTable.prototype.initServer = _initServer;

// early return if we don't need to populate any select values with cookie values
if (this.options.filterControl && cookiesPresent() && selectsWithoutDefaults.length === 0) {
return;
}

// call BootstrapTable.prototype.initServer
_initServer.apply(this, Array.prototype.slice.apply(arguments));
};


BootstrapTable.prototype.initTable = function () {
_initTable.apply(this, Array.prototype.slice.apply(arguments));
this.initCookie();
Expand All @@ -233,7 +321,6 @@

if ((this.options.cookieIdTable === '') || (this.options.cookieExpire === '') || (!cookieEnabled())) {
throw new Error("Configuration error. Please review the cookieIdTable, cookieExpire properties, if those properties are ok, then this browser does not support the cookies");
return;
}

var sortOrderCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortOrder),
Expand Down Expand Up @@ -310,22 +397,38 @@

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 () {
_onSearch.apply(this, Array.prototype.slice.apply(arguments));
setCookie(this, cookieIds.searchText, this.searchText);
var target = Array.prototype.slice.apply(arguments);
_onSearch.apply(this, target);

if ($(target[0].currentTarget).parent().hasClass('search')) {
setCookie(this, cookieIds.searchText, this.searchText);
}
};

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;
};

BootstrapTable.prototype.deleteCookie = function (cookieName) {
if ((cookieName === '') || (!cookieEnabled())) {
return;
}

deleteCookie(this.options.cookieIdTable, cookieIds[cookieName], this.options.cookiePath, this.options.cookieDomain);
deleteCookie(this, this.options.cookieIdTable, cookieIds[cookieName]);
};
})(jQuery);
Loading

0 comments on commit c6a9563

Please sign in to comment.