File size: 2,451 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// @flow

import * as React from "react";
import cn from "classnames";
import { Manager, Reference, Popper } from "react-popper";
import type {
  Placement,
  PopperChildrenProps,
  ReferenceChildrenProps,
} from "react-popper";
import "./Tooltip.css";

type Props = {|
  /**
   * The reference element which the Tooltip will be based on.
   */
  +children?: React.Element<any>,
  /**
   * Any additional classNames for the Tooltip.
   */
  +className?: string,
  /**
   * This is the text content of the Tooltip.
   */
  +content: string,
  /**
   * This is the placement of the Tooltip (top, bottom, left, right).
   */
  +placement?: Placement,
  +type?: "link",
|};

type State = {
  isShown: boolean,
};

class Tooltip extends React.Component<Props, State> {
  state = { isShown: false };

  _handleTriggerOnMouseEnter = (e: SyntheticMouseEvent<HTMLElement>) => {
    e.preventDefault();
    this.setState({ isShown: true });
  };

  _handleTriggerOnMouseLeave = (e: SyntheticMouseEvent<HTMLElement>) => {
    e.preventDefault();
    this.setState({ isShown: false });
  };

  render(): React.Node {
    const { className, children, placement, content } = this.props;

    const classes = cn(
      "tooltip",
      placement && "bs-tooltip-" + placement,
      "show",
      className
    );

    const arrowClasses = cn(
      "arrow",
      placement === "top" || placement === "bottom"
        ? "tbr-arrow-vertical"
        : "tbr-arrow-horizontal"
    );

    return (
      <Manager>
        <Reference>
          {({ ref }: ReferenceChildrenProps) =>
            typeof children !== "undefined" &&
            React.cloneElement(children, {
              ref: ref,
              onMouseEnter: this._handleTriggerOnMouseEnter,
              onMouseLeave: this._handleTriggerOnMouseLeave,
            })
          }
        </Reference>
        {this.state.isShown && (
          <Popper placement={placement}>
            {({ ref, style, placement }: PopperChildrenProps) => {
              return (
                <div
                  className={classes}
                  data-placement={placement}
                  style={style}
                  ref={ref}
                >
                  <div className={arrowClasses} />
                  <div className="tooltip-inner">{content}</div>
                </div>
              );
            }}
          </Popper>
        )}
      </Manager>
    );
  }
}

export default Tooltip;