You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RouteRegistry.js 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * Object describing application route.
  3. *
  4. * @typedef {Object} Route
  5. * @property {Component} component - React Component constructor.
  6. * @property {string} path - URL route, required for web routing.
  7. */
  8. /**
  9. * A registry for Navigator routes, allowing features to register themselves
  10. * without needing to create additional inter-feature dependencies.
  11. */
  12. class RouteRegistry {
  13. /**
  14. * Method checking whether route objects are equal by value. Returns true if
  15. * and only if key values of the first object are equal to key values of
  16. * the second one.
  17. *
  18. * @param {Object} newRoute - New route object to be compared.
  19. * @param {Object} oldRoute - Old route object to be compared.
  20. * @returns {boolean}
  21. */
  22. areRoutesEqual(newRoute, oldRoute) {
  23. return Object.keys(newRoute)
  24. .every(key => newRoute[key] === oldRoute[key]);
  25. }
  26. /**
  27. * Initializes a new RouteRegistry instance.
  28. */
  29. constructor() {
  30. /**
  31. * The set of registered routes.
  32. *
  33. * @private
  34. */
  35. this._routeRegistry = new Set();
  36. }
  37. /**
  38. * Returns all registered routes.
  39. *
  40. * @returns {Route[]}
  41. */
  42. getRoutes() {
  43. // We use the destructuring operator to 'clone' the route object to
  44. // prevent modifications from outside (e.g. React Native's Navigator
  45. // extends it with additional properties).
  46. return [ ...this._routeRegistry ].map(r => {
  47. return { ...r };
  48. });
  49. }
  50. /**
  51. * Returns registered route by name if any.
  52. *
  53. * @param {Object} component - The React Component (class) of the route to
  54. * retrieve.
  55. * @returns {Route|null}
  56. */
  57. getRouteByComponent(component) {
  58. const route
  59. = [ ...this._routeRegistry ].find(r => r.component === component);
  60. // We use destructuring operator to 'clone' route object to prevent
  61. // modifications from outside (e.g. React Native's Navigator extends
  62. // it with some additional properties).
  63. return route ? { ...route } : null;
  64. }
  65. /**
  66. * Adds a route to this registry.
  67. *
  68. * @param {Route} route - Route definition object.
  69. * @returns {void}
  70. */
  71. register(route) {
  72. if (this._routeRegistry.has(route)) {
  73. throw new Error(`Route ${route.component} is registered already!`);
  74. }
  75. this._routeRegistry.add(route);
  76. }
  77. }
  78. /**
  79. * The public singleton instance of the RouteRegistry class.
  80. */
  81. export default new RouteRegistry();