ModuleSystem.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. loadModule(name, ctor, namespace = "default") {
  10. // Load a Module constructor
  11. if(! ctor instanceof Module ){
  12. throw new Error("This is not a module: ", ctor);
  13. }
  14. if(!this.constructors[namespace])
  15. this.constructors[namespace] = {};
  16. if(this.constructors[namespace][name]) {
  17. log("Duplicate module: ", ctor);
  18. return true;
  19. }
  20. this.constructors[namespace][name] = ctor;
  21. }
  22. load(Dictionary, Namespace = "default") {
  23. for(var i in Dictionary) {
  24. this.loadModule(i, Dictionary[i], Namespace);
  25. }
  26. }
  27. list() {
  28. return this.constructors;
  29. }
  30. get(modName, namespace = "default") {
  31. return this.constructors[namespace][modName];
  32. }
  33. fromViewNode(vn) {
  34. return this.get(vn.value, vn.namespace);
  35. }
  36. createRef(id) {
  37. !this.refs[id] && (this.refs[id] = React.createRef());
  38. return this.refs[id];
  39. }
  40. getRef(id) {
  41. return this.refs[id];
  42. }
  43. createElement(name, props, children, namespace = "default", ref) {
  44. let ctor = this.get(name, namespace);
  45. return this.createElementCtor(ctor, props, children, ref);
  46. }
  47. createElementCtor(ctor, props, children, ref) {
  48. let validatedProps = this.validateProps(ctor, props);
  49. if (ref) {
  50. validatedProps = {
  51. ...validatedProps,
  52. ref: this.refs[ref]
  53. }
  54. }
  55. return React.createElement(ctor, validatedProps, children);
  56. }
  57. validateProps(ctor, props = {}) {
  58. let res = {};
  59. if(ctor && ctor.Inputs) {
  60. res = Resolver(ctor.Inputs, props);
  61. }
  62. return {
  63. ...props,
  64. ...res
  65. }
  66. }
  67. }