speedscope/reloadable.tsx

41 lines
1.1 KiB
TypeScript
Raw Normal View History

import {Component} from 'preact'
2017-12-23 21:37:56 +03:00
export interface SerializedComponent<S> {
2017-12-23 21:37:56 +03:00
state: S
serializedSubcomponents: {[key: string]: any}
2017-12-23 21:37:56 +03:00
}
export abstract class ReloadableComponent<P, S> extends Component<P, S> {
serialize(): SerializedComponent<S> {
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,
}
}
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-23 21:37:56 +03:00
}
subcomponents(): {[key: string]: any} {
2017-12-23 21:37:56 +03:00
return Object.create(null)
}
}