2018-06-16 09:20:30 -04:00
|
|
|
/* eslint-disable no-param-reassign, prefer-template, no-void, consistent-return */
|
2017-10-12 12:31:29 -04:00
|
|
|
|
2017-05-05 13:59:41 -04:00
|
|
|
import AccessorUtilities from './lib/utils/accessor';
|
2016-07-24 16:45:11 -04:00
|
|
|
|
2017-10-12 12:31:29 -04:00
|
|
|
export default class Autosave {
|
2018-02-27 19:10:43 -05:00
|
|
|
constructor(field, key) {
|
2017-03-11 02:30:44 -05:00
|
|
|
this.field = field;
|
2018-02-27 19:10:43 -05:00
|
|
|
|
2017-05-05 13:59:41 -04:00
|
|
|
this.isLocalStorageAvailable = AccessorUtilities.isLocalStorageAccessSafe();
|
2017-03-11 02:30:44 -05:00
|
|
|
if (key.join != null) {
|
2017-08-13 07:02:31 -04:00
|
|
|
key = key.join('/');
|
2017-03-11 02:30:44 -05:00
|
|
|
}
|
2017-08-13 07:02:31 -04:00
|
|
|
this.key = 'autosave/' + key;
|
|
|
|
this.field.data('autosave', this);
|
2017-03-11 02:30:44 -05:00
|
|
|
this.restore();
|
2018-07-17 19:58:01 -04:00
|
|
|
this.field.on('input', () => this.save());
|
2017-03-11 02:30:44 -05:00
|
|
|
}
|
2016-07-24 16:45:11 -04:00
|
|
|
|
2017-10-12 12:31:29 -04:00
|
|
|
restore() {
|
2017-05-05 13:59:41 -04:00
|
|
|
if (!this.isLocalStorageAvailable) return;
|
2018-02-27 19:10:43 -05:00
|
|
|
if (!this.field.length) return;
|
2017-05-05 13:59:41 -04:00
|
|
|
|
2018-02-27 19:10:43 -05:00
|
|
|
const text = window.localStorage.getItem(this.key);
|
2017-05-05 13:59:41 -04:00
|
|
|
|
2017-03-11 02:30:44 -05:00
|
|
|
if ((text != null ? text.length : void 0) > 0) {
|
|
|
|
this.field.val(text);
|
|
|
|
}
|
2018-02-27 19:10:43 -05:00
|
|
|
|
|
|
|
this.field.trigger('input');
|
|
|
|
// 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);
|
2018-06-21 08:22:40 -04:00
|
|
|
if (field) {
|
|
|
|
field.dispatchEvent(event);
|
|
|
|
}
|
2017-10-12 12:31:29 -04:00
|
|
|
}
|
2016-07-24 16:45:11 -04:00
|
|
|
|
2017-10-12 12:31:29 -04:00
|
|
|
save() {
|
2018-02-27 19:10:43 -05:00
|
|
|
if (!this.field.length) return;
|
|
|
|
|
|
|
|
const text = this.field.val();
|
2017-05-05 13:59:41 -04:00
|
|
|
|
|
|
|
if (this.isLocalStorageAvailable && (text != null ? text.length : void 0) > 0) {
|
|
|
|
return window.localStorage.setItem(this.key, text);
|
2017-03-11 02:30:44 -05:00
|
|
|
}
|
2017-05-05 13:59:41 -04:00
|
|
|
|
|
|
|
return this.reset();
|
2017-10-12 12:31:29 -04:00
|
|
|
}
|
2017-03-11 02:30:44 -05:00
|
|
|
|
2017-10-12 12:31:29 -04:00
|
|
|
reset() {
|
2017-05-05 13:59:41 -04:00
|
|
|
if (!this.isLocalStorageAvailable) return;
|
|
|
|
|
|
|
|
return window.localStorage.removeItem(this.key);
|
2017-10-12 12:31:29 -04:00
|
|
|
}
|
2018-07-31 15:24:16 -04:00
|
|
|
|
|
|
|
dispose() {
|
|
|
|
this.field.off('input');
|
|
|
|
}
|
2017-10-12 12:31:29 -04:00
|
|
|
}
|