summaryrefslogtreecommitdiff
path: root/source/features/copy-file.tsx
blob: 91bd188c9ced57cecbd49d0b6b9aa2a55132f016 (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
import React from 'dom-chef';
import select from 'select-dom';
import delegate from 'delegate-it';
import * as pageDetect from 'github-url-detection';

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');
	button.setAttribute('value', content);
}

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

function init(): void {
	delegate(document, '.rgh-copy-file:not([value])', 'click', handleClick, true);
	renderButton();
}

void features.add(__filebasename, {
	asLongAs: [
		() => select.exists('table.highlight'), // Rendered page
	],
	include: [
		pageDetect.isSingleFile,
		pageDetect.isGist,
	],
	deduplicate: '.rgh-copy-file', // #3945
	init,
});