3
0

ModuleSystem.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. console.log(this.constructors);
  38. }
  39. list() {
  40. return this.constructors;
  41. }
  42. get(modName, namespace = "default") {
  43. return this.constructors[namespace][modName];
  44. }
  45. fromViewNode(vn) {
  46. return this.get(vn.value, vn.namespace);
  47. }
  48. createRef(id) {
  49. !this.refs[id] && (this.refs[id] = React.createRef());
  50. return this.refs[id];
  51. }
  52. getRef(id) {
  53. return this.refs[id];
  54. }
  55. createElement(name, props, children, namespace = "default", ref) {
  56. let ctor = this.get(name, namespace);
  57. return this.createElementCtor(ctor, props, children, ref);
  58. }
  59. createElementCtor(ctor, props, children, ref) {
  60. let validatedProps = this.validateProps(ctor, props);
  61. if (ref) {
  62. validatedProps = {
  63. ...validatedProps,
  64. ref: this.refs[ref]
  65. }
  66. }
  67. return React.createElement(ctor, validatedProps, children);
  68. }
  69. validateProps(ctor, props = {}) {
  70. let res = {};
  71. if(ctor && ctor.Inputs) {
  72. res = Resolver(ctor.Inputs, props);
  73. }
  74. return {
  75. ...props,
  76. ...res
  77. }
  78. }
  79. }