summaryrefslogtreecommitdiff
path: root/source/features/preserve-file-finder-term.tsx
blob: 1e3fca0e022cf81fe41c9c751eda835bd79b8132 (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
import select from 'select-dom';
import elementReady from 'element-ready';
import * as pageDetect from 'github-url-detection';

import features from '.';

function unloadHandler(): void {
	const inputElement = select<HTMLInputElement>('#tree-finder-field');
	if (inputElement) {
		history.replaceState({
			...history.state,
			rghFileFinderTerm: inputElement.value
		}, document.title);
	}
}

// Set the input field value & trigger event
async function setValueInField(): Promise<void> {
	const preservedValue = history.state?.rghFileFinderTerm;
	const inputElement = select<HTMLInputElement>('#tree-finder-field');
	if (inputElement && !inputElement.value && preservedValue) {
		await elementReady('.js-tree-browser-results > li', {stopOnDomReady: false});	// For search to work
		inputElement.value = preservedValue;
		inputElement.dispatchEvent(new Event('input')); // Trigger search
	}
}

async function init(): Promise<void> {
	await setValueInField();
	window.addEventListener('beforeunload', unloadHandler);
	window.addEventListener('pjax:start', unloadHandler);
}

function deinit(): void {
	window.removeEventListener('beforeunload', unloadHandler);
	window.removeEventListener('pjax:start', unloadHandler);
}

void features.add({
	id: __filebasename,
	description: 'Preserves the search terms when navigating back and forth between the File Finder and the files.',
	screenshot: false
}, {
	include: [
		pageDetect.isFileFinder
	],
	init,
	deinit
});