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.

functions.js 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* @flow */
  2. declare type StyleSheet = Object;
  3. /**
  4. * The list of the well-known style properties which may not be numbers on Web
  5. * but must be numbers on React Native.
  6. *
  7. * @private
  8. */
  9. const _WELL_KNOWN_NUMBER_PROPERTIES = [ 'height', 'width' ];
  10. /* eslint-disable flowtype/space-before-type-colon */
  11. /**
  12. * Create a style sheet using the provided style definitions.
  13. *
  14. * @param {StyleSheet} styles - A dictionary of named style definitions.
  15. * @param {StyleSheet} [overrides={}] - Optional set of additional (often
  16. * platform-dependent/specific) style definitions that will override the base
  17. * (often platform-independent) styles.
  18. * @returns {StyleSheet}
  19. */
  20. export function createStyleSheet(styles: StyleSheet, overrides: StyleSheet = {})
  21. : StyleSheet {
  22. /* eslint-enable flowtype/space-before-type-colon */
  23. const combinedStyles = {};
  24. for (const k of Object.keys(styles)) {
  25. combinedStyles[k]
  26. = _shimStyles({
  27. ...styles[k],
  28. ...overrides[k]
  29. });
  30. }
  31. return combinedStyles;
  32. }
  33. /**
  34. * Shims style properties to work correctly on native. Allows us to minimize the
  35. * number of style declarations that need to be set or overridden for specific
  36. * platforms.
  37. *
  38. * @param {StyleSheet} styles - An object which represents a stylesheet.
  39. * @private
  40. * @returns {StyleSheet}
  41. */
  42. function _shimStyles<T: StyleSheet>(styles: T): T {
  43. // Certain style properties may not be numbers on Web but must be numbers on
  44. // React Native. For example, height and width may be expressed in percent
  45. // on Web but React Native will not understand them and we will get errors
  46. // (at least during development). Convert such well-known properties to
  47. // numbers if possible; otherwise, remove them to avoid runtime errors.
  48. for (const k of _WELL_KNOWN_NUMBER_PROPERTIES) {
  49. const v = styles[k];
  50. const typeofV = typeof v;
  51. if (typeofV !== 'undefined' && typeofV !== 'number') {
  52. const numberV = Number(v);
  53. if (Number.isNaN(numberV)) {
  54. delete styles[k];
  55. } else {
  56. styles[k] = numberV;
  57. }
  58. }
  59. }
  60. return styles;
  61. }