From 5a3dcbbc4b81d5ce123e2327afe60b95db130355 Mon Sep 17 00:00:00 2001 From: hassanbot Date: Thu, 13 Oct 2016 00:26:36 +0200 Subject: [PATCH] Return tooltip to original position when possible --- src/index.js | 5 +++-- src/utils/getPosition.js | 27 ++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/index.js b/src/index.js index 15ebfe8ef..6a19b4fc7 100644 --- a/src/index.js +++ b/src/index.js @@ -247,6 +247,7 @@ class ReactTooltip extends Component { this.setState({ placeholder, isEmptyTip, + desiredPlace: e.currentTarget.getAttribute('data-place') || this.props.place || 'top', place: e.currentTarget.getAttribute('data-place') || this.props.place || 'top', type: e.currentTarget.getAttribute('data-type') || this.props.type || 'dark', effect: switchToSolid && 'solid' || e.currentTarget.getAttribute('data-effect') || this.props.effect || 'float', @@ -363,9 +364,9 @@ class ReactTooltip extends Component { // Calculation the position updatePosition () { - const {currentEvent, currentTarget, place, effect, offset} = this.state + const {currentEvent, currentTarget, place, desiredPlace, effect, offset} = this.state const node = ReactDOM.findDOMNode(this) - const result = getPosition(currentEvent, currentTarget, node, place, effect, offset) + const result = getPosition(currentEvent, currentTarget, node, place, desiredPlace, effect, offset) if (result.isNewState) { // Switch to reverse placement diff --git a/src/utils/getPosition.js b/src/utils/getPosition.js index 780003531..b02dcdecb 100644 --- a/src/utils/getPosition.js +++ b/src/utils/getPosition.js @@ -14,7 +14,7 @@ * - `newState` {Object} * - `position` {OBject} {left: {Number}, top: {Number}} */ -export default function (e, target, node, place, effect, offset) { +export default function (e, target, node, place, desiredPlace, effect, offset) { const tipWidth = node.clientWidth const tipHeight = node.clientHeight const {mouseX, mouseY} = getCurrentOffset(e, target, effect) @@ -151,6 +151,31 @@ export default function (e, target, node, place, effect, offset) { } } + // Change back to original place if possible + if (place !== desiredPlace) { + if (desiredPlace === 'top' && !outsideTopResult.result) { + return { + isNewState: true, + newState: {place: 'top'} + } + } else if (desiredPlace === 'left' && !outsideLeftResult.result) { + return { + isNewState: true, + newState: {place: 'left'} + } + } else if (desiredPlace === 'right' && !outsideRightResult.result) { + return { + isNewState: true, + newState: {place: 'right'} + } + } else if (desiredPlace === 'bottom' && !outsideBottomResult.result) { + return { + isNewState: true, + newState: {place: 'bottom'} + } + } + } + // Return tooltip offset position return { isNewState: false,