Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

BaseApp.js 7.3KB

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