StatusBar.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. * @flow
  9. */
  10. 'use strict';
  11. const Platform = require('../../Utilities/Platform');
  12. const React = require('react');
  13. const invariant = require('invariant');
  14. const processColor = require('../../StyleSheet/processColor');
  15. import type {ColorValue} from '../../StyleSheet/StyleSheetTypes';
  16. import NativeStatusBarManagerAndroid from './NativeStatusBarManagerAndroid';
  17. import NativeStatusBarManagerIOS from './NativeStatusBarManagerIOS';
  18. /**
  19. * Status bar style
  20. */
  21. export type StatusBarStyle = $Keys<{
  22. /**
  23. * Default status bar style (dark for iOS, light for Android)
  24. */
  25. default: string,
  26. /**
  27. * Dark background, white texts and icons
  28. */
  29. 'light-content': string,
  30. /**
  31. * Light background, dark texts and icons
  32. */
  33. 'dark-content': string,
  34. ...
  35. }>;
  36. /**
  37. * Status bar animation
  38. */
  39. export type StatusBarAnimation = $Keys<{
  40. /**
  41. * No animation
  42. */
  43. none: string,
  44. /**
  45. * Fade animation
  46. */
  47. fade: string,
  48. /**
  49. * Slide animation
  50. */
  51. slide: string,
  52. ...
  53. }>;
  54. type AndroidProps = $ReadOnly<{|
  55. /**
  56. * The background color of the status bar.
  57. * @platform android
  58. */
  59. backgroundColor?: ?ColorValue,
  60. /**
  61. * If the status bar is translucent.
  62. * When translucent is set to true, the app will draw under the status bar.
  63. * This is useful when using a semi transparent status bar color.
  64. *
  65. * @platform android
  66. */
  67. translucent?: ?boolean,
  68. |}>;
  69. type IOSProps = $ReadOnly<{|
  70. /**
  71. * If the network activity indicator should be visible.
  72. *
  73. * @platform ios
  74. */
  75. networkActivityIndicatorVisible?: ?boolean,
  76. /**
  77. * The transition effect when showing and hiding the status bar using the `hidden`
  78. * prop. Defaults to 'fade'.
  79. *
  80. * @platform ios
  81. */
  82. showHideTransition?: ?('fade' | 'slide'),
  83. |}>;
  84. type Props = $ReadOnly<{|
  85. ...AndroidProps,
  86. ...IOSProps,
  87. /**
  88. * If the status bar is hidden.
  89. */
  90. hidden?: ?boolean,
  91. /**
  92. * If the transition between status bar property changes should be animated.
  93. * Supported for backgroundColor, barStyle and hidden.
  94. */
  95. animated?: ?boolean,
  96. /**
  97. * Sets the color of the status bar text.
  98. */
  99. barStyle?: ?('default' | 'light-content' | 'dark-content'),
  100. |}>;
  101. /**
  102. * Merges the prop stack with the default values.
  103. */
  104. function mergePropsStack(
  105. propsStack: Array<Object>,
  106. defaultValues: Object,
  107. ): Object {
  108. return propsStack.reduce((prev, cur) => {
  109. for (const prop in cur) {
  110. if (cur[prop] != null) {
  111. prev[prop] = cur[prop];
  112. }
  113. }
  114. return prev;
  115. }, Object.assign({}, defaultValues));
  116. }
  117. /**
  118. * Returns an object to insert in the props stack from the props
  119. * and the transition/animation info.
  120. */
  121. function createStackEntry(props: any): any {
  122. return {
  123. backgroundColor:
  124. props.backgroundColor != null
  125. ? {
  126. value: props.backgroundColor,
  127. animated: props.animated,
  128. }
  129. : null,
  130. barStyle:
  131. props.barStyle != null
  132. ? {
  133. value: props.barStyle,
  134. animated: props.animated,
  135. }
  136. : null,
  137. translucent: props.translucent,
  138. hidden:
  139. props.hidden != null
  140. ? {
  141. value: props.hidden,
  142. animated: props.animated,
  143. transition: props.showHideTransition,
  144. }
  145. : null,
  146. networkActivityIndicatorVisible: props.networkActivityIndicatorVisible,
  147. };
  148. }
  149. /**
  150. * Component to control the app status bar.
  151. *
  152. * ### Usage with Navigator
  153. *
  154. * It is possible to have multiple `StatusBar` components mounted at the same
  155. * time. The props will be merged in the order the `StatusBar` components were
  156. * mounted. One use case is to specify status bar styles per route using `Navigator`.
  157. *
  158. * ```
  159. * <View>
  160. * <StatusBar
  161. * backgroundColor="blue"
  162. * barStyle="light-content"
  163. * />
  164. * <Navigator
  165. * initialRoute={{statusBarHidden: true}}
  166. * renderScene={(route, navigator) =>
  167. * <View>
  168. * <StatusBar hidden={route.statusBarHidden} />
  169. * ...
  170. * </View>
  171. * }
  172. * />
  173. * </View>
  174. * ```
  175. *
  176. * ### Imperative API
  177. *
  178. * For cases where using a component is not ideal, there are static methods
  179. * to manipulate the `StatusBar` display stack. These methods have the same
  180. * behavior as mounting and unmounting a `StatusBar` component.
  181. *
  182. * For example, you can call `StatusBar.pushStackEntry` to update the status bar
  183. * before launching a third-party native UI component, and then call
  184. * `StatusBar.popStackEntry` when completed.
  185. *
  186. * ```
  187. * const openThirdPartyBugReporter = async () => {
  188. * // The bug reporter has a dark background, so we push a new status bar style.
  189. * const stackEntry = StatusBar.pushStackEntry({barStyle: 'light-content'});
  190. *
  191. * // `open` returns a promise that resolves when the UI is dismissed.
  192. * await BugReporter.open();
  193. *
  194. * // Don't forget to call `popStackEntry` when you're done.
  195. * StatusBar.popStackEntry(stackEntry);
  196. * };
  197. * ```
  198. *
  199. * There is a legacy imperative API that enables you to manually update the
  200. * status bar styles. However, the legacy API does not update the internal
  201. * `StatusBar` display stack, which means that any changes will be overridden
  202. * whenever a `StatusBar` component is mounted or unmounted.
  203. *
  204. * It is strongly advised that you use `pushStackEntry`, `popStackEntry`, or
  205. * `replaceStackEntry` instead of the static methods beginning with `set`.
  206. *
  207. * ### Constants
  208. *
  209. * `currentHeight` (Android only) The height of the status bar.
  210. */
  211. class StatusBar extends React.Component<Props> {
  212. static _propsStack = [];
  213. static _defaultProps = createStackEntry({
  214. animated: false,
  215. showHideTransition: 'fade',
  216. backgroundColor:
  217. Platform.OS === 'android'
  218. ? NativeStatusBarManagerAndroid.getConstants()
  219. .DEFAULT_BACKGROUND_COLOR ?? 'black'
  220. : 'black',
  221. barStyle: 'default',
  222. translucent: false,
  223. hidden: false,
  224. networkActivityIndicatorVisible: false,
  225. });
  226. // Timer for updating the native module values at the end of the frame.
  227. static _updateImmediate = null;
  228. // The current merged values from the props stack.
  229. static _currentValues = null;
  230. // TODO(janic): Provide a real API to deal with status bar height. See the
  231. // discussion in #6195.
  232. /**
  233. * The current height of the status bar on the device.
  234. *
  235. * @platform android
  236. */
  237. static currentHeight: ?number =
  238. Platform.OS === 'android'
  239. ? NativeStatusBarManagerAndroid.getConstants().HEIGHT
  240. : null;
  241. // Provide an imperative API as static functions of the component.
  242. // See the corresponding prop for more detail.
  243. /**
  244. * Show or hide the status bar
  245. * @param hidden Hide the status bar.
  246. * @param animation Optional animation when
  247. * changing the status bar hidden property.
  248. */
  249. static setHidden(hidden: boolean, animation?: StatusBarAnimation) {
  250. animation = animation || 'none';
  251. StatusBar._defaultProps.hidden.value = hidden;
  252. if (Platform.OS === 'ios') {
  253. NativeStatusBarManagerIOS.setHidden(hidden, animation);
  254. } else if (Platform.OS === 'android') {
  255. NativeStatusBarManagerAndroid.setHidden(hidden);
  256. }
  257. }
  258. /**
  259. * Set the status bar style
  260. * @param style Status bar style to set
  261. * @param animated Animate the style change.
  262. */
  263. static setBarStyle(style: StatusBarStyle, animated?: boolean) {
  264. animated = animated || false;
  265. StatusBar._defaultProps.barStyle.value = style;
  266. if (Platform.OS === 'ios') {
  267. NativeStatusBarManagerIOS.setStyle(style, animated);
  268. } else if (Platform.OS === 'android') {
  269. NativeStatusBarManagerAndroid.setStyle(style);
  270. }
  271. }
  272. /**
  273. * Control the visibility of the network activity indicator
  274. * @param visible Show the indicator.
  275. */
  276. static setNetworkActivityIndicatorVisible(visible: boolean) {
  277. if (Platform.OS !== 'ios') {
  278. console.warn(
  279. '`setNetworkActivityIndicatorVisible` is only available on iOS',
  280. );
  281. return;
  282. }
  283. StatusBar._defaultProps.networkActivityIndicatorVisible = visible;
  284. NativeStatusBarManagerIOS.setNetworkActivityIndicatorVisible(visible);
  285. }
  286. /**
  287. * Set the background color for the status bar
  288. * @param color Background color.
  289. * @param animated Animate the style change.
  290. */
  291. static setBackgroundColor(color: string, animated?: boolean) {
  292. if (Platform.OS !== 'android') {
  293. console.warn('`setBackgroundColor` is only available on Android');
  294. return;
  295. }
  296. animated = animated || false;
  297. StatusBar._defaultProps.backgroundColor.value = color;
  298. const processedColor = processColor(color);
  299. if (processedColor == null) {
  300. console.warn(
  301. `\`StatusBar.setBackgroundColor\`: Color ${color} parsed to null or undefined`,
  302. );
  303. return;
  304. }
  305. invariant(
  306. typeof processedColor === 'number',
  307. 'Unexpected color given for StatusBar.setBackgroundColor',
  308. );
  309. NativeStatusBarManagerAndroid.setColor(processedColor, animated);
  310. }
  311. /**
  312. * Control the translucency of the status bar
  313. * @param translucent Set as translucent.
  314. */
  315. static setTranslucent(translucent: boolean) {
  316. if (Platform.OS !== 'android') {
  317. console.warn('`setTranslucent` is only available on Android');
  318. return;
  319. }
  320. StatusBar._defaultProps.translucent = translucent;
  321. NativeStatusBarManagerAndroid.setTranslucent(translucent);
  322. }
  323. /**
  324. * Push a StatusBar entry onto the stack.
  325. * The return value should be passed to `popStackEntry` when complete.
  326. *
  327. * @param props Object containing the StatusBar props to use in the stack entry.
  328. */
  329. static pushStackEntry(props: any): any {
  330. const entry = createStackEntry(props);
  331. StatusBar._propsStack.push(entry);
  332. StatusBar._updatePropsStack();
  333. return entry;
  334. }
  335. /**
  336. * Pop a StatusBar entry from the stack.
  337. *
  338. * @param entry Entry returned from `pushStackEntry`.
  339. */
  340. static popStackEntry(entry: any) {
  341. const index = StatusBar._propsStack.indexOf(entry);
  342. if (index !== -1) {
  343. StatusBar._propsStack.splice(index, 1);
  344. }
  345. StatusBar._updatePropsStack();
  346. }
  347. /**
  348. * Replace an existing StatusBar stack entry with new props.
  349. *
  350. * @param entry Entry returned from `pushStackEntry` to replace.
  351. * @param props Object containing the StatusBar props to use in the replacement stack entry.
  352. */
  353. static replaceStackEntry(entry: any, props: any): any {
  354. const newEntry = createStackEntry(props);
  355. const index = StatusBar._propsStack.indexOf(entry);
  356. if (index !== -1) {
  357. StatusBar._propsStack[index] = newEntry;
  358. }
  359. StatusBar._updatePropsStack();
  360. return newEntry;
  361. }
  362. static defaultProps: {|
  363. animated: boolean,
  364. showHideTransition: $TEMPORARY$string<'fade'>,
  365. |} = {
  366. animated: false,
  367. showHideTransition: 'fade',
  368. };
  369. _stackEntry = null;
  370. componentDidMount() {
  371. // Every time a StatusBar component is mounted, we push it's prop to a stack
  372. // and always update the native status bar with the props from the top of then
  373. // stack. This allows having multiple StatusBar components and the one that is
  374. // added last or is deeper in the view hierarchy will have priority.
  375. this._stackEntry = StatusBar.pushStackEntry(this.props);
  376. }
  377. componentWillUnmount() {
  378. // When a StatusBar is unmounted, remove itself from the stack and update
  379. // the native bar with the next props.
  380. StatusBar.popStackEntry(this._stackEntry);
  381. }
  382. componentDidUpdate() {
  383. this._stackEntry = StatusBar.replaceStackEntry(
  384. this._stackEntry,
  385. this.props,
  386. );
  387. }
  388. /**
  389. * Updates the native status bar with the props from the stack.
  390. */
  391. static _updatePropsStack = () => {
  392. // Send the update to the native module only once at the end of the frame.
  393. clearImmediate(StatusBar._updateImmediate);
  394. StatusBar._updateImmediate = setImmediate(() => {
  395. const oldProps = StatusBar._currentValues;
  396. const mergedProps = mergePropsStack(
  397. StatusBar._propsStack,
  398. StatusBar._defaultProps,
  399. );
  400. // Update the props that have changed using the merged values from the props stack.
  401. if (Platform.OS === 'ios') {
  402. if (
  403. !oldProps ||
  404. oldProps.barStyle.value !== mergedProps.barStyle.value
  405. ) {
  406. NativeStatusBarManagerIOS.setStyle(
  407. mergedProps.barStyle.value,
  408. mergedProps.barStyle.animated || false,
  409. );
  410. }
  411. if (!oldProps || oldProps.hidden.value !== mergedProps.hidden.value) {
  412. NativeStatusBarManagerIOS.setHidden(
  413. mergedProps.hidden.value,
  414. mergedProps.hidden.animated
  415. ? mergedProps.hidden.transition
  416. : 'none',
  417. );
  418. }
  419. if (
  420. !oldProps ||
  421. oldProps.networkActivityIndicatorVisible !==
  422. mergedProps.networkActivityIndicatorVisible
  423. ) {
  424. NativeStatusBarManagerIOS.setNetworkActivityIndicatorVisible(
  425. mergedProps.networkActivityIndicatorVisible,
  426. );
  427. }
  428. } else if (Platform.OS === 'android') {
  429. //todo(T60684787): Add back optimization to only update bar style and
  430. //background color if the new value is different from the old value.
  431. NativeStatusBarManagerAndroid.setStyle(mergedProps.barStyle.value);
  432. const processedColor = processColor(mergedProps.backgroundColor.value);
  433. if (processedColor == null) {
  434. console.warn(
  435. `\`StatusBar._updatePropsStack\`: Color ${
  436. mergedProps.backgroundColor.value
  437. } parsed to null or undefined`,
  438. );
  439. } else {
  440. invariant(
  441. typeof processedColor === 'number',
  442. 'Unexpected color given in StatusBar._updatePropsStack',
  443. );
  444. NativeStatusBarManagerAndroid.setColor(
  445. processedColor,
  446. mergedProps.backgroundColor.animated,
  447. );
  448. }
  449. if (!oldProps || oldProps.hidden.value !== mergedProps.hidden.value) {
  450. NativeStatusBarManagerAndroid.setHidden(mergedProps.hidden.value);
  451. }
  452. if (!oldProps || oldProps.translucent !== mergedProps.translucent) {
  453. NativeStatusBarManagerAndroid.setTranslucent(mergedProps.translucent);
  454. }
  455. }
  456. // Update the current prop values.
  457. StatusBar._currentValues = mergedProps;
  458. });
  459. };
  460. render(): React.Node {
  461. return null;
  462. }
  463. }
  464. module.exports = StatusBar;