gitlab-org--gitlab-foss/app/assets/javascripts/autosave.js

69 lines
1.7 KiB
JavaScript
Raw Normal View History

/* eslint-disable no-param-reassign, consistent-return */
2017-05-05 13:59:41 -04:00
import AccessorUtilities from './lib/utils/accessor';
2016-07-24 16:45:11 -04:00
export default class Autosave {
constructor(field, key, fallbackKey) {
this.field = field;
2017-05-05 13:59:41 -04:00
this.isLocalStorageAvailable = AccessorUtilities.isLocalStorageAccessSafe();
if (key.join != null) {
key = key.join('/');
}
this.key = `autosave/${key}`;
this.fallbackKey = fallbackKey;
this.field.data('autosave', this);
this.restore();
2018-07-17 19:58:01 -04:00
this.field.on('input', () => this.save());
}
2016-07-24 16:45:11 -04:00
restore() {
2017-05-05 13:59:41 -04:00
if (!this.isLocalStorageAvailable) return;
if (!this.field.length) return;
2017-05-05 13:59:41 -04:00
const text = window.localStorage.getItem(this.key);
const fallbackText = window.localStorage.getItem(this.fallbackKey);
2017-05-05 13:59:41 -04:00
if (text) {
this.field.val(text);
} else if (fallbackText) {
this.field.val(fallbackText);
}
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);
}
}
2016-07-24 16:45:11 -04:00
save() {
if (!this.field.length) return;
const text = this.field.val();
2017-05-05 13:59:41 -04:00
if (this.isLocalStorageAvailable && text) {
if (this.fallbackKey) {
window.localStorage.setItem(this.fallbackKey, text);
}
2017-05-05 13:59:41 -04:00
return window.localStorage.setItem(this.key, text);
}
2017-05-05 13:59:41 -04:00
return this.reset();
}
reset() {
2017-05-05 13:59:41 -04:00
if (!this.isLocalStorageAvailable) return;
window.localStorage.removeItem(this.fallbackKey);
2017-05-05 13:59:41 -04:00
return window.localStorage.removeItem(this.key);
}
dispose() {
this.field.off('input');
}
}