Skip to content

Commit

Permalink
[FEATURE] #179 Add savestate for session and storage, also keep add…
Browse files Browse the repository at this point in the history
…itional GET url-parameter (#297)
  • Loading branch information
roman-1983 authored Apr 20, 2023
1 parent ee493ad commit 2b25e0d
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions src/Resources/public/js/datatables.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,34 @@
state = ''
;

// Load page state if needed
var stateDuration = null
// Load page state if needed
switch (config.state) {
case 'fragment':
state = window.location.hash;
state = (state.length > 1 ? deparam(state.substr(1)) : {});
break;
case 'query':
state = window.location.search;
state = (state.length > 1 ? deparam(state.substr(1)) : {});
break;
case 'local':
stateDuration = 0
if (localStorage.getItem('DataTables_' + config.name + '_' + window.location.pathname) !== null) {
state = JSON.parse(localStorage.getItem('DataTables_' + config.name + '_' + window.location.pathname))
}
break;
case 'session':
stateDuration = -1
if (sessionStorage.getItem('DataTables_' + config.name + '_' + window.location.pathname) !== null) {
state = JSON.parse(sessionStorage.getItem('DataTables_' + config.name + '_' + window.location.pathname))
}
break;
}
state = (state.length > 1 ? deparam(state.substr(1)) : {});

var persistOptions = config.state === 'none' ? {} : {
stateDuration: stateDuration,
stateSave: true,
stateLoadCallback: function(s, cb) {
// Only need stateSave to expose state() function as loading lazily is not possible otherwise
Expand Down Expand Up @@ -63,7 +80,7 @@
var merged = $.extend(true, {}, api.state(), state);

api
.order(merged.order)
.order(state.order ?? api.state().order)
.search(merged.search.search)
.page.len(merged.length)
.page(merged.start / merged.length)
Expand All @@ -90,7 +107,6 @@
if (config.state !== 'none') {
dt.on('draw.dt', function(e) {
var data = $.param(dt.state()).split('&');

// First draw establishes state, subsequent draws run diff on the first
if (!baseState) {
baseState = data;
Expand All @@ -102,8 +118,13 @@
+ '#' + decodeURIComponent(diff.join('&')));
break;
case 'query':
var windowLocationSearch = deparam(decodeURIComponent(diff.join('&')))
if(window.location.search !== null) {
windowLocationSearch = deparam(window.location.search.substr(1))
Object.assign(windowLocationSearch, deparam(decodeURIComponent(diff.join('&'))))
}
history.replaceState(null, null, window.location.origin + window.location.pathname
+ '?' + decodeURIComponent(diff.join('&') + window.location.hash));
+ '?' + decodeURIComponent($.param(windowLocationSearch) + window.location.hash));
break;
}
}
Expand Down

0 comments on commit 2b25e0d

Please sign in to comment.