Skip to content

Commit

Permalink
fix(Tooltip): add focus trap behavior and fix focus management logic
Browse files Browse the repository at this point in the history
  • Loading branch information
emyarod committed Jul 13, 2020
1 parent d63dd09 commit b055d81
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion packages/react/src/components/Tooltip/Tooltip.js
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,12 @@ class Tooltip extends Component {
_tooltipId =
this.props.id || `__carbon-tooltip_${Math.random().toString(36).substr(2)}`;

/**
* Internal flag for tracking whether or not focusing on the tooltip trigger
* should automatically display the tooltip body
*/
_tooltipDismissed = false;

componentDidMount() {
if (!this._debouncedHandleFocus) {
this._debouncedHandleFocus = debounce(this._handleFocus, 200);
Expand Down Expand Up @@ -264,10 +270,16 @@ class Tooltip extends Component {
}

_handleUserInputOpenClose = (event, { open }) => {
// capture tooltip body element before it is removed from the DOM
const tooltipBody = this._tooltipEl;
this.setState({ open }, () => {
if (this.props.onChange) {
this.props.onChange(event, { open });
}
if (!open && tooltipBody && tooltipBody.id === this._tooltipId) {
this._tooltipDismissed = true;
this._triggerRef?.current.focus();
}
});
};

Expand All @@ -279,7 +291,10 @@ class Tooltip extends Component {
_handleFocus = (state, evt) => {
const { relatedTarget } = evt;
if (state === 'over') {
this._handleUserInputOpenClose(evt, { open: true });
if (!this._tooltipDismissed) {
this._handleUserInputOpenClose(evt, { open: true });
}
this._tooltipDismissed = false;
} else {
// Note: SVGElement in IE11 does not have `.contains()`
const { current: triggerEl } = this._triggerRef;
Expand Down Expand Up @@ -460,6 +475,7 @@ class Tooltip extends Component {
</ClickListener>
{open && (
<FloatingMenu
focusTrap
selectorPrimaryFocus={this.props.selectorPrimaryFocus}
target={this._getTarget}
triggerRef={this._triggerRef}
Expand Down

0 comments on commit b055d81

Please sign in to comment.