-
Notifications
You must be signed in to change notification settings - Fork 54
/
index.js
123 lines (102 loc) · 2.61 KB
/
index.js
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
'use strict';
module.exports = function(el, onOver, onOut) {
var x, y, pX, pY;
var mouseOver = false;
var focused = false;
var h = {},
state = 0,
timer = 0;
var options = {
sensitivity: 7,
interval: 100,
timeout: 0,
handleFocus: false
};
function delay(el, e) {
if (timer) timer = clearTimeout(timer);
state = 0;
return focused ? undefined : onOut.call(el, e);
}
function tracker(e) {
x = e.clientX;
y = e.clientY;
}
function compare(el, e) {
if (timer) timer = clearTimeout(timer);
if ((Math.abs(pX - x) + Math.abs(pY - y)) < options.sensitivity) {
state = 1;
return focused ? undefined : onOver.call(el, e);
} else {
pX = x;
pY = y;
timer = setTimeout(function() {
compare(el, e);
}, options.interval);
}
}
// Public methods
h.options = function(opt) {
var focusOptionChanged = opt.handleFocus !== options.handleFocus;
options = Object.assign({}, options, opt);
if (focusOptionChanged) {
options.handleFocus ? addFocus() : removeFocus();
}
return h;
};
function dispatchOver(e) {
mouseOver = true;
if (timer) timer = clearTimeout(timer);
el.removeEventListener('mousemove', tracker, false);
if (state !== 1) {
pX = e.clientX;
pY = e.clientY;
el.addEventListener('mousemove', tracker, false);
timer = setTimeout(function() {
compare(el, e);
}, options.interval);
}
return this;
}
function dispatchOut(e) {
mouseOver = false;
if (timer) timer = clearTimeout(timer);
el.removeEventListener('mousemove', tracker, false);
if (state === 1) {
timer = setTimeout(function() {
delay(el, e);
}, options.timeout);
}
return this;
}
function dispatchFocus(e) {
if (!mouseOver) {
focused = true;
onOver.call(el, e);
}
}
function dispatchBlur(e) {
if (!mouseOver && focused) {
focused = false;
onOut.call(el, e);
}
}
function addFocus() {
el.addEventListener('focus', dispatchFocus, false);
el.addEventListener('blur', dispatchBlur, false);
}
function removeFocus() {
el.removeEventListener('focus', dispatchFocus, false);
el.removeEventListener('blur', dispatchBlur, false);
}
h.remove = function() {
if (!el) return;
el.removeEventListener('mouseover', dispatchOver, false);
el.removeEventListener('mouseout', dispatchOut, false);
removeFocus();
};
if (el) {
el.addEventListener('mouseover', dispatchOver, false);
el.addEventListener('mouseout', dispatchOut, false);
}
return h;
};