-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
embed-gist-inline.tsx
64 lines (56 loc) · 1.64 KB
/
embed-gist-inline.tsx
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
import React from 'dom-chef';
import domify from 'doma';
import select from 'select-dom';
import * as pageDetect from 'github-url-detection';
import features from '.';
const isGist = ({pathname, hostname}: HTMLAnchorElement): boolean =>
!pathname.includes('.') && // Exclude links to embed files
(
(hostname.startsWith('gist.') && pathname.includes('/', 1)) || // Exclude user links
pathname.startsWith('gist/')
);
const isOnlyChild = ({textContent, parentNode}: HTMLAnchorElement): boolean => textContent!.trim() === parentNode!.textContent!.trim();
async function embedGist(link: HTMLAnchorElement): Promise<void> {
const info = <em> (loading)</em>;
link.after(info);
try {
// Fetch via background.js due to CORB policies
const gistData = await browser.runtime.sendMessage({fetchJSON: `${link.href}.json`});
if (gistData.div.length > 10000) {
info.textContent = ' (too large to embed)';
return;
}
const fileCount: number = gistData.files.length;
if (fileCount > 1) {
info.textContent = ` (${fileCount} files)`;
} else {
const container = <div/>;
container.attachShadow({mode: 'open'}).append(
<style>{`
.gist .gist-data {
max-height: 16em;
overflow-y: auto;
}
`}
</style>,
<link rel="stylesheet" href={gistData.stylesheet}/>,
domify.one(gistData.div)!
);
link.parentElement!.after(container);
info.remove();
}
} catch {
info.remove();
}
}
function init(): void {
select.all('.js-comment-body p a:only-child')
.filter(item => isGist(item) && isOnlyChild(item))
.forEach(embedGist);
}
void features.add(__filebasename, {
include: [
pageDetect.hasComments
],
init
});