summaryrefslogtreecommitdiff
path: root/source/features/expand-all-collapsed-code.tsx
blob: 4eaac9234e61f2ce86588c0fed53ba8304e66d95 (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
import select from 'select-dom';
import delegate from 'delegate-it';
import * as pageDetect from 'github-url-detection';

import features from '.';

const expanderSelector = '.js-expand.directional-expander';

// Waits for the next loaded diff part and clicks on any additional "Expand" buttons it finds
const expandingCodeObserver = new MutationObserver(([mutation]) => {
	const expandButton = select(expanderSelector, mutation.target as Element);
	if (expandButton) {
		expandButton.click();
	} else {
		document.body.removeEventListener('keyup', disconnectOnEscape);
		expandingCodeObserver.disconnect();
	}
});

function disconnectOnEscape(event: KeyboardEvent): void {
	if (event.key === 'Escape') {
		document.body.removeEventListener('keyup', disconnectOnEscape);
		expandingCodeObserver.disconnect();
	}
}

function handleAltClick(event: delegate.Event<MouseEvent, HTMLButtonElement>): void {
	if (!event.altKey) {
		return;
	}

	document.body.addEventListener('keyup', disconnectOnEscape);

	expandingCodeObserver.observe(
		event.delegateTarget.closest('.diff-table > tbody')!,
		{childList: true}
	);
}

function init(): void {
	delegate(document, expanderSelector, 'click', handleAltClick);
}

void features.add(__filebasename, {
	include: [
		pageDetect.isPRCommit,
		pageDetect.isPRFiles,
		pageDetect.isSingleCommit
	],
	init
});