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

App.native.tsx 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import React, { ComponentType } from 'react';
  2. import { NativeModules, Platform, StyleSheet, View } from 'react-native';
  3. import DeviceInfo from 'react-native-device-info';
  4. import { SafeAreaProvider } from 'react-native-safe-area-context';
  5. import SplashScreen from 'react-native-splash-screen';
  6. import BottomSheetContainer from '../../base/dialog/components/native/BottomSheetContainer';
  7. import DialogContainer from '../../base/dialog/components/native/DialogContainer';
  8. import { updateFlags } from '../../base/flags/actions';
  9. import { CALL_INTEGRATION_ENABLED, SERVER_URL_CHANGE_ENABLED } from '../../base/flags/constants';
  10. import { getFeatureFlag } from '../../base/flags/functions';
  11. import { clientResized, setSafeAreaInsets } from '../../base/responsive-ui/actions';
  12. import DimensionsDetector from '../../base/responsive-ui/components/DimensionsDetector.native';
  13. import { updateSettings } from '../../base/settings/actions';
  14. import { _getRouteToRender } from '../getRouteToRender.native';
  15. import logger from '../logger';
  16. import { AbstractApp, IProps as AbstractAppProps } from './AbstractApp';
  17. // Register middlewares and reducers.
  18. import '../middlewares.native';
  19. import '../reducers.native';
  20. declare let __DEV__: any;
  21. const { AppInfo } = NativeModules;
  22. const DialogContainerWrapper = Platform.select({
  23. default: View
  24. });
  25. /**
  26. * The type of React {@code Component} props of {@link App}.
  27. */
  28. interface IProps extends AbstractAppProps {
  29. /**
  30. * An object with the feature flags.
  31. */
  32. flags: any;
  33. /**
  34. * An object with user information (display name, email, avatar URL).
  35. */
  36. userInfo?: Object;
  37. }
  38. /**
  39. * Root app {@code Component} on mobile/React Native.
  40. *
  41. * @augments AbstractApp
  42. */
  43. export class App extends AbstractApp<IProps> {
  44. /**
  45. * Initializes a new {@code App} instance.
  46. *
  47. * @param {IProps} props - The read-only React {@code Component} props with
  48. * which the new instance is to be initialized.
  49. */
  50. constructor(props: IProps) {
  51. super(props);
  52. // In the Release configuration, React Native will (intentionally) throw
  53. // an unhandled JavascriptException for an unhandled JavaScript error.
  54. // This will effectively kill the app. In accord with the Web, do not
  55. // kill the app.
  56. this._maybeDisableExceptionsManager();
  57. // Bind event handler so it is only bound once per instance.
  58. this._onDimensionsChanged = this._onDimensionsChanged.bind(this);
  59. this._onSafeAreaInsetsChanged = this._onSafeAreaInsetsChanged.bind(this);
  60. }
  61. /**
  62. * Initializes the color scheme.
  63. *
  64. * @inheritdoc
  65. *
  66. * @returns {void}
  67. */
  68. async componentDidMount() {
  69. await super.componentDidMount();
  70. SplashScreen.hide();
  71. const liteTxt = AppInfo.isLiteSDK ? ' (lite)' : '';
  72. logger.info(`Loaded SDK ${AppInfo.sdkVersion}${liteTxt}`);
  73. }
  74. /**
  75. * Initializes feature flags and updates settings.
  76. *
  77. * @returns {void}
  78. */
  79. async _extraInit() {
  80. const { dispatch, getState } = this.state.store ?? {};
  81. const { flags = {} } = this.props;
  82. // CallKit does not work on the simulator, make sure we disable it.
  83. if (Platform.OS === 'ios' && DeviceInfo.isEmulatorSync()) {
  84. flags['call-integration.enabled'] = false;
  85. logger.info('Disabling CallKit because this is a simulator');
  86. }
  87. // We set these early enough so then we avoid any unnecessary re-renders.
  88. dispatch?.(updateFlags(flags));
  89. const route = await _getRouteToRender();
  90. // We need the root navigator to be set early.
  91. await this._navigate(route);
  92. // HACK ALERT!
  93. // Wait until the root navigator is ready.
  94. // We really need to break the inheritance relationship between App,
  95. // AbstractApp and BaseApp, it's very inflexible and cumbersome right now.
  96. const rootNavigationReady = new Promise<void>(resolve => {
  97. const i = setInterval(() => {
  98. // @ts-ignore
  99. const { ready } = getState()['features/app'] || {};
  100. if (ready) {
  101. clearInterval(i);
  102. resolve();
  103. }
  104. }, 50);
  105. });
  106. await rootNavigationReady;
  107. // Check if serverURL is configured externally and not allowed to change.
  108. const serverURLChangeEnabled = getState && getFeatureFlag(getState(), SERVER_URL_CHANGE_ENABLED, true);
  109. if (!serverURLChangeEnabled) {
  110. // As serverURL is provided externally, so we push it to settings.
  111. if (typeof this.props.url !== 'undefined') {
  112. // @ts-ignore
  113. const { serverURL } = this.props.url;
  114. if (typeof serverURL !== 'undefined') {
  115. dispatch?.(updateSettings({ serverURL }));
  116. }
  117. }
  118. }
  119. dispatch?.(updateSettings(this.props.userInfo || {}));
  120. // Update settings with feature-flag.
  121. const callIntegrationEnabled = flags[CALL_INTEGRATION_ENABLED as keyof typeof flags];
  122. if (typeof callIntegrationEnabled !== 'undefined') {
  123. dispatch?.(updateSettings({ disableCallIntegration: !callIntegrationEnabled }));
  124. }
  125. }
  126. /**
  127. * Overrides the parent method to inject {@link DimensionsDetector} as
  128. * the top most component.
  129. *
  130. * @override
  131. */
  132. _createMainElement(component: ComponentType<any>, props: Object) {
  133. return (
  134. <SafeAreaProvider>
  135. <DimensionsDetector
  136. onDimensionsChanged = { this._onDimensionsChanged }
  137. onSafeAreaInsetsChanged = { this._onSafeAreaInsetsChanged }>
  138. { super._createMainElement(component, props) }
  139. </DimensionsDetector>
  140. </SafeAreaProvider>
  141. );
  142. }
  143. /**
  144. * Attempts to disable the use of React Native
  145. * {@link ExceptionsManager#handleException} on platforms and in
  146. * configurations on/in which the use of the method in questions has been
  147. * determined to be undesirable. For example, React Native will
  148. * (intentionally) throw an unhandled {@code JavascriptException} for an
  149. * unhandled JavaScript error in the Release configuration. This will
  150. * effectively kill the app. In accord with the Web, do not kill the app.
  151. *
  152. * @private
  153. * @returns {void}
  154. */
  155. _maybeDisableExceptionsManager() {
  156. if (__DEV__) {
  157. // As mentioned above, only the Release configuration was observed
  158. // to suffer.
  159. return;
  160. }
  161. if (Platform.OS !== 'android') {
  162. // A solution based on RTCSetFatalHandler was implemented on iOS and
  163. // it is preferred because it is at a later step of the
  164. // error/exception handling and it is specific to fatal
  165. // errors/exceptions which were observed to kill the app. The
  166. // solution implemented below was tested on Android only so it is
  167. // considered safest to use it there only.
  168. return;
  169. }
  170. // @ts-ignore
  171. const oldHandler = global.ErrorUtils.getGlobalHandler();
  172. const newHandler = _handleException;
  173. if (!oldHandler || oldHandler !== newHandler) {
  174. // @ts-ignore
  175. newHandler.next = oldHandler;
  176. // @ts-ignore
  177. global.ErrorUtils.setGlobalHandler(newHandler);
  178. }
  179. }
  180. /**
  181. * Updates the known available size for the app to occupy.
  182. *
  183. * @param {number} width - The component's current width.
  184. * @param {number} height - The component's current height.
  185. * @private
  186. * @returns {void}
  187. */
  188. _onDimensionsChanged(width: number, height: number) {
  189. const { dispatch } = this.state.store ?? {};
  190. dispatch?.(clientResized(width, height));
  191. }
  192. /**
  193. * Updates the safe are insets values.
  194. *
  195. * @param {Object} insets - The insets.
  196. * @param {number} insets.top - The top inset.
  197. * @param {number} insets.right - The right inset.
  198. * @param {number} insets.bottom - The bottom inset.
  199. * @param {number} insets.left - The left inset.
  200. * @private
  201. * @returns {void}
  202. */
  203. _onSafeAreaInsetsChanged(insets: Object) {
  204. const { dispatch } = this.state.store ?? {};
  205. dispatch?.(setSafeAreaInsets(insets));
  206. }
  207. /**
  208. * Renders the platform specific dialog container.
  209. *
  210. * @returns {React$Element}
  211. */
  212. _renderDialogContainer() {
  213. return (
  214. <DialogContainerWrapper
  215. pointerEvents = 'box-none'
  216. style = { StyleSheet.absoluteFill }>
  217. <BottomSheetContainer />
  218. <DialogContainer />
  219. </DialogContainerWrapper>
  220. );
  221. }
  222. }
  223. /**
  224. * Handles a (possibly unhandled) JavaScript error by preventing React Native
  225. * from converting a fatal error into an unhandled native exception which will
  226. * kill the app.
  227. *
  228. * @param {Error} error - The (possibly unhandled) JavaScript error to handle.
  229. * @param {boolean} fatal - If the specified error is fatal, {@code true};
  230. * otherwise, {@code false}.
  231. * @private
  232. * @returns {void}
  233. */
  234. function _handleException(error: Error, fatal: boolean) {
  235. if (fatal) {
  236. // In the Release configuration, React Native will (intentionally) throw
  237. // an unhandled JavascriptException for an unhandled JavaScript error.
  238. // This will effectively kill the app. In accord with the Web, do not
  239. // kill the app.
  240. logger.error(error);
  241. } else {
  242. // Forward to the next globalHandler of ErrorUtils.
  243. // @ts-ignore
  244. const { next } = _handleException;
  245. typeof next === 'function' && next(error, fatal);
  246. }
  247. }