2016-08-25 21:17:09 +02:00
|
|
|
const inherits = require('util').inherits
|
|
|
|
const Component = require('react').Component
|
|
|
|
const defaultKey = 'persistent-form-default'
|
2016-08-25 23:23:41 +02:00
|
|
|
const eventName = 'keyup'
|
2016-08-25 21:17:09 +02:00
|
|
|
|
|
|
|
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()
|
2016-08-30 02:34:29 +02:00
|
|
|
|
2019-12-03 15:52:01 +01:00
|
|
|
for (let i = 0; i < fields.length; i++) {
|
2016-08-30 02:34:29 +02:00
|
|
|
const field = fields[i]
|
2016-08-25 21:17:09 +02:00
|
|
|
const key = field.getAttribute('data-persistent-formid')
|
|
|
|
const cached = store[key]
|
|
|
|
if (cached !== undefined) {
|
|
|
|
field.value = cached
|
|
|
|
}
|
|
|
|
|
|
|
|
field.addEventListener(eventName, this.persistentFieldDidUpdate.bind(this))
|
2016-08-30 02:34:29 +02:00
|
|
|
}
|
2016-08-25 21:17:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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]')
|
2019-12-03 15:52:01 +01:00
|
|
|
for (let i = 0; i < fields.length; i++) {
|
2016-08-30 02:34:29 +02:00
|
|
|
const field = fields[i]
|
2016-08-25 21:17:09 +02:00
|
|
|
field.removeEventListener(eventName, this.persistentFieldDidUpdate.bind(this))
|
2016-08-30 02:34:29 +02:00
|
|
|
}
|
2016-08-25 21:17:09 +02:00
|
|
|
this.setPersistentStore({})
|
|
|
|
}
|
2016-08-30 01:40:57 +02:00
|
|
|
|