summaryrefslogtreecommitdiff
path: root/source/features/copy-file.tsx
blob: 3cff95abf4e6e786b45235a7709d0e08800cb371 (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
import React from 'dom-chef';
import select from 'select-dom';
import copyToClipboard from 'copy-text-to-clipboard';
import features from '../libs/features';
import {groupSiblings} from '../libs/group-buttons';

function init() {
	// This selector skips binaries + markdowns with code
	for (const code of select.all<HTMLElement>('.file .blob-wrapper > .highlight:not(.rgh-copy-file)')) {
		code.classList.add('rgh-copy-file');
		const file = code.closest('.file');

		const content = select.all<HTMLElement>('.blob-code-inner', file)
			.map(blob => blob.innerText)
			.map(line => line === '\n' ? '' : line)
			.join('\n');

		const handleClick = () => {
			copyToClipboard(content);
		};

		// Prepend to list of buttons
		const firstAction = select('.file-actions .btn', file);
		if (firstAction) {
			firstAction.before(
				<button onClick={handleClick} class="btn btn-sm copy-btn tooltipped tooltipped-n" aria-label="Copy file to clipboard" type="button">Copy</button>
			);

			// Group buttons if necessary
			groupSiblings(firstAction);
		}
	}
}

features.add({
	id: 'copy-file',
	include: [
		features.isSingleFile,
		features.isGist
	],
	load: features.onAjaxedPages,
	init
});