summaryrefslogtreecommitdiff
path: root/source/features/stop-pjax-loading-with-esc.tsx
blob: a8c0f3a21710b9ff0513651770f29b2ea0c41402 (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 select from 'select-dom';
import * as pageDetect from 'github-url-detection';

import features from '.';

let progressLoader: HTMLElement;
const progressLoaderLoadingClass = 'is-loading';

function fixProfileNavAndTimeline(): void {
	for (const stickyElement of select.all('.js-sticky:not(.is-stuck)')) {
		stickyElement.removeAttribute('style');
	}
}

function keydownHandler(event: KeyboardEvent): void {
	if (event.key !== 'Escape' || !progressLoader.classList.contains(progressLoaderLoadingClass)) {
		return;
	}

	if (history.state && '_id' in history.state) {
		const pjaxContainer = select('#js-repo-pjax-container, #js-pjax-container, #gist-pjax-container');

		if (pjaxContainer) {
			// We need it for correct work of browser forward-button
			history.replaceState({
				url: location.href,
				title: '',
				container: `#${pjaxContainer.id}`,
				...history.state
			}, '', location.href);
		} else {
			features.error(__filebasename, 'Pjax container not found.');
		}
	}

	window.addEventListener('pjax:error', pjaxErrorHandler, {once: true});

	history.back();
	progressLoader.classList.remove(progressLoaderLoadingClass);
}

function pjaxErrorHandler(event: CustomEvent): void {
	if (event.cancelable) {
		// Avoid location.replace() when AbortController.abort() throw an error
		event.preventDefault();
	}
}

function init(): void {
	progressLoader = select('.progress-pjax-loader')!;

	window.addEventListener('keydown', keydownHandler);

	if (pageDetect.isUserProfile()) {
		window.addEventListener('pjax:end', fixProfileNavAndTimeline);
	}
}

void features.add(__filebasename, {
	include: [
		pageDetect.isRepo,
		pageDetect.isRepoSearch,
		pageDetect.isGlobalSearchResults,
		pageDetect.isUserProfile,
		pageDetect.isSingleGist,
		pageDetect.isGlobalConversationList
	],
	init
});