This repository has been archived by the owner on Aug 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathprivate-eye.js
105 lines (83 loc) · 2.72 KB
/
private-eye.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
// https://github.com/18F/private-eye
(function() {
'use strict';
var STYLES = 'a.private-link::after { content: "\\1F512"; font-size: 0.75em; vertical-align: top; }';
var STYLES_ID = '_privateEye-styles';
var DEFAULT_OPTIONS = {
defaultMessage: 'This is a link to a private site, which may or may not be accessible to you.',
wrapper: ''
};
var isString = function(str) { return !!str && typeof str === 'string'; };
var isArray = function(arr) { return !!arr && arr.length; };
var optionValidators = {
defaultMessage: isString,
wrapper: isString,
ignoreUrls: isArray,
};
function setStyles() {
var styles = document.createElement('style');
styles.innerHTML = STYLES;
styles.id = STYLES_ID;
document.body.appendChild(styles);
}
function getOptions(opts) {
var newObj = {};
for (var prop in DEFAULT_OPTIONS) {
newObj[prop] = DEFAULT_OPTIONS[prop];
}
for (var prop in opts) {
var val = opts[prop];
if (optionValidators[prop](val)) {
newObj[prop] = val;
}
}
return newObj;
}
var PrivateEye = function(opts) {
// The old docs recommend calling this as a function. This is here to detect
// those cases and make sure backward compatibility stays intact now that the
// new syntax is preferred.
if (!(this instanceof PrivateEye)) {
return new PrivateEye(opts);
}
// Don't add the styles to the page more than once.
if (!document.getElementById(STYLES_ID)) {
setStyles();
}
this.opts = getOptions(opts);
this.checkLinks();
};
PrivateEye.prototype.checkLinks = function() {
var self = this;
this.opts.ignoreUrls.forEach(function(url) {
var hrefValue;
var titleValue;
// If the `url` is an Object, then parse the properties `message` & `url`
if (url === Object(url)) {
titleValue = url.message;
hrefValue = url.url;
} else {
hrefValue = url;
titleValue = self.opts.defaultMessage;
}
var wrapper = self.opts.wrapper.length ? self.opts.wrapper + ' ' : '';
var selector = wrapper + 'a';
var anchors = document.querySelectorAll(selector);
Array.prototype.forEach.call(anchors, function(anchor) {
var anchorHref = anchor.href.toLowerCase().trim();
if (anchorHref.indexOf(hrefValue.toLowerCase()) !== -1) {
anchor.className += ' private-link';
// Only replace the anchor's title if it is empty
if (!anchor.title) {
anchor.title = titleValue;
}
}
});
});
}
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = PrivateEye;
} else {
window.PrivateEye = PrivateEye;
}
})();