2018-04-15 02:18:50 +03:00
|
|
|
import {Component} from 'preact'
|
2017-12-23 21:37:56 +03:00
|
|
|
|
2018-01-24 10:48:13 +03:00
|
|
|
export interface SerializedComponent<S> {
|
2017-12-23 21:37:56 +03:00
|
|
|
state: S
|
2018-04-15 02:18:50 +03:00
|
|
|
serializedSubcomponents: {[key: string]: any}
|
2017-12-23 21:37:56 +03:00
|
|
|
}
|
|
|
|
|
2017-12-26 19:49:25 +03:00
|
|
|
export abstract class ReloadableComponent<P, S> extends Component<P, S> {
|
|
|
|
serialize(): SerializedComponent<S> {
|
2018-04-15 02:18:50 +03:00
|
|
|
const serializedSubcomponents: {[key: string]: any} = Object.create(null)
|
2017-12-23 21:37:56 +03:00
|
|
|
|
|
|
|
const subcomponents = this.subcomponents()
|
|
|
|
for (const key in subcomponents) {
|
|
|
|
const val = subcomponents[key]
|
|
|
|
if (val && val instanceof ReloadableComponent) {
|
|
|
|
serializedSubcomponents[key] = val.serialize()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
state: this.state,
|
|
|
|
serializedSubcomponents,
|
|
|
|
}
|
|
|
|
}
|
2017-12-26 19:49:25 +03:00
|
|
|
rehydrate(serialized: SerializedComponent<S>) {
|
|
|
|
this.setState(serialized.state, () => {
|
|
|
|
const subcomponents = this.subcomponents()
|
|
|
|
for (const key in subcomponents) {
|
|
|
|
const val = subcomponents[key]
|
|
|
|
const data = serialized.serializedSubcomponents[key]
|
|
|
|
if (data && val && val instanceof ReloadableComponent) {
|
|
|
|
val.rehydrate(data)
|
|
|
|
}
|
2017-12-23 21:37:56 +03:00
|
|
|
}
|
2017-12-26 19:49:25 +03:00
|
|
|
})
|
2017-12-23 21:37:56 +03:00
|
|
|
}
|
2018-04-15 02:18:50 +03:00
|
|
|
subcomponents(): {[key: string]: any} {
|
2017-12-23 21:37:56 +03:00
|
|
|
return Object.create(null)
|
|
|
|
}
|
|
|
|
}
|