Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

BaseApp.tsx 8.3KB

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