├── .babelrc ├── .eslintignore ├── .github ├── labeler.yml └── workflows │ └── main.yml ├── .gitignore ├── tooltipExample.gif ├── .npmignore ├── src ├── helpers.js ├── Triangle.js ├── getTooltipCoordinate.js └── Tooltip.js ├── .eslintrc ├── index.d.ts ├── LICENSE ├── package.json ├── __tests__ ├── Tooltip.test.js └── __snapshots__ │ └── Tooltip.test.js.snap └── README.md /.babelrc: -------------------------------------------------------------------------------- 1 | 2 | { 3 | "presets": ["react-native"] 4 | } -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | /coverage 2 | /node_modules 3 | /.vscode 4 | -------------------------------------------------------------------------------- /.github/labeler.yml: -------------------------------------------------------------------------------- 1 | enhancement: 2 | - src/**/* 3 | 4 | has_test: 5 | - _tests_/**/* 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | 3 | 4 | yarn-error.log 5 | 6 | .vscode 7 | coverage 8 | 9 | -------------------------------------------------------------------------------- /tooltipExample.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndreiCalazans/rn-tooltip/HEAD/tooltipExample.gif -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | yarn-error.log 3 | .vscode 4 | .github 5 | /TooltipExample 6 | /coverage 7 | /__tests__ 8 | /tooltipExample.gif 9 | -------------------------------------------------------------------------------- /src/helpers.js: -------------------------------------------------------------------------------- 1 | // @flow 2 | 3 | import { Platform, Dimensions } from 'react-native'; 4 | 5 | const Screen = Dimensions.get('window'); 6 | export const ScreenWidth: number = Screen.width; 7 | export const ScreenHeight: number = Screen.height; 8 | export const isIOS = Platform.OS === 'ios'; 9 | 10 | export const Colors = { 11 | darkergray: '#617080', 12 | overlay_bright: 'rgba(250, 250, 250, 0.70)', 13 | }; 14 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "env": { 4 | "browser": true 5 | }, 6 | "plugins": [ 7 | "react", 8 | "react-native", 9 | "flowtype" 10 | ], 11 | "extends": [ 12 | "eslint:recommended", 13 | "plugin:react/recommended" 14 | ], 15 | "globals": { 16 | "describe": false, 17 | "it": false, 18 | "expect": false, 19 | "beforeEach": false, 20 | "before": false, 21 | "afterEach": false, 22 | "after": false, 23 | "jest": false, 24 | "global": false 25 | }, 26 | "rules": { 27 | "quotes": ["error", "single", { "allowTemplateLiterals": true }], 28 | "semi": ["error", "always"] 29 | } 30 | } -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | on: 2 | - push 3 | 4 | name: 'Validate Code' 5 | jobs: 6 | triage: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/labeler@v2 10 | with: 11 | repo-token: "${{ secrets.GITHUB_TOKEN }}" 12 | chore: 13 | name: 'Validate Codebase' 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@master 18 | 19 | - name: 'Use Node.js 10.x' 20 | uses: actions/setup-node@master 21 | with: 22 | version: 10.x 23 | - name: 'Install Dependencies' 24 | run: | 25 | yarn 26 | - name: 'Lint and Test' 27 | run: | 28 | yarn prettier:check 29 | yarn lint 30 | yarn test 31 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { StyleProp, ViewStyle, TouchableOpacityProps } from 'react-native'; 3 | 4 | type Props = { 5 | popover?: React.ReactElement<{}>; 6 | withPointer?: boolean, 7 | height?: number | string, 8 | width?: number | string, 9 | containerStyle?: StyleProp; 10 | pointerColor?: string, 11 | pointerStyle?: StyleProp, 12 | onClose?: () => void, 13 | onOpen?: () => void, 14 | withOverlay?: boolean, 15 | overlayColor?: string, 16 | backgroundColor?: string, 17 | highlightColor?: string, 18 | toggleWrapperProps?: TouchableOpacityProps, 19 | actionType: 'press' | 'longPress' | 'none', 20 | children: React.ReactNode 21 | }; 22 | 23 | export default class Tooltip extends React.Component { 24 | toggleTooltip: () => void; 25 | } 26 | -------------------------------------------------------------------------------- /src/Triangle.js: -------------------------------------------------------------------------------- 1 | // @flow 2 | 3 | import React from 'react'; 4 | import { View, StyleSheet } from 'react-native'; 5 | 6 | type Props = { 7 | style: any, 8 | isDown: boolean, 9 | }; 10 | 11 | const Triangle = ({ style, isDown }: Props) => ( 12 | 13 | ); 14 | 15 | const styles = StyleSheet.create({ 16 | down: { 17 | transform: [{ rotate: '180deg' }], 18 | }, 19 | triangle: { 20 | width: 0, 21 | height: 0, 22 | backgroundColor: 'transparent', 23 | borderStyle: 'solid', 24 | borderLeftWidth: 8, 25 | borderRightWidth: 8, 26 | borderBottomWidth: 15, 27 | borderLeftColor: 'transparent', 28 | borderRightColor: 'transparent', 29 | borderBottomColor: 'white', 30 | }, 31 | }); 32 | 33 | export default Triangle; 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Andrei Xavier de Oliveira Calazans 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rn-tooltip", 3 | "version": "3.0.3", 4 | "main": "src/Tooltip.js", 5 | "homepage": "https://github.com/AndreiCalazans/rn-tooltip#readme", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/AndreiCalazans/rn-tooltip" 9 | }, 10 | "author": "AndreiCalazans ", 11 | "license": "MIT", 12 | "scripts": { 13 | "check:commit": "yarn flow && npm run test && lint-staged", 14 | "check:commit_lazy": "yarn flow && lint-staged", 15 | "prettier": "prettier --write --single-quote true --trailing-comma all --print-width 80", 16 | "precommit": "lint-staged", 17 | "commitmsg": "commitlint -e $GIT_PARAMS", 18 | "prettier:all": "prettier --write --single-quote true --trailing-comma all --print-width 80 --write 'src/**/*.js'", 19 | "prettier:check": "prettier -c --single-quote true --trailing-comma all --print-width 80 'src/**/*.js'", 20 | "flow": "node_modules/.bin/flow check", 21 | "flow-typed": "rm -rf flow-typed/npm && node_modules/.bin/flow-typed install", 22 | "flow-log": "yarn flow --show-all-errors > flow.log", 23 | "test": "jest", 24 | "test:watch": "jest --watch", 25 | "test:coverage": "jest --coverage", 26 | "lint": "node_modules/.bin/eslint src --max-warnings=0" 27 | }, 28 | "lint-staged": { 29 | "*.js": [ 30 | "yarn prettier", 31 | "eslint --fix", 32 | "git add" 33 | ] 34 | }, 35 | "jest": { 36 | "preset": "react-native", 37 | "coverageDirectory": "./coverage/", 38 | "collectCoverageFrom": [ 39 | "src/**/*.js" 40 | ], 41 | "collectCoverage": true, 42 | "globals": { 43 | "__DEV__": true 44 | } 45 | }, 46 | "dependencies": { 47 | "deprecated-react-native-prop-types": "^2.3.0" 48 | }, 49 | "devDependencies": { 50 | "@commitlint/cli": "^6.1.3", 51 | "@commitlint/config-conventional": "^6.1.3", 52 | "babel-eslint": "^8.1.1", 53 | "babel-preset-react-native": "4.0.0", 54 | "eslint": "^4.14.0", 55 | "eslint-plugin-flowtype": "^2.40.1", 56 | "eslint-plugin-react": "^7.5.1", 57 | "eslint-plugin-react-native": "^3.2.0", 58 | "flow-bin": "0.67", 59 | "flow-typed": "^2.4.0", 60 | "husky": "0.14.3", 61 | "jest": "^23.1.0", 62 | "lint-staged": "6.0.0", 63 | "prettier": "^1.9.2", 64 | "prop-types": "^15.6.1", 65 | "react": "^16.4.0", 66 | "react-native": "^0.55.4", 67 | "react-test-renderer": "^16.4.0" 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /__tests__/Tooltip.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Text, TouchableOpacity } from 'react-native'; 3 | import TestRenderer from 'react-test-renderer'; 4 | import Tooltip from '../src/Tooltip'; 5 | import Triangle from '../src/Triangle'; 6 | 7 | describe('Tooltip component', () => { 8 | it('should render without issues', () => { 9 | const component = TestRenderer.create( 10 | Info here}> 11 | Press me 12 | , 13 | ); 14 | 15 | expect(component.toJSON()).toMatchSnapshot(); 16 | }); 17 | 18 | it('should display tooltip when no actionType is provided (will default to onPress)', () => { 19 | const Info = () => Info here; 20 | const component = TestRenderer.create( 21 | }> 22 | Press me 23 | , 24 | ); 25 | 26 | component.root.findAllByType(TouchableOpacity)[0].props.onPress(); 27 | expect(component.root.findByType(Triangle)).toBeTruthy(); 28 | expect(component.root.findByType(Info)).toBeTruthy(); 29 | 30 | expect(component.toJSON()).toMatchSnapshot(); 31 | }); 32 | 33 | it('should display tooltip on longPress', () => { 34 | const Info = () => Info here; 35 | const component = TestRenderer.create( 36 | } 40 | actionType="longPress" 41 | > 42 | Press me 43 | , 44 | ); 45 | 46 | component.root.findAllByType(TouchableOpacity)[0].props.onLongPress(); 47 | expect(component.root.findByType(Triangle)).toBeTruthy(); 48 | expect(component.root.findByType(Info)).toBeTruthy(); 49 | 50 | expect(component.toJSON()).toMatchSnapshot(); 51 | }); 52 | 53 | it('does not render pointer', () => { 54 | const component = TestRenderer.create( 55 | Info here} 60 | > 61 | Press me 62 | , 63 | ).root; 64 | 65 | component.findAllByType(TouchableOpacity)[0].props.onPress(); 66 | expect(component.instance.state.isVisible).toBe(true); 67 | try { 68 | component.findByType(Triangle); 69 | } catch (e) { 70 | expect(e.message).toBe('No instances found with node type: "Triangle"'); 71 | } 72 | }); 73 | 74 | it('does not render pointer when actionType is longPress', () => { 75 | const component = TestRenderer.create( 76 | Info here} 82 | > 83 | Press me 84 | , 85 | ).root; 86 | 87 | component.findAllByType(TouchableOpacity)[0].props.onLongPress(); 88 | expect(component.instance.state.isVisible).toBe(true); 89 | try { 90 | component.findByType(Triangle); 91 | } catch (e) { 92 | expect(e.message).toBe('No instances found with node type: "Triangle"'); 93 | } 94 | }); 95 | }); 96 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | [![npm version](https://badge.fury.io/js/rn-tooltip.svg)](https://badge.fury.io/js/rn-tooltip) 3 | 4 | 5 | # rn-tooltip 6 | 7 | *Simple, lightwweight and **blazing fast** react native tooltip* 8 | 9 | 10 | 11 | 12 | Expo App if you want to try it out: https://expo.io/@andreixoc/RNTooltipTester 13 | 14 | Code for the Expo app is here: https://github.com/andreiCalazans/rnTooltipTester 15 | 16 | ## Install 17 | 18 | `yarn add rn-tooltip` 19 | 20 | or 21 | 22 | `npm install rn-tooltip --save` 23 | 24 | 25 | 26 | ## Usage 27 | 28 | ```js 29 | import { Text } from 'react-native'; 30 | import Tooltip from 'rn-tooltip'; 31 | 32 | ... 33 | 34 | Info here}> 35 | Press me 36 | 37 | ``` 38 | 39 | ## Props 40 | 41 | * [`backgroundColor`](#backgroundcolor) 42 | * [`containerStyle`](#containerStyle) 43 | * [`height`](#height) 44 | * [`highlightColor`](#highlightColor) 45 | * [`onClose`](#onClose) 46 | * [`onOpen`](#onOpen) 47 | * [`pointerColor`](#pointerColor) 48 | * [`pointerStyle`](#pointerStyle) 49 | * [`popover`](#popover) 50 | * [`actionType`](#actionType) 51 | * [`width`](#width) 52 | * [`withOverlay`](#withOverlay) 53 | * [`overlayColor`](#withOverlay) 54 | * [`withPointer`](#withPointer) 55 | * [`toggleWrapperProps`](#toggleWrapperProps) 56 | 57 | --- 58 | 59 | ## Reference 60 | 61 | ### `backgroundColor` 62 | 63 | sets backgroundColor of the tooltip and pointer. 64 | 65 | | Type | Default | 66 | | :----: | :-----: | 67 | | string | #617080 | 68 | 69 | --- 70 | 71 | ### `containerStyle` 72 | 73 | Passes style object to tooltip container 74 | 75 | | Type | Default | 76 | | :------------: | :---------------: | 77 | | object (style) | inherited styling | 78 | 79 | --- 80 | 81 | ### `height` 82 | 83 | Tooltip container height. Necessary in order to render the container in the 84 | correct place. Pass height according to the size of the content rendered inside 85 | the container. 86 | 87 | | Type | Default | 88 | | :----: | :-----: | 89 | | number | string | 40 | 90 | 91 | --- 92 | 93 | ### `highlightColor` 94 | 95 | Color to highlight the item the tooltip is surrounding. 96 | 97 | | Type | Default | 98 | | :----: | :---------: | 99 | | string | transparent | 100 | 101 | --- 102 | 103 | ### `onClose` 104 | 105 | function which gets called on closing the tooltip. 106 | 107 | | Type | Default | 108 | | :------: | :------: | 109 | | function | () => {} | 110 | 111 | --- 112 | 113 | ### `onOpen` 114 | 115 | function which gets called on opening the tooltip. 116 | 117 | | Type | Default | 118 | | :------: | :------: | 119 | | function | () => {} | 120 | 121 | --- 122 | 123 | ### `pointerColor` 124 | 125 | Color of tooltip pointer, it defaults to the 126 | [`backgroundColor`](#backgroundcolor) if none is passed . 127 | 128 | | Type | Default | 129 | | :----: | :-----------------------------------: | 130 | | string | [`backgroundColor`](#backgroundcolor) | 131 | 132 | --- 133 | 134 | ### `pointerStyle` 135 | 136 | Passes style object to tooltip pointer view 137 | 138 | | Type | Default | 139 | | :------------: | :---------------: | 140 | | object (style) | inherited styling | 141 | 142 | ### `popover` 143 | 144 | Component to be rendered as the display container. 145 | 146 | | Type | Default | 147 | | :-----------: | :-----: | 148 | | React.Element | null | 149 | 150 | --- 151 | 152 | ### `actionType` 153 | 154 | Flag to determine how the tooltip reacts to presses. 155 | 156 | | Type | Default | 157 | | :-----: | :-----: | 158 | | press or none or longPress | press | 159 | 160 | --- 161 | 162 | ### `width` 163 | 164 | Tooltip container width. Necessary in order to render the container in the 165 | correct place. Pass height according to the size of the content rendered inside 166 | the container. 167 | 168 | | Type | Default | 169 | | :----: | :-----: | 170 | | number | number | 150 | 171 | 172 | ### `withOverlay` 173 | 174 | Flag to determine whether or not dislay overlay shadow when tooltip is open. 175 | 176 | | Type | Default | 177 | | :-----: | :-----: | 178 | | boolean | true | 179 | 180 | ### `overlayColor` 181 | 182 | Sets backgroundColor of the overlay. 183 | 184 | | Type | Default | 185 | | :-----: | :-----: | 186 | | string | rgba(250, 250, 250, 0.70) | 187 | 188 | ### `withPointer` 189 | 190 | Flag to determine whether or not dislay pointer. 191 | 192 | | Type | Default | 193 | | :-----: | :-----: | 194 | | boolean | true | 195 | 196 | ### `toggleWrapperProps` 197 | 198 | Drills TouchableOpacity Props down to the TouchableOpacity wrapper that toggles the Tooltip. 199 | 200 | | Type | Default | 201 | | :------------: | :---------------: | 202 | | TouchableOpacityProps | {} | 203 | 204 | 205 | **MIT Licensed** -------------------------------------------------------------------------------- /src/getTooltipCoordinate.js: -------------------------------------------------------------------------------- 1 | // @flow 2 | import { Dimensions } from 'react-native'; 3 | 4 | function convertDimensionToNumber(dimension, screenDimension) { 5 | if (typeof dimension === 'string' && dimension.includes('%')) { 6 | const decimal = Number(dimension.replace(/%/, '')) / 100; 7 | return decimal * screenDimension; 8 | } 9 | 10 | if (typeof dimension === 'number') { 11 | return dimension; 12 | } 13 | return Number(dimension); 14 | } 15 | 16 | const getArea = (a: number, b: number): number => a * b; 17 | 18 | const getPointDistance = (a: number[], b: number[]): number => 19 | Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2)); 20 | 21 | type Coord = { 22 | x: number, 23 | y: number, 24 | }; 25 | 26 | /* 27 | ~Tooltip coordinate system:~ 28 | The tooltip coordinates are based on the element which it is wrapping. 29 | We take the x and y coordinates of the element and find the best position 30 | to place the tooltip. To find the best position we look for the side with the 31 | most space. In order to find the side with the most space we divide the the 32 | surroundings in four quadrants and check for the one with biggest area. 33 | Once we know the quandrant with the biggest area it place the tooltip in that 34 | direction. 35 | 36 | To find the areas we first get 5 coordinate points. The center and the other 4 extreme points 37 | which together make a perfect cross shape. 38 | 39 | Once we know the coordincates we can get the length of the vertices which form each quadrant. 40 | Since they are squares we only need two. 41 | */ 42 | 43 | const getTooltipCoordinate = ( 44 | x: number, 45 | y: number, 46 | width: number, 47 | height: number, 48 | ScreenWidth: number, 49 | ScreenHeight: number, 50 | receivedTooltipWidth: number | string, 51 | withPointer: boolean, 52 | ): Coord => { 53 | const screenDims = Dimensions.get('screen'); 54 | 55 | const tooltipWidth = convertDimensionToNumber( 56 | receivedTooltipWidth, 57 | screenDims.width, 58 | ); 59 | // The following are point coordinates: [x, y] 60 | const center = [x + width / 2, y + height / 2]; 61 | const pOne = [center[0], 0]; 62 | const pTwo = [ScreenWidth, center[1]]; 63 | const pThree = [center[0], ScreenHeight]; 64 | const pFour = [0, center[1]]; 65 | 66 | // vertices 67 | const vOne = getPointDistance(center, pOne); 68 | const vTwo = getPointDistance(center, pTwo); 69 | const vThree = getPointDistance(center, pThree); 70 | const vFour = getPointDistance(center, pFour); 71 | 72 | // Quadrant areas. 73 | type Areas = { 74 | area: number, 75 | id: number, 76 | }; 77 | 78 | const areas: Areas[] = [ 79 | getArea(vOne, vFour), 80 | getArea(vOne, vTwo), 81 | getArea(vTwo, vThree), 82 | getArea(vThree, vFour), 83 | ].map((each, index) => ({ area: each, id: index })); 84 | 85 | const sortedArea = areas.sort((a, b) => b.area - a.area); 86 | 87 | // deslocated points 88 | const dX = 0.001; 89 | const dY = height / 2; 90 | 91 | // Deslocate the coordinates in the direction of the quadrant. 92 | const directionCorrection = [ 93 | [-1, -1], 94 | [1, -1], 95 | [1, 1], 96 | [-1, 1], 97 | ]; 98 | const deslocateReferencePoint = [ 99 | [-tooltipWidth, 0], 100 | [0, 0], 101 | [0, 0], 102 | [-tooltipWidth, 0], 103 | ]; 104 | 105 | // current quadrant index 106 | const qIndex = sortedArea[0].id; 107 | 108 | const getWithPointerOffsetY = () => 109 | withPointer ? 10 * directionCorrection[qIndex][1] : 0; 110 | const getWithPointerOffsetX = () => 111 | withPointer ? center[0] - 18 * directionCorrection[qIndex][0] : center[0]; 112 | 113 | const newX = 114 | getWithPointerOffsetX() + 115 | (dX * directionCorrection[qIndex][0] + deslocateReferencePoint[qIndex][0]); 116 | 117 | return { 118 | x: constraintX(newX, qIndex, center[0], ScreenWidth, tooltipWidth), 119 | y: 120 | center[1] + 121 | (dY * directionCorrection[qIndex][1] + 122 | deslocateReferencePoint[qIndex][1]) + 123 | getWithPointerOffsetY(), 124 | }; 125 | }; 126 | 127 | const constraintX = ( 128 | newX: number, 129 | qIndex: number, 130 | x: number, 131 | ScreenWidth: number, 132 | tooltipWidth: number, 133 | ): number => { 134 | switch (qIndex) { 135 | // 0 and 3 are the left side quadrants. 136 | case 0: 137 | case 3: { 138 | const maxWidth = newX > ScreenWidth ? ScreenWidth - 10 : newX; 139 | return newX < 1 ? 10 : maxWidth; 140 | } 141 | // 1 and 2 are the right side quadrants 142 | case 1: 143 | case 2: { 144 | const leftOverSpace = ScreenWidth - newX; 145 | return leftOverSpace >= tooltipWidth 146 | ? newX 147 | : newX - (tooltipWidth - leftOverSpace + 10); 148 | } 149 | default: { 150 | return 0; 151 | } 152 | } 153 | }; 154 | 155 | export default getTooltipCoordinate; 156 | -------------------------------------------------------------------------------- /src/Tooltip.js: -------------------------------------------------------------------------------- 1 | // @flow 2 | 3 | import * as React from 'react'; 4 | import { TouchableOpacity, Modal, View, I18nManager } from 'react-native'; 5 | import { ViewPropTypes as RNViewPropTypes } from 'deprecated-react-native-prop-types'; 6 | import PropTypes from 'prop-types'; 7 | 8 | import Triangle from './Triangle'; 9 | import { ScreenWidth, ScreenHeight, isIOS } from './helpers'; 10 | import getTooltipCoordinate from './getTooltipCoordinate'; 11 | 12 | const ViewPropTypes = RNViewPropTypes || View.propTypes; 13 | 14 | type State = { 15 | isVisible: boolean, 16 | yOffset: number, 17 | xOffset: number, 18 | elementWidth: number, 19 | elementHeight: number, 20 | }; 21 | 22 | type Props = { 23 | withPointer: boolean, 24 | popover: React.Element, 25 | height: number | string, 26 | width: number | string, 27 | containerStyle: any, 28 | pointerColor: string, 29 | pointerStyle: {}, 30 | onClose: () => void, 31 | onOpen: () => void, 32 | withOverlay: boolean, 33 | overlayColor: string, 34 | backgroundColor: string, 35 | highlightColor: string, 36 | toggleWrapperProps: {}, 37 | actionType: 'press' | 'longPress' | 'none', 38 | }; 39 | 40 | class Tooltip extends React.Component { 41 | state = { 42 | isVisible: false, 43 | yOffset: 0, 44 | xOffset: 0, 45 | elementWidth: 0, 46 | elementHeight: 0, 47 | }; 48 | 49 | renderedElement; 50 | timeout; 51 | 52 | toggleTooltip = () => { 53 | const { onClose } = this.props; 54 | this.getElementPosition(); 55 | this.setState(prevState => { 56 | if (prevState.isVisible && !isIOS) { 57 | onClose && onClose(); 58 | } 59 | 60 | return { isVisible: !prevState.isVisible }; 61 | }); 62 | }; 63 | 64 | wrapWithAction = (actionType, children) => { 65 | switch (actionType) { 66 | case 'press': 67 | return ( 68 | 73 | {children} 74 | 75 | ); 76 | case 'longPress': 77 | return ( 78 | 83 | {children} 84 | 85 | ); 86 | default: 87 | return children; 88 | } 89 | }; 90 | 91 | getTooltipStyle = () => { 92 | const { yOffset, xOffset, elementHeight, elementWidth } = this.state; 93 | const { 94 | height, 95 | backgroundColor, 96 | width, 97 | withPointer, 98 | containerStyle, 99 | } = this.props; 100 | 101 | const { x, y } = getTooltipCoordinate( 102 | xOffset, 103 | yOffset, 104 | elementWidth, 105 | elementHeight, 106 | ScreenWidth, 107 | ScreenHeight, 108 | width, 109 | withPointer, 110 | ); 111 | 112 | const tooltipStyle = { 113 | position: 'absolute', 114 | left: I18nManager.isRTL ? null : x, 115 | right: I18nManager.isRTL ? x : null, 116 | width, 117 | height, 118 | backgroundColor, 119 | // default styles 120 | display: 'flex', 121 | alignItems: 'center', 122 | justifyContent: 'center', 123 | flex: 1, 124 | borderRadius: 10, 125 | padding: 10, 126 | ...containerStyle, 127 | }; 128 | 129 | const pastMiddleLine = yOffset > y; 130 | if (typeof height !== 'number' && pastMiddleLine) { 131 | tooltipStyle.bottom = ScreenHeight - y; 132 | } else if (typeof height === 'number' && pastMiddleLine) { 133 | tooltipStyle.top = y - height; 134 | } else { 135 | tooltipStyle.top = y; 136 | } 137 | 138 | return { tooltipStyle, pastMiddleLine }; 139 | }; 140 | 141 | renderPointer = pastMiddleLine => { 142 | const { yOffset, xOffset, elementHeight, elementWidth } = this.state; 143 | const { backgroundColor, pointerColor, pointerStyle } = this.props; 144 | 145 | return ( 146 | 154 | 161 | 162 | ); 163 | }; 164 | renderContent = withTooltip => { 165 | const { popover, withPointer, highlightColor, actionType } = this.props; 166 | 167 | if (!withTooltip) 168 | return this.wrapWithAction(actionType, this.props.children); 169 | 170 | const { yOffset, xOffset, elementWidth, elementHeight } = this.state; 171 | const { pastMiddleLine, tooltipStyle } = this.getTooltipStyle(); 172 | return ( 173 | 174 | 186 | {this.props.children} 187 | 188 | {withPointer && this.renderPointer(Boolean(pastMiddleLine))} 189 | {popover} 190 | 191 | ); 192 | }; 193 | 194 | componentDidMount() { 195 | // wait to compute onLayout values. 196 | this.timeout = setTimeout(this.getElementPosition, 500); 197 | } 198 | 199 | componentWillUnmount() { 200 | clearTimeout(this.timeout); 201 | } 202 | 203 | getElementPosition = () => { 204 | this.renderedElement && 205 | this.renderedElement.measureInWindow( 206 | (pageOffsetX, pageOffsetY, width, height) => { 207 | this.setState({ 208 | xOffset: pageOffsetX, 209 | yOffset: pageOffsetY, 210 | elementWidth: width, 211 | elementHeight: height, 212 | }); 213 | }, 214 | ); 215 | }; 216 | 217 | render() { 218 | const { isVisible } = this.state; 219 | const { onClose, withOverlay, onOpen, overlayColor } = this.props; 220 | 221 | return ( 222 | (this.renderedElement = e)}> 223 | {this.renderContent(false)} 224 | 232 | 237 | {this.renderContent(true)} 238 | 239 | 240 | 241 | ); 242 | } 243 | } 244 | 245 | Tooltip.propTypes = { 246 | children: PropTypes.element, 247 | withPointer: PropTypes.bool, 248 | popover: PropTypes.element, 249 | height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), 250 | width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), 251 | containerStyle: ViewPropTypes.style, 252 | pointerColor: PropTypes.string, 253 | pointerStyle: PropTypes.object, 254 | onClose: PropTypes.func, 255 | onOpen: PropTypes.func, 256 | withOverlay: PropTypes.bool, 257 | toggleWrapperProps: PropTypes.object, 258 | overlayColor: PropTypes.string, 259 | backgroundColor: PropTypes.string, 260 | highlightColor: PropTypes.string, 261 | actionType: PropTypes.oneOf(['press', 'longPress', 'none']), 262 | }; 263 | 264 | Tooltip.defaultProps = { 265 | toggleWrapperProps: {}, 266 | withOverlay: true, 267 | highlightColor: 'transparent', 268 | withPointer: true, 269 | actionType: 'press', 270 | height: 40, 271 | width: 150, 272 | containerStyle: {}, 273 | pointerStyle: {}, 274 | backgroundColor: '#617080', 275 | onClose: () => {}, 276 | onOpen: () => {}, 277 | }; 278 | 279 | const styles = { 280 | container: (withOverlay, overlayColor) => ({ 281 | backgroundColor: withOverlay 282 | ? overlayColor 283 | ? overlayColor 284 | : 'rgba(250, 250, 250, 0.70)' 285 | : 'transparent', 286 | flex: 1, 287 | }), 288 | }; 289 | 290 | export default Tooltip; 291 | -------------------------------------------------------------------------------- /__tests__/__snapshots__/Tooltip.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Tooltip component should display tooltip on longPress 1`] = ` 4 | 7 | 22 | 27 | Press me 28 | 29 | 30 | 39 | 56 | 70 | 75 | Press me 76 | 77 | 78 | 88 | 110 | 111 | 130 | 135 | Info here 136 | 137 | 138 | 139 | 140 | 141 | `; 142 | 143 | exports[`Tooltip component should display tooltip when no actionType is provided (will default to onPress) 1`] = ` 144 | 147 | 162 | 167 | Press me 168 | 169 | 170 | 179 | 196 | 210 | 215 | Press me 216 | 217 | 218 | 228 | 250 | 251 | 270 | 275 | Info here 276 | 277 | 278 | 279 | 280 | 281 | `; 282 | 283 | exports[`Tooltip component should render without issues 1`] = ` 284 | 287 | 302 | 307 | Press me 308 | 309 | 310 | 319 | 336 | 350 | 355 | Press me 356 | 357 | 358 | 368 | 390 | 391 | 410 | 415 | Info here 416 | 417 | 418 | 419 | 420 | 421 | `; 422 | --------------------------------------------------------------------------------