aboutsummaryrefslogtreecommitdiffstats
path: root/ui/lib/persistent-form.js
blob: d4dc20b0300d86eea48d2a785b8b0feed04e9d9c (plain) (blame)
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
const inherits = require('util').inherits
const Component = require('react').Component
const defaultKey = 'persistent-form-default'
const eventName = 'keyup'

module.exports = PersistentForm

function PersistentForm () {
  Component.call(this)
}

inherits(PersistentForm, Component)

PersistentForm.prototype.componentDidMount = function () {
  const fields = document.querySelectorAll('[data-persistent-formid]')
  const store = this.getPersistentStore()

  for (var i = 0; i < fields.length; i++) {
    const field = fields[i]
    const key = field.getAttribute('data-persistent-formid')
    const cached = store[key]
    if (cached !== undefined) {
      field.value = cached
    }

    field.addEventListener(eventName, this.persistentFieldDidUpdate.bind(this))
  }
}

PersistentForm.prototype.getPersistentStore = function () {
  let store = window.localStorage[this.persistentFormParentId || defaultKey]
  if (store && store !== 'null') {
    store = JSON.parse(store)
  } else {
    store = {}
  }
  return store
}

PersistentForm.prototype.setPersistentStore = function (newStore) {
  window.localStorage[this.persistentFormParentId || defaultKey] = JSON.stringify(newStore)
}

PersistentForm.prototype.persistentFieldDidUpdate = function (event) {
  const field = event.target
  const store = this.getPersistentStore()
  const key = field.getAttribute('data-persistent-formid')
  const val = field.value
  store[key] = val
  this.setPersistentStore(store)
}

PersistentForm.prototype.componentWillUnmount = function () {
  const fields = document.querySelectorAll('[data-persistent-formid]')
  for (var i = 0; i < fields.length; i++) {
    const field = fields[i]
    field.removeEventListener(eventName, this.persistentFieldDidUpdate.bind(this))
  }
  this.setPersistentStore({})
}