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.

BaseApp.js 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. // @flow
  2. import _ from 'lodash';
  3. import React, { Component, Fragment } from 'react';
  4. import { I18nextProvider } from 'react-i18next';
  5. import { Provider } from 'react-redux';
  6. import { compose, createStore } from 'redux';
  7. import Thunk from 'redux-thunk';
  8. import { i18next } from '../../i18n';
  9. import {
  10. MiddlewareRegistry,
  11. ReducerRegistry,
  12. StateListenerRegistry
  13. } from '../../redux';
  14. import { SoundCollection } from '../../sounds';
  15. import { PersistenceRegistry } from '../../storage';
  16. import { appWillMount, appWillUnmount } from '../actions';
  17. import logger from '../logger';
  18. declare var APP: Object;
  19. /**
  20. * The type of the React {@code Component} state of {@link BaseApp}.
  21. */
  22. type State = {
  23. /**
  24. * The {@code Route} rendered by the {@code BaseApp}.
  25. */
  26. route: Object,
  27. /**
  28. * The redux store used by the {@code BaseApp}.
  29. */
  30. store: Object
  31. };
  32. /**
  33. * Base (abstract) class for main App component.
  34. *
  35. * @abstract
  36. */
  37. export default class BaseApp extends Component<*, State> {
  38. _init: Promise<*>;
  39. /**
  40. * Initializes a new {@code BaseApp} instance.
  41. *
  42. * @param {Object} props - The read-only React {@code Component} props with
  43. * which the new instance is to be initialized.
  44. */
  45. constructor(props: Object) {
  46. super(props);
  47. this.state = {
  48. route: {},
  49. store: undefined
  50. };
  51. }
  52. /**
  53. * Initializes the app.
  54. *
  55. * @inheritdoc
  56. */
  57. componentDidMount() {
  58. /**
  59. * Make the mobile {@code BaseApp} wait until the {@code AsyncStorage}
  60. * implementation of {@code Storage} initializes fully.
  61. *
  62. * @private
  63. * @see {@link #_initStorage}
  64. * @type {Promise}
  65. */
  66. this._init = this._initStorage()
  67. .catch(err => {
  68. /* BaseApp should always initialize! */
  69. logger.error(err);
  70. })
  71. .then(() => new Promise(resolve => {
  72. this.setState({
  73. store: this._createStore()
  74. }, resolve);
  75. }))
  76. .then(() => this.state.store.dispatch(appWillMount(this)))
  77. .catch(err => {
  78. /* BaseApp should always initialize! */
  79. logger.error(err);
  80. });
  81. }
  82. /**
  83. * De-initializes the app.
  84. *
  85. * @inheritdoc
  86. */
  87. componentWillUnmount() {
  88. this.state.store.dispatch(appWillUnmount(this));
  89. }
  90. /**
  91. * Delays this {@code BaseApp}'s startup until the {@code Storage}
  92. * implementation of {@code localStorage} initializes. While the
  93. * initialization is instantaneous on Web (with Web Storage API), it is
  94. * asynchronous on mobile/react-native.
  95. *
  96. * @private
  97. * @returns {Promise}
  98. */
  99. _initStorage(): Promise<*> {
  100. const { _initializing } = window.localStorage;
  101. return _initializing || Promise.resolve();
  102. }
  103. /**
  104. * Implements React's {@link Component#render()}.
  105. *
  106. * @inheritdoc
  107. * @returns {ReactElement}
  108. */
  109. render() {
  110. const { route: { component }, store } = this.state;
  111. if (store) {
  112. return (
  113. <I18nextProvider i18n = { i18next }>
  114. <Provider store = { store }>
  115. <Fragment>
  116. { this._createMainElement(component) }
  117. <SoundCollection />
  118. { this._createExtraElement() }
  119. { this._renderDialogContainer() }
  120. </Fragment>
  121. </Provider>
  122. </I18nextProvider>
  123. );
  124. }
  125. return null;
  126. }
  127. /**
  128. * Creates an extra {@link ReactElement}s to be added (unconditionaly)
  129. * alongside the main element.
  130. *
  131. * @returns {ReactElement}
  132. * @abstract
  133. * @protected
  134. */
  135. _createExtraElement() {
  136. return null;
  137. }
  138. /**
  139. * Creates a {@link ReactElement} from the specified component, the
  140. * specified props and the props of this {@code AbstractApp} which are
  141. * suitable for propagation to the children of this {@code Component}.
  142. *
  143. * @param {Component} component - The component from which the
  144. * {@code ReactElement} is to be created.
  145. * @param {Object} props - The read-only React {@code Component} props with
  146. * which the {@code ReactElement} is to be initialized.
  147. * @returns {ReactElement}
  148. * @protected
  149. */
  150. _createMainElement(component, props) {
  151. return component ? React.createElement(component, props || {}) : null;
  152. }
  153. /**
  154. * Initializes a new redux store instance suitable for use by this
  155. * {@code AbstractApp}.
  156. *
  157. * @private
  158. * @returns {Store} - A new redux store instance suitable for use by
  159. * this {@code AbstractApp}.
  160. */
  161. _createStore() {
  162. // Create combined reducer from all reducers in ReducerRegistry.
  163. const reducer = ReducerRegistry.combineReducers();
  164. // Apply all registered middleware from the MiddlewareRegistry and
  165. // additional 3rd party middleware:
  166. // - Thunk - allows us to dispatch async actions easily. For more info
  167. // @see https://github.com/gaearon/redux-thunk.
  168. let middleware = MiddlewareRegistry.applyMiddleware(Thunk);
  169. // Try to enable Redux DevTools Chrome extension in order to make it
  170. // available for the purposes of facilitating development.
  171. let devToolsExtension;
  172. if (typeof window === 'object'
  173. && (devToolsExtension = window.devToolsExtension)) {
  174. middleware = compose(middleware, devToolsExtension());
  175. }
  176. const store = createStore(
  177. reducer, PersistenceRegistry.getPersistedState(), middleware);
  178. // StateListenerRegistry
  179. StateListenerRegistry.subscribe(store);
  180. // This is temporary workaround to be able to dispatch actions from
  181. // non-reactified parts of the code (conference.js for example).
  182. // Don't use in the react code!!!
  183. // FIXME: remove when the reactification is finished!
  184. if (typeof APP !== 'undefined') {
  185. APP.store = store;
  186. }
  187. return store;
  188. }
  189. /**
  190. * Navigates to a specific Route.
  191. *
  192. * @param {Route} route - The Route to which to navigate.
  193. * @returns {Promise}
  194. */
  195. _navigate(route): Promise<*> {
  196. if (_.isEqual(route, this.state.route)) {
  197. return Promise.resolve();
  198. }
  199. if (route.href) {
  200. // This navigation requires loading a new URL in the browser.
  201. window.location.href = route.href;
  202. return Promise.resolve();
  203. }
  204. // XXX React's setState is asynchronous which means that the value of
  205. // this.state.route above may not even be correct. If the check is
  206. // performed before setState completes, the app may not navigate to the
  207. // expected route. In order to mitigate the problem, _navigate was
  208. // changed to return a Promise.
  209. return new Promise(resolve => {
  210. this.setState({ route }, resolve);
  211. });
  212. }
  213. /**
  214. * Renders the platform specific dialog container.
  215. *
  216. * @returns {React$Element}
  217. */
  218. _renderDialogContainer: () => React$Element<*>
  219. }