3
0

ModuleSystem.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import React from 'react';
  2. import Module from '../Module';
  3. import { Resolver } from '../Types';
  4. export default class ModuleSystem {
  5. constructor() {
  6. this.constructors = {};
  7. this.refs = {};
  8. }
  9. isAcceptedModule(ctor) {
  10. return (ctor.prototype instanceof Module ||
  11. ctor.prototype instanceof React.Component ||
  12. typeof ctor === "function");
  13. }
  14. loadModule(name, ctor, namespace = "default") {
  15. // Load a Module constructor
  16. if(!this.isAcceptedModule(ctor)){
  17. throw new Error("This is not a module: ", ctor);
  18. }
  19. if(!this.constructors[namespace])
  20. this.constructors[namespace] = {};
  21. if(this.constructors[namespace][name]) {
  22. log("Duplicate module: ", ctor);
  23. return true;
  24. }
  25. this.constructors[namespace][name] = ctor;
  26. }
  27. load(Dictionary, Namespace = "default") {
  28. for(var i in Dictionary) {
  29. let ctor = Dictionary[i];
  30. if(!this.isAcceptedModule(ctor) && typeof ctor === "object"){
  31. console.log("Loading new namespace : " , i);
  32. this.load(Dictionary[i], i);
  33. } else if (this.isAcceptedModule(ctor)) {
  34. this.loadModule(i, Dictionary[i], Namespace);
  35. }
  36. }
  37. }
  38. list() {
  39. return this.constructors;
  40. }
  41. get(modName, namespace = "default") {
  42. return this.constructors[namespace][modName];
  43. }
  44. fromViewNode(vn) {
  45. return this.get(vn.value, vn.namespace);
  46. }
  47. createRef(id) {
  48. !this.refs[id] && (this.refs[id] = React.createRef());
  49. return this.refs[id];
  50. }
  51. getRef(id) {
  52. return this.refs[id];
  53. }
  54. createElement(name, props, children, namespace = "default", ref) {
  55. let ctor = this.get(name, namespace);
  56. return this.createElementCtor(ctor, props, children, ref);
  57. }
  58. createElementCtor(ctor, props, children, ref) {
  59. let validatedProps = this.validateProps(ctor, props);
  60. if (ref) {
  61. validatedProps = {
  62. ...validatedProps,
  63. ref: this.refs[ref]
  64. }
  65. }
  66. return React.createElement(ctor, validatedProps, children);
  67. }
  68. validateProps(ctor, props = {}) {
  69. let res = {};
  70. if(ctor && ctor.Inputs) {
  71. res = Resolver(ctor.Inputs, props);
  72. }
  73. return {
  74. ...props,
  75. ...res
  76. }
  77. }
  78. }