ng_react.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. //
  2. // This is using ng-react with this PR applied https://github.com/ngReact/ngReact/pull/199
  3. //
  4. // # ngReact
  5. // ### Use React Components inside of your Angular applications
  6. //
  7. // Composed of
  8. // - reactComponent (generic directive for delegating off to React Components)
  9. // - reactDirective (factory for creating specific directives that correspond to reactComponent directives)
  10. import React from 'react';
  11. import ReactDOM from 'react-dom';
  12. import angular from 'angular';
  13. // get a react component from name (components can be an angular injectable e.g. value, factory or
  14. // available on window
  15. function getReactComponent(name, $injector) {
  16. // if name is a function assume it is component and return it
  17. if (angular.isFunction(name)) {
  18. return name;
  19. }
  20. // a React component name must be specified
  21. if (!name) {
  22. throw new Error('ReactComponent name attribute must be specified');
  23. }
  24. // ensure the specified React component is accessible, and fail fast if it's not
  25. var reactComponent;
  26. try {
  27. reactComponent = $injector.get(name);
  28. } catch (e) {}
  29. if (!reactComponent) {
  30. try {
  31. reactComponent = name.split('.').reduce(function(current, namePart) {
  32. return current[namePart];
  33. }, window);
  34. } catch (e) {}
  35. }
  36. if (!reactComponent) {
  37. throw Error('Cannot find react component ' + name);
  38. }
  39. return reactComponent;
  40. }
  41. // wraps a function with scope.$apply, if already applied just return
  42. function applied(fn, scope) {
  43. if (fn.wrappedInApply) {
  44. return fn;
  45. }
  46. var wrapped: any = function() {
  47. var args = arguments;
  48. var phase = scope.$root.$$phase;
  49. if (phase === '$apply' || phase === '$digest') {
  50. return fn.apply(null, args);
  51. } else {
  52. return scope.$apply(function() {
  53. return fn.apply(null, args);
  54. });
  55. }
  56. };
  57. wrapped.wrappedInApply = true;
  58. return wrapped;
  59. }
  60. /**
  61. * wraps functions on obj in scope.$apply
  62. *
  63. * keeps backwards compatibility, as if propsConfig is not passed, it will
  64. * work as before, wrapping all functions and won't wrap only when specified.
  65. *
  66. * @version 0.4.1
  67. * @param obj react component props
  68. * @param scope current scope
  69. * @param propsConfig configuration object for all properties
  70. * @returns {Object} props with the functions wrapped in scope.$apply
  71. */
  72. function applyFunctions(obj, scope, propsConfig?) {
  73. return Object.keys(obj || {}).reduce(function(prev, key) {
  74. var value = obj[key];
  75. var config = (propsConfig || {})[key] || {};
  76. /**
  77. * wrap functions in a function that ensures they are scope.$applied
  78. * ensures that when function is called from a React component
  79. * the Angular digest cycle is run
  80. */
  81. prev[key] = angular.isFunction(value) && config.wrapApply !== false ? applied(value, scope) : value;
  82. return prev;
  83. }, {});
  84. }
  85. /**
  86. *
  87. * @param watchDepth (value of HTML watch-depth attribute)
  88. * @param scope (angular scope)
  89. *
  90. * Uses the watchDepth attribute to determine how to watch props on scope.
  91. * If watchDepth attribute is NOT reference or collection, watchDepth defaults to deep watching by value
  92. */
  93. function watchProps(watchDepth, scope, watchExpressions, listener) {
  94. var supportsWatchCollection = angular.isFunction(scope.$watchCollection);
  95. var supportsWatchGroup = angular.isFunction(scope.$watchGroup);
  96. var watchGroupExpressions = [];
  97. watchExpressions.forEach(function(expr) {
  98. var actualExpr = getPropExpression(expr);
  99. var exprWatchDepth = getPropWatchDepth(watchDepth, expr);
  100. if (exprWatchDepth === 'collection' && supportsWatchCollection) {
  101. scope.$watchCollection(actualExpr, listener);
  102. } else if (exprWatchDepth === 'reference' && supportsWatchGroup) {
  103. watchGroupExpressions.push(actualExpr);
  104. } else if (exprWatchDepth === 'one-time') {
  105. //do nothing because we handle our one time bindings after this
  106. } else {
  107. scope.$watch(actualExpr, listener, exprWatchDepth !== 'reference');
  108. }
  109. });
  110. if (watchDepth === 'one-time') {
  111. listener();
  112. }
  113. if (watchGroupExpressions.length) {
  114. scope.$watchGroup(watchGroupExpressions, listener);
  115. }
  116. }
  117. // render React component, with scope[attrs.props] being passed in as the component props
  118. function renderComponent(component, props, scope, elem) {
  119. scope.$evalAsync(function() {
  120. ReactDOM.render(React.createElement(component, props), elem[0]);
  121. });
  122. }
  123. // get prop name from prop (string or array)
  124. function getPropName(prop) {
  125. return Array.isArray(prop) ? prop[0] : prop;
  126. }
  127. // get prop name from prop (string or array)
  128. function getPropConfig(prop) {
  129. return Array.isArray(prop) ? prop[1] : {};
  130. }
  131. // get prop expression from prop (string or array)
  132. function getPropExpression(prop) {
  133. return Array.isArray(prop) ? prop[0] : prop;
  134. }
  135. // find the normalized attribute knowing that React props accept any type of capitalization
  136. function findAttribute(attrs, propName) {
  137. var index = Object.keys(attrs).filter(function(attr) {
  138. return attr.toLowerCase() === propName.toLowerCase();
  139. })[0];
  140. return attrs[index];
  141. }
  142. // get watch depth of prop (string or array)
  143. function getPropWatchDepth(defaultWatch, prop) {
  144. var customWatchDepth = Array.isArray(prop) && angular.isObject(prop[1]) && prop[1].watchDepth;
  145. return customWatchDepth || defaultWatch;
  146. }
  147. // # reactComponent
  148. // Directive that allows React components to be used in Angular templates.
  149. //
  150. // Usage:
  151. // <react-component name="Hello" props="name"/>
  152. //
  153. // This requires that there exists an injectable or globally available 'Hello' React component.
  154. // The 'props' attribute is optional and is passed to the component.
  155. //
  156. // The following would would create and register the component:
  157. //
  158. // var module = angular.module('ace.react.components');
  159. // module.value('Hello', React.createClass({
  160. // render: function() {
  161. // return <div>Hello {this.props.name}</div>;
  162. // }
  163. // }));
  164. //
  165. var reactComponent = function($injector) {
  166. return {
  167. restrict: 'E',
  168. replace: true,
  169. link: function(scope, elem, attrs) {
  170. var reactComponent = getReactComponent(attrs.name, $injector);
  171. var renderMyComponent = function() {
  172. var scopeProps = scope.$eval(attrs.props);
  173. var props = applyFunctions(scopeProps, scope);
  174. renderComponent(reactComponent, props, scope, elem);
  175. };
  176. // If there are props, re-render when they change
  177. attrs.props ? watchProps(attrs.watchDepth, scope, [attrs.props], renderMyComponent) : renderMyComponent();
  178. // cleanup when scope is destroyed
  179. scope.$on('$destroy', function() {
  180. if (!attrs.onScopeDestroy) {
  181. ReactDOM.unmountComponentAtNode(elem[0]);
  182. } else {
  183. scope.$eval(attrs.onScopeDestroy, {
  184. unmountComponent: ReactDOM.unmountComponentAtNode.bind(this, elem[0]),
  185. });
  186. }
  187. });
  188. },
  189. };
  190. };
  191. // # reactDirective
  192. // Factory function to create directives for React components.
  193. //
  194. // With a component like this:
  195. //
  196. // var module = angular.module('ace.react.components');
  197. // module.value('Hello', React.createClass({
  198. // render: function() {
  199. // return <div>Hello {this.props.name}</div>;
  200. // }
  201. // }));
  202. //
  203. // A directive can be created and registered with:
  204. //
  205. // module.directive('hello', function(reactDirective) {
  206. // return reactDirective('Hello', ['name']);
  207. // });
  208. //
  209. // Where the first argument is the injectable or globally accessible name of the React component
  210. // and the second argument is an array of property names to be watched and passed to the React component
  211. // as props.
  212. //
  213. // This directive can then be used like this:
  214. //
  215. // <hello name="name"/>
  216. //
  217. var reactDirective = function($injector) {
  218. return function(reactComponentName, props, conf, injectableProps) {
  219. var directive = {
  220. restrict: 'E',
  221. replace: true,
  222. link: function(scope, elem, attrs) {
  223. var reactComponent = getReactComponent(reactComponentName, $injector);
  224. // if props is not defined, fall back to use the React component's propTypes if present
  225. props = props || Object.keys(reactComponent.propTypes || {});
  226. // for each of the properties, get their scope value and set it to scope.props
  227. var renderMyComponent = function() {
  228. var scopeProps = {},
  229. config = {};
  230. props.forEach(function(prop) {
  231. var propName = getPropName(prop);
  232. scopeProps[propName] = scope.$eval(findAttribute(attrs, propName));
  233. config[propName] = getPropConfig(prop);
  234. });
  235. scopeProps = applyFunctions(scopeProps, scope, config);
  236. scopeProps = angular.extend({}, scopeProps, injectableProps);
  237. renderComponent(reactComponent, scopeProps, scope, elem);
  238. };
  239. // watch each property name and trigger an update whenever something changes,
  240. // to update scope.props with new values
  241. var propExpressions = props.map(function(prop) {
  242. return Array.isArray(prop) ? [attrs[getPropName(prop)], getPropConfig(prop)] : attrs[prop];
  243. });
  244. // If we don't have any props, then our watch statement won't fire.
  245. props.length ? watchProps(attrs.watchDepth, scope, propExpressions, renderMyComponent) : renderMyComponent();
  246. // cleanup when scope is destroyed
  247. scope.$on('$destroy', function() {
  248. if (!attrs.onScopeDestroy) {
  249. ReactDOM.unmountComponentAtNode(elem[0]);
  250. } else {
  251. scope.$eval(attrs.onScopeDestroy, {
  252. unmountComponent: ReactDOM.unmountComponentAtNode.bind(this, elem[0]),
  253. });
  254. }
  255. });
  256. },
  257. };
  258. return angular.extend(directive, conf);
  259. };
  260. };
  261. let ngModule = angular.module('react', []);
  262. ngModule.directive('reactComponent', ['$injector', reactComponent]);
  263. ngModule.factory('reactDirective', ['$injector', reactDirective]);