debian-mirror-gitlab/app/assets/javascripts/autosave.js

61 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-11-08 19:23:39 +05:30
/* eslint-disable no-param-reassign, prefer-template, no-void, consistent-return */
2018-03-17 18:26:18 +05:30
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 {
2018-03-27 19:54:05 +05:30
constructor(field, key) {
2017-08-17 22:00:37 +05:30
this.field = field;
2018-03-27 19:54:05 +05:30
2017-08-17 22:00:37 +05:30
this.isLocalStorageAvailable = AccessorUtilities.isLocalStorageAccessSafe();
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
if (!this.isLocalStorageAvailable) return;
2018-03-27 19:54:05 +05:30
if (!this.field.length) return;
2017-08-17 22:00:37 +05:30
2018-03-27 19:54:05 +05:30
const text = window.localStorage.getItem(this.key);
2017-08-17 22:00:37 +05:30
if ((text != null ? text.length : void 0) > 0) {
this.field.val(text);
2016-09-13 17:45:13 +05:30
}
2018-03-27 19:54:05 +05:30
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-11-08 19:23:39 +05:30
if (field) {
field.dispatchEvent(event);
}
2018-03-17 18:26:18 +05:30
}
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
save() {
2018-03-27 19:54:05 +05:30
if (!this.field.length) return;
const text = this.field.val();
2017-08-17 22:00:37 +05:30
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
}
2018-11-18 11:00:15 +05:30
dispose() {
this.field.off('input');
}
2018-03-17 18:26:18 +05:30
}