1
0
Fork 0
mirror of https://github.com/koalyptus/TableFilter.git synced 2024-06-17 05:06:49 +02:00
TableFilter/src/modules/storage.js

90 lines
2.1 KiB
JavaScript
Raw Normal View History

2016-04-07 12:13:54 +02:00
2016-04-08 12:13:29 +02:00
import Cookie from '../cookie';
2016-04-07 12:13:54 +02:00
const global = window;
2016-04-07 18:34:25 +02:00
const JSON = global.JSON;
const localStorage = global.localStorage;
2016-04-07 12:13:54 +02:00
export const hasStorage = () => {
return 'Storage' in global;
};
export class Storage {
constructor(state){
this.state = state;
2016-04-07 18:34:25 +02:00
this.tf = state.tf;
2016-04-07 12:13:54 +02:00
this.enableLocalStorage = state.enableLocalStorage && hasStorage();
2016-04-08 12:13:29 +02:00
this.enableCookie = state.enableCookie && !this.enableLocalStorage;
2016-04-07 12:13:54 +02:00
this.emitter = state.emitter;
2016-04-08 12:13:29 +02:00
this.duration = state.cookieDuration;
2016-04-07 12:13:54 +02:00
}
init(){
2016-04-07 18:34:25 +02:00
this.emitter.on(['state-changed'], (tf, state) => this.save(state));
this.emitter.on(['initialized'], () => this.sync());
2016-04-07 12:13:54 +02:00
}
2016-04-07 18:34:25 +02:00
save(state){
if(this.enableLocalStorage) {
localStorage[this.getKey()] = JSON.stringify(state);
2016-04-08 12:13:29 +02:00
} else {
Cookie.write(this.getKey(), JSON.stringify(state), this.duration);
}
}
parse(){
let state = null;
if(this.enableLocalStorage) {
state = localStorage[this.getKey()];
} else {
state = Cookie.read(this.getKey());
}
if(!state){
return null;
2016-04-07 18:34:25 +02:00
}
2016-04-08 12:13:29 +02:00
return JSON.parse(state);
2016-04-07 12:13:54 +02:00
}
2016-04-08 12:13:29 +02:00
remove(){
2016-04-07 18:34:25 +02:00
if(this.enableLocalStorage) {
localStorage.removeItem(this.getKey());
2016-04-08 12:13:29 +02:00
} else {
Cookie.remove(this.getKey());
2016-04-07 18:34:25 +02:00
}
}
2016-04-07 12:13:54 +02:00
2016-04-07 18:34:25 +02:00
sync() {
2016-04-08 12:13:29 +02:00
let state = this.parse();
2016-04-07 18:34:25 +02:00
if (!state) {
return;
}
// To prevent state to react to features changes, state is temporarily
// disabled
this.state.disable();
// State is overriden with hash state object
this.state.override(state);
// New hash state is applied to features
this.state.sync();
// State is re-enabled
this.state.enable();
}
getKey(){
return `${this.tf.prfxTf}_${this.tf.id}`;
}
destroy(){
this.emitter.off(['state-changed'], (tf, state) => this.save(state));
this.emitter.off(['initialized'], () => this.sync());
2016-04-08 12:13:29 +02:00
this.remove();
2016-04-07 18:34:25 +02:00
this.state = null;
this.emitter = null;
}
2016-04-07 12:13:54 +02:00
}