summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/vue_shared/components/local_storage_sync.vue
blob: 33e77b6510c1f0d7fc6b26d2a9148f40c3b22f58 (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
80
81
82
83
84
85
<script>
import { isEqual } from 'lodash';

export default {
  props: {
    storageKey: {
      type: String,
      required: true,
    },
    value: {
      type: [String, Number, Boolean, Array, Object],
      required: false,
      default: '',
    },
    asJson: {
      type: Boolean,
      required: false,
      default: false,
    },
    persist: {
      type: Boolean,
      required: false,
      default: true,
    },
    clear: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  watch: {
    value(newVal) {
      this.saveValue(this.serialize(newVal));
    },
    clear(newVal) {
      if (newVal) {
        localStorage.removeItem(this.storageKey);
      }
    },
  },
  mounted() {
    // On mount, trigger update if we actually have a localStorageValue
    const { exists, value } = this.getStorageValue();

    if (exists && !isEqual(value, this.value)) {
      this.$emit('input', value);
    }
  },
  methods: {
    getStorageValue() {
      const value = localStorage.getItem(this.storageKey);

      if (value === null) {
        return { exists: false };
      }

      try {
        return { exists: true, value: this.deserialize(value) };
      } catch {
        // eslint-disable-next-line no-console
        console.warn(
          `[gitlab] Failed to deserialize value from localStorage (key=${this.storageKey})`,
          value,
        );
        // default to "don't use localStorage value"
        return { exists: false };
      }
    },
    saveValue(val) {
      if (!this.persist) return;

      localStorage.setItem(this.storageKey, val);
    },
    serialize(val) {
      return this.asJson ? JSON.stringify(val) : val;
    },
    deserialize(val) {
      return this.asJson ? JSON.parse(val) : val;
    },
  },
  render() {
    return this.$slots.default;
  },
};
</script>