regular-redux-undo
Version:
the plugin of regular-redux to archieve undo and redo
60 lines (53 loc) • 1.49 kB
JavaScript
import Module from './module'
import { assert, forEachValue, typeOf} from '../util'
export default class ModuleCollection {
constructor(rawRootModule) {
//root module
this.root = Object.create(null);
//the rawRootModule is the options of regular-redux-store
this.register([], rawRootModule);
//check the state for structure
//when a module has a submodule, the state of this module need to be an object
this.root.checkState();
//combine the all module state for init
this.state = this.root.combineState();
}
/**
* register a module
* @param {Array} path
* @param {Object} rawModule
*/
register (path, rawModule) {
const newModule = new Module(rawModule, path);
if (path.length === 0) {
this.root = newModule;
} else {
const parent = this.get(path.slice(0, -1))
parent.addChild(path[path.length - 1], newModule)
}
// register nested modules
if (rawModule.modules) {
forEachValue(rawModule.modules, (rawChildModule, key) => {
this.register(path.concat(key), rawChildModule)
})
}
}
/**
* unregister a module
* @param {Array} path
*/
unregister (path) {
const parent = this.get(path.slice(0, -1));
const key = path[path.length - 1];
parent.removeChild(key);
}
/**
* get a module
* @param {Array} path
*/
get(path) {
return path.reduce((module, key) => {
return module.getChild(key)
}, this.root)
}
}