forked from camsong/chrome-github-mate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
82 lines (73 loc) · 2.81 KB
/
script.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
// page.js injection start
var s = document.createElement('script');
s.src = chrome.extension.getURL('page.js');
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
// page.js injection end
var FileDownloader = {
init: function() {
FileDownloader.addDownloadTooltip();
FileDownloader.bindPopState();
chrome.runtime.sendMessage({key: "feature-1-enable"}, function(response) {
if(typeof(response.result) === 'undefined' || response.result === true) {
$(document).on('click', '.octicon-file-text', function(e) {
FileDownloader.eventHandler(e);
});
} else {
console.log('GitHub Mate click to download file is disabled, you can re-enable it in options page.');
}
});
},
addDownloadTooltip: function() {
Array.prototype.slice.call(document.querySelectorAll('.octicon-file-text')).map(function(icon) {
var td = icon.parentNode;
td.classList.add('tooltipped', 'tooltipped-se');
td.setAttribute('aria-label', 'Click to download');
});
// if in file detail page
var rawUrlNode = document.querySelector('#raw-url');
if (rawUrlNode && !document.querySelector('.download-btn')) {
var fileName = document.querySelector('.breadcrumb .final-path').textContent;
let btn = document.createElement('a');
btn.setAttribute('class', 'btn btn-sm btn-primary tooltipped tooltipped-n download-btn');
btn.setAttribute('href', rawUrlNode.href);
btn.setAttribute('download', fileName);
btn.setAttribute('aria-label', 'Click to download ' + fileName);
btn.textContent = 'Download';
rawUrlNode.parentNode.parentNode.prepend(btn);
}
},
bindPopState: function() {
document.addEventListener('_pjax:end', function() {
FileDownloader.addDownloadTooltip();
ShowSize.init();
}, false);
window.onpopstate = function(event) {
FileDownloader.addDownloadTooltip();
ShowSize.init();
};
},
eventHandler: function(event) {
if (this.isFromListPage(event.currentTarget)) {
var linkNode = event.currentTarget.parentNode.nextElementSibling.querySelector('a');
var href = linkNode.href.replace('\/blob\/', '\/raw\/');
this.downloadIt(href, linkNode.textContent);
}
},
downloadIt: function(href, fileName) {
var downloadNode = document.createElement('a');
downloadNode.setAttribute('href', href);
downloadNode.setAttribute('download', fileName);
downloadNode.click();
downloadNode = null;
},
isFromListPage: function(node) {
return node.classList.contains('octicon-file-text') &&
document.querySelector('.files') &&
document.querySelector('.files').contains(node) &&
document.querySelector('.file') === null;
},
}
FileDownloader.init();