summaryrefslogtreecommitdiff
path: root/source/features/highlight-deleted-and-added-files-in-diffs.tsx
blob: dc3e5cac1026344612339889845d122c5d034572 (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
70
import React from 'dom-chef';
import select from 'select-dom';
import oneTime from 'onetime';
import {observe} from 'selector-observer';
import elementReady from 'element-ready';
import * as pageDetect from 'github-url-detection';

import features from '.';
import {observeOneMutation} from '../helpers/simplified-element-observer';

async function loadDeferred(jumpList: Element): Promise<void> {
	const loadJumpList = (jumpList: Element) => jumpList.parentElement!.dispatchEvent(new MouseEvent('mouseover'));
	loadJumpList(jumpList);
	// The event listener might not have been attached yet, so we can try twice
	setTimeout(loadJumpList, 1000, jumpList);
	await observeOneMutation(jumpList);
}

async function init(): Promise<void> {
	const fileList = await elementReady([
		'.toc-select details-menu', // `isPR`
		'.toc-diff-stats + .content' // `isSingleCommit`
	].join());
	if (pageDetect.isPR()) {
		await loadDeferred(fileList!);
	}

	observe('.file-info [href]:not(.rgh-pr-file-state)', {
		constructor: HTMLAnchorElement,
		add(filename) {
			filename.classList.add('rgh-pr-file-state');
			const sourceIcon = pageDetect.isPR() ?
				select(`[href="${filename.hash}"] svg`, fileList)! :
				select(`svg + [href="${filename.hash}"]`, fileList)?.previousElementSibling!;
			const icon = sourceIcon.cloneNode(true);
			const action = icon.getAttribute('title')!;
			if (action === 'added') {
				icon.classList.add('text-green');
			} else if (action === 'removed') {
				icon.classList.add('text-red');
			} else {
				return;
			}

			icon.classList.remove('select-menu-item-icon');
			filename.parentElement!.append(
				<span className="tooltipped tooltipped-s" aria-label={'File ' + action}>
					{icon}
				</span>
			);
		}
	});
}

void features.add({
	id: __filebasename,
	description: 'Indicates with an icon whether files in commits and pull requests being added or removed.',
	screenshot: 'https://user-images.githubusercontent.com/1402241/90332474-23262b00-dfb5-11ea-9a03-8fd676ea0fdd.png'
}, {
	include: [
		pageDetect.isPRFiles,
		pageDetect.isCommit
	],
	exclude: [
		pageDetect.isPRFile404,
		pageDetect.isPRCommit404
	],
	init: oneTime(init),
	waitForDomReady: false
});