2018-03-17 18:26:18 +05:30
|
|
|
/* eslint-disable no-param-reassign, prefer-template, no-var, no-void, consistent-return */
|
|
|
|
|
2017-08-17 22:00:37 +05:30
|
|
|
import AccessorUtilities from './lib/utils/accessor';
|
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
export default class Autosave {
|
|
|
|
constructor(field, key, resource) {
|
2017-08-17 22:00:37 +05:30
|
|
|
this.field = field;
|
|
|
|
this.isLocalStorageAvailable = AccessorUtilities.isLocalStorageAccessSafe();
|
2018-03-17 18:26:18 +05:30
|
|
|
this.resource = resource;
|
2017-08-17 22:00:37 +05:30
|
|
|
if (key.join != null) {
|
2018-03-17 18:26:18 +05:30
|
|
|
key = key.join('/');
|
2017-08-17 22:00:37 +05:30
|
|
|
}
|
2018-03-17 18:26:18 +05:30
|
|
|
this.key = 'autosave/' + key;
|
|
|
|
this.field.data('autosave', this);
|
2017-08-17 22:00:37 +05:30
|
|
|
this.restore();
|
2018-03-17 18:26:18 +05:30
|
|
|
this.field.on('input', () => this.save());
|
2017-08-17 22:00:37 +05:30
|
|
|
}
|
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
restore() {
|
2017-08-17 22:00:37 +05:30
|
|
|
var text;
|
|
|
|
|
|
|
|
if (!this.isLocalStorageAvailable) return;
|
|
|
|
|
|
|
|
text = window.localStorage.getItem(this.key);
|
|
|
|
|
|
|
|
if ((text != null ? text.length : void 0) > 0) {
|
|
|
|
this.field.val(text);
|
2016-09-13 17:45:13 +05:30
|
|
|
}
|
2018-03-17 18:26:18 +05:30
|
|
|
if (!this.resource && this.resource !== 'issue') {
|
|
|
|
this.field.trigger('input');
|
|
|
|
} else {
|
|
|
|
// v-model does not update with jQuery trigger
|
|
|
|
// https://github.com/vuejs/vue/issues/2804#issuecomment-216968137
|
|
|
|
const event = new Event('change', { bubbles: true, cancelable: false });
|
|
|
|
const field = this.field.get(0);
|
|
|
|
if (field) {
|
|
|
|
field.dispatchEvent(event);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
save() {
|
2017-08-17 22:00:37 +05:30
|
|
|
var text;
|
|
|
|
text = this.field.val();
|
|
|
|
|
|
|
|
if (this.isLocalStorageAvailable && (text != null ? text.length : void 0) > 0) {
|
|
|
|
return window.localStorage.setItem(this.key, text);
|
|
|
|
}
|
|
|
|
|
|
|
|
return this.reset();
|
2018-03-17 18:26:18 +05:30
|
|
|
}
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
reset() {
|
2017-08-17 22:00:37 +05:30
|
|
|
if (!this.isLocalStorageAvailable) return;
|
|
|
|
|
|
|
|
return window.localStorage.removeItem(this.key);
|
2018-03-17 18:26:18 +05:30
|
|
|
}
|
|
|
|
}
|