1+ import {
2+ isString ,
3+ isFunction ,
4+ merge
5+ } from '../common/Util' ;
6+ export default class Tooltip {
7+ constructor ( toolDom ) {
8+ this . _dom = this . _create ( toolDom ) ;
9+ this . _tooltipTemplate = null ;
10+ this . _opts = { } ;
11+ this . isShow = null ;
12+ this . hide ( ) ;
13+ }
14+ _create ( toolDom ) {
15+ let dom = document . createElement ( 'div' ) ;
16+ dom . classList . add ( 'inmap-tooltip' ) ;
17+ toolDom . appendChild ( dom ) ;
18+ return dom ;
19+ }
20+ _compileTooltipTemplate ( formatter ) {
21+ //语法解析 先暂时不支持ie11
22+ let RexStr = / \{ | \} / g;
23+ formatter = formatter . replace ( RexStr , function ( MatchStr ) {
24+ switch ( MatchStr ) {
25+ case '{' :
26+ return 'overItem.' ;
27+ case '}' :
28+ return '' ;
29+ default :
30+ break ;
31+ }
32+ } ) ;
33+ this . _tooltipTemplate = new Function ( 'overItem' , 'return ' + formatter ) ;
34+ }
35+ show ( x , y , text ) {
36+ let {
37+ left,
38+ top
39+ } = this . _opts . offsets ;
40+ this . _dom . innerHTML = text ;
41+ this . _dom . style . left = x + left + 'px' ;
42+ this . _dom . style . top = y + top + 'px' ;
43+ this . _show ( ) ;
44+ }
45+
46+ showText ( text , x , y ) {
47+ this . _dom . innerHTML = text ;
48+ this . _dom . style . left = x + 'px' ;
49+ this . _dom . style . top = y + 'px' ;
50+ this . _show ( ) ;
51+ }
52+ _show ( ) {
53+ if ( this . isShow != true ) {
54+ this . isShow = true ;
55+ this . _dom . style . display = 'block' ;
56+ }
57+ }
58+ hide ( ) {
59+ if ( this . isShow != false ) {
60+ this . isShow = false ;
61+ this . _dom . style . display = 'none' ;
62+ }
63+
64+ }
65+ setOption ( opts ) {
66+ let result = merge ( this . _opts , opts ) ;
67+ let {
68+ formatter,
69+ customClass
70+ } = result ;
71+
72+ if ( isString ( formatter ) ) { //编译字符串
73+ this . _compileTooltipTemplate ( result . formatter ) ;
74+ }
75+
76+ if ( this . _opts . customClass ) {
77+ this . _dom . classList . remove ( this . _opts . customClass ) ;
78+ }
79+
80+ this . _dom . classList . add ( customClass ) ;
81+ this . _opts = result ;
82+ }
83+ render ( event , overItem ) {
84+ if ( ! this . _opts . show ) return ;
85+ if ( overItem ) {
86+ let formatter = this . _opts . formatter ;
87+ let text = null ;
88+ if ( isFunction ( formatter ) ) {
89+ text = formatter ( overItem ) ;
90+ } else if ( isString ( formatter ) ) {
91+ text = this . _tooltipTemplate ( overItem ) ;
92+ }
93+ this . show ( event . offsetX , event . offsetY , text ) ;
94+ } else {
95+ this . hide ( ) ;
96+ }
97+
98+ }
99+ dispose ( ) {
100+ this . _dom . parentNode . removeChild ( this . _dom ) ;
101+ this . _tooltipTemplate = null ;
102+ this . _opts = null ;
103+ this . _dom = null ;
104+ }
105+ }
0 commit comments