-
Notifications
You must be signed in to change notification settings - Fork 8
/
bullseye.js
87 lines (73 loc) · 2.03 KB
/
bullseye.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
'use strict';
var crossvent = require('crossvent');
var throttle = require('./throttle');
var tailormade = require('./tailormade');
function bullseye (el, target, options) {
var o = options;
var domTarget = target && target.tagName;
if (!domTarget && arguments.length === 2) {
o = target;
}
if (!domTarget) {
target = el;
}
if (!o) { o = {}; }
var destroyed = false;
var throttledWrite = throttle(write, 30);
var tailorOptions = { update: o.autoupdateToCaret !== false && update };
var tailor = o.caret && tailormade(target, tailorOptions);
write();
if (o.tracking !== false) {
crossvent.add(window, 'resize', throttledWrite);
}
return {
read: readNull,
refresh: write,
destroy: destroy,
sleep: sleep
};
function sleep () {
tailorOptions.sleeping = true;
}
function readNull () { return read(); }
function read (readings) {
var bounds = target.getBoundingClientRect();
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
if (tailor) {
readings = tailor.read();
return {
x: (readings.absolute ? 0 : bounds.left) + readings.x,
y: (readings.absolute ? 0 : bounds.top) + scrollTop + readings.y + 20
};
}
return {
x: bounds.left,
y: bounds.top + scrollTop
};
}
function update (readings) {
write(readings);
}
function write (readings) {
if (destroyed) {
throw new Error('Bullseye can\'t refresh after being destroyed. Create another instance instead.');
}
if (tailor && !readings) {
tailorOptions.sleeping = false;
tailor.refresh(); return;
}
var p = read(readings);
if (!tailor && target !== el) {
p.y += target.offsetHeight;
}
var context = o.context;
el.style.left = p.x + 'px';
el.style.top = (context ? context.offsetHeight : p.y) + 'px';
}
function destroy () {
if (tailor) { tailor.destroy(); }
crossvent.remove(window, 'resize', throttledWrite);
destroyed = true;
}
}
module.exports = bullseye;