summaryrefslogtreecommitdiff
path: root/source/features/copy-file.tsx
blob: 102ace71876027c74dd8a2f0187c55c3683cc5e5 (plain) (blame)
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
import React from 'dom-chef';
import select from 'select-dom';
import delegate from 'delegate-it';
import * as pageDetect from 'github-url-detection';
import copyToClipboard from 'copy-text-to-clipboard';

import features from '.';
import {groupButtons} from '../github-helpers/group-buttons';

function handleClick({delegateTarget: button}: delegate.Event<MouseEvent, HTMLButtonElement>): void {
	const file = button.closest('.Box, .js-gist-file-update-container')!;
	const content = select.all('.blob-code-inner', file)
		.map(({innerText: line}) => line === '\n' ? '' : line) // Must be `.innerText`
		.join('\n');
	copyToClipboard(content);

	button.textContent = 'Copied!';
	button.classList.remove('tooltipped');
	setTimeout(() => {
		button.textContent = 'Copy';
		button.classList.add('tooltipped');
	}, 2000);
}

function renderButton(): void {
	for (const button of select.all<HTMLAnchorElement>([
		'.file-actions .btn[href*="/raw/"]', // `isGist`
		'[data-hotkey="b"]'
	])) {
		const copyButton = (
			<button
				className="btn btn-sm tooltipped tooltipped-n BtnGroup-item rgh-copy-file"
				aria-label="Copy file to clipboard"
				type="button"
			>
				Copy
			</button>
		);
		const group = button.closest('.BtnGroup');
		if (group) {
			group.prepend(copyButton);
		} else {
			groupButtons([button, copyButton]);
		}
	}
}

function removeButton(): void {
	select('.rgh-copy-file')?.remove();
}

function init(): void {
	delegate(document, '.rgh-copy-file', 'click', handleClick);

	if (select.exists('.blob > .markdown-body')) {
		delegate(document, '.rgh-md-source', 'rgh:view-markdown-source', renderButton);
		delegate(document, '.rgh-md-source', 'rgh:view-markdown-rendered', removeButton);
	} else {
		renderButton();
	}
}

void features.add(__filebasename, {
	include: [
		pageDetect.isSingleFile,
		pageDetect.isGist
	],
	init
});