summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/autosave.js
blob: 5f50fcc112e1242e771c06be5cf479983d7f210d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* eslint-disable no-param-reassign, consistent-return */

import AccessorUtilities from './lib/utils/accessor';

export default class Autosave {
  constructor(field, key, fallbackKey, lockVersion) {
    this.field = field;

    this.isLocalStorageAvailable = AccessorUtilities.isLocalStorageAccessSafe();
    if (key.join != null) {
      key = key.join('/');
    }
    this.key = `autosave/${key}`;
    this.fallbackKey = fallbackKey;
    this.lockVersionKey = `${this.key}/lockVersion`;
    this.lockVersion = lockVersion;
    this.field.data('autosave', this);
    this.restore();
    this.field.on('input', () => this.save());
  }

  restore() {
    if (!this.isLocalStorageAvailable) return;
    if (!this.field.length) return;

    const text = window.localStorage.getItem(this.key);
    const fallbackText = window.localStorage.getItem(this.fallbackKey);

    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);
    if (field) {
      field.dispatchEvent(event);
    }
  }

  getSavedLockVersion() {
    if (!this.isLocalStorageAvailable) return;
    return window.localStorage.getItem(this.lockVersionKey);
  }

  save() {
    if (!this.field.length) return;

    const text = this.field.val();

    if (this.isLocalStorageAvailable && text) {
      if (this.fallbackKey) {
        window.localStorage.setItem(this.fallbackKey, text);
      }
      if (this.lockVersion !== undefined) {
        window.localStorage.setItem(this.lockVersionKey, this.lockVersion);
      }
      return window.localStorage.setItem(this.key, text);
    }

    return this.reset();
  }

  reset() {
    if (!this.isLocalStorageAvailable) return;

    window.localStorage.removeItem(this.lockVersionKey);
    window.localStorage.removeItem(this.fallbackKey);
    return window.localStorage.removeItem(this.key);
  }

  dispose() {
    this.field.off('input');
  }
}