autosave.js 1.51 KB
Newer Older
1 2
/* eslint-disable no-param-reassign, prefer-template, no-var, no-void, consistent-return */

3
import AccessorUtilities from './lib/utils/accessor';
Fatih Acet's avatar
Fatih Acet committed
4

5 6
export default class Autosave {
  constructor(field, key, resource) {
7
    this.field = field;
8
    this.isLocalStorageAvailable = AccessorUtilities.isLocalStorageAccessSafe();
9
    this.resource = resource;
10
    if (key.join != null) {
11
      key = key.join('/');
12
    }
13 14
    this.key = 'autosave/' + key;
    this.field.data('autosave', this);
15
    this.restore();
16
    this.field.on('input', () => this.save());
17
  }
Fatih Acet's avatar
Fatih Acet committed
18

19
  restore() {
20 21 22 23 24 25
    var text;

    if (!this.isLocalStorageAvailable) return;

    text = window.localStorage.getItem(this.key);

26 27 28
    if ((text != null ? text.length : void 0) > 0) {
      this.field.val(text);
    }
29 30 31 32 33 34
    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 });
35 36 37 38
      const field = this.field.get(0);
      if (field) {
        field.dispatchEvent(event);
      }
39
    }
40
  }
Fatih Acet's avatar
Fatih Acet committed
41

42
  save() {
43 44
    var text;
    text = this.field.val();
45 46 47

    if (this.isLocalStorageAvailable && (text != null ? text.length : void 0) > 0) {
      return window.localStorage.setItem(this.key, text);
48
    }
49 50

    return this.reset();
51
  }
52

53
  reset() {
54 55 56
    if (!this.isLocalStorageAvailable) return;

    return window.localStorage.removeItem(this.key);
57 58
  }
}