-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile-embeds.js
67 lines (52 loc) · 1.96 KB
/
file-embeds.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
/*!
* file-embeds - v0.0.1 - 2014-02-12
* Copyright (c) 2014 Ah-Lun Tang <tang@ahlun.be>
*
* License: The MIT License (MIT) - http://ahluntang.mit-license.org/
*/
(function(){
if (!self.document || !document.querySelector) {
return;
}
/**
* Depth-first search for all pre tags with data-src attribute
*/
Array.prototype.slice.call(document.querySelectorAll('pre[data-src]')).forEach(function(pre) {
var src = pre.getAttribute('data-src');
var code = document.createElement('code');
pre.textContent = '';
code.textContent = 'Loading...';
pre.appendChild(code);
var xhr = new XMLHttpRequest();
/* Detect GitHub */
var is_github = /https:\/\/github.com\//i.test(src);
if (is_github) {
var match = src.match( /https:\/\/github.com\/([^\/]+)\/([^\/]+)\/([^\/]+)\/([^\/]+)\/([\s\S]+)/);
var github = {
user: match[1],
repo: match[2],
path: match[5]
};
src = 'https://api.github.com/repos/' + github.user + '/' + github.repo + '/contents/' + github.path;
}
xhr.open('GET', src, true);
/* If GitHub uri, set Accept to raw */
if (is_github) {
xhr.setRequestHeader('Accept', 'application/vnd.github.v3.raw');
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status < 400 && xhr.responseText) {
code.textContent = xhr.responseText;
}
else if (xhr.status >= 400) {
code.textContent = ' Error ' + xhr.status + ' while fetching file: ' + xhr.statusText;
}
else {
code.textContent = ' Error: File does not exist or is empty';
}
}
};
xhr.send(null);
});
})();