2020-01-09 04:34:58 +01:00
|
|
|
import ObservableStore from 'obs-store'
|
2018-04-13 05:26:50 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* An ObservableStore that can composes a flat
|
|
|
|
* structure of child stores based on configuration
|
|
|
|
*/
|
2020-05-06 00:19:38 +02:00
|
|
|
export default class ComposableObservableStore extends ObservableStore {
|
2018-04-13 05:26:50 +02:00
|
|
|
/**
|
|
|
|
* Create a new store
|
|
|
|
*
|
|
|
|
* @param {Object} [initState] - The initial store state
|
|
|
|
* @param {Object} [config] - Map of internal state keys to child stores
|
|
|
|
*/
|
2020-11-03 00:41:28 +01:00
|
|
|
constructor(initState, config) {
|
2018-04-13 19:13:36 +02:00
|
|
|
super(initState)
|
|
|
|
this.updateStructure(config)
|
|
|
|
}
|
2018-04-13 05:26:50 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Composes a new internal store subscription structure
|
|
|
|
*
|
|
|
|
* @param {Object} [config] - Map of internal state keys to child stores
|
|
|
|
*/
|
2020-11-03 00:41:28 +01:00
|
|
|
updateStructure(config) {
|
2018-04-13 05:26:50 +02:00
|
|
|
this.config = config
|
2018-04-13 19:13:36 +02:00
|
|
|
this.removeAllListeners()
|
|
|
|
for (const key in config) {
|
2020-08-13 22:34:51 +02:00
|
|
|
if (Object.prototype.hasOwnProperty.call(config, key)) {
|
2020-07-21 23:10:45 +02:00
|
|
|
config[key].subscribe((state) => {
|
|
|
|
this.updateState({ [key]: state })
|
|
|
|
})
|
|
|
|
}
|
2018-04-13 19:13:36 +02:00
|
|
|
}
|
2018-04-13 05:26:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Merges all child store state into a single object rather than
|
|
|
|
* returning an object keyed by child store class name
|
|
|
|
*
|
2020-11-10 18:30:41 +01:00
|
|
|
* @returns {Object} Object containing merged child store state
|
2018-04-13 05:26:50 +02:00
|
|
|
*/
|
2020-11-03 00:41:28 +01:00
|
|
|
getFlatState() {
|
2018-04-13 05:26:50 +02:00
|
|
|
let flatState = {}
|
|
|
|
for (const key in this.config) {
|
2020-08-13 22:34:51 +02:00
|
|
|
if (Object.prototype.hasOwnProperty.call(this.config, key)) {
|
2020-07-21 23:10:45 +02:00
|
|
|
const controller = this.config[key]
|
2020-11-03 00:41:28 +01:00
|
|
|
const state = controller.getState
|
|
|
|
? controller.getState()
|
|
|
|
: controller.state
|
2020-07-21 23:10:45 +02:00
|
|
|
flatState = { ...flatState, ...state }
|
|
|
|
}
|
2018-04-13 05:26:50 +02:00
|
|
|
}
|
|
|
|
return flatState
|
|
|
|
}
|
|
|
|
}
|