PressabilityDebug.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. * @flow strict-local
  8. * @format
  9. */
  10. 'use strict';
  11. import normalizeColor from '../StyleSheet/normalizeColor';
  12. import type {ColorValue} from '../StyleSheet/StyleSheetTypes';
  13. import Touchable from '../Components/Touchable/Touchable';
  14. import View from '../Components/View/View';
  15. import * as React from 'react';
  16. type Props = $ReadOnly<{|
  17. color: ColorValue,
  18. hitSlop: ?$ReadOnly<{|
  19. bottom?: ?number,
  20. left?: ?number,
  21. right?: ?number,
  22. top?: ?number,
  23. |}>,
  24. |}>;
  25. /**
  26. * Displays a debug overlay to visualize press targets when enabled via the
  27. * React Native Inspector. Calls to this module should be guarded by `__DEV__`,
  28. * for example:
  29. *
  30. * return (
  31. * <View>
  32. * {children}
  33. * {__DEV__ ? (
  34. * <PressabilityDebugView color="..." hitSlop={props.hitSlop} />
  35. * ) : null}
  36. * </View>
  37. * );
  38. *
  39. */
  40. export function PressabilityDebugView({color, hitSlop}: Props): React.Node {
  41. if (__DEV__) {
  42. if (isEnabled()) {
  43. const normalizedColor = normalizeColor(color);
  44. if (typeof normalizedColor !== 'number') {
  45. return null;
  46. }
  47. const baseColor =
  48. '#' + (normalizedColor ?? 0).toString(16).padStart(8, '0');
  49. return (
  50. <View
  51. pointerEvents="none"
  52. style={{
  53. backgroundColor: baseColor.slice(0, -2) + '0F', // 15%
  54. borderColor: baseColor.slice(0, -2) + '55', // 85%
  55. borderStyle: 'dashed',
  56. borderWidth: 1,
  57. bottom: -(hitSlop?.bottom ?? 0),
  58. left: -(hitSlop?.left ?? 0),
  59. position: 'absolute',
  60. right: -(hitSlop?.right ?? 0),
  61. top: -(hitSlop?.top ?? 0),
  62. }}
  63. />
  64. );
  65. }
  66. }
  67. return null;
  68. }
  69. export function isEnabled(): boolean {
  70. if (__DEV__) {
  71. return Touchable.TOUCH_TARGET_DEBUG;
  72. }
  73. return false;
  74. }