This repository has been archived by the owner on Jan 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl-expander.js
84 lines (68 loc) · 2.16 KB
/
url-expander.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
var UrlExpander = function(tweet) {
var listeners = [];
var links = $('#stream-item-tweet-' + tweet.id() + ', #stream-item-activity-' + tweet.id()).find('a.twitter-timeline-link');
var urlsToExpandCount = links.length;
var expandedUrlsCount = 0;
links.each(expand);
function expand() {
var urlToExpand = $(this).data('expanded-url');
if (urlToExpand !== undefined) {
expandUrl(this, urlToExpand);
} else {
urlsToExpandCount--;
}
}
function expandUrl(linkElement, urlToExpand) {
fetch(urlToExpand, {
method: 'head'
}).then(function(response) {
handleExpandedUrl(linkElement, processUrl(response.url));
}).catch(function(err) {
console.log(err);
});
}
function processUrl(url) {
var urlElement = document.createElement('a');
urlElement.href = url;
if (urlElement.search !== '') {
urlElement.search = cleanupQuerystring(urlElement.search);
}
return urlElement.href;
}
function cleanupQuerystring(querystring) {
var unwantedKeys = ['buffer_share', 'utm_content', 'utm_source', 'utm_medium', 'utm_campaign'];
var cleanParams = [];
var params = querystring.substring(1).split('&');
params.forEach(function(param) {
var containsUnwantedKey = unwantedKeys.some(function(unwantedKey) {
return (param.indexOf(unwantedKey) > -1)
});
if (!containsUnwantedKey) {
cleanParams.push(param);
}
});
return (cleanParams.length > 0) ? '?' + cleanParams.join('&') : '';
}
function handleExpandedUrl(linkElement, expandedUrl) {
expandedUrlsCount++;
$(linkElement).data('expanded-url', expandedUrl);
$(linkElement).attr('href', expandedUrl);
$(linkElement).attr('title', expandedUrl);
$(linkElement).find('.js-display-url').text(expandedUrl);
$(linkElement).find('.tco-ellipsis').hide();
if (expandedUrlsCount === urlsToExpandCount) {
notifyListeners();
}
}
function notifyListeners() {
listeners.forEach(function(listener) {
listener(tweet);
});
}
function onAllUrlsExpanded(listener) {
listeners.push(listener);
}
return {
onAllUrlsExpanded: onAllUrlsExpanded
}
}