summaryrefslogtreecommitdiff
path: root/source/features/collapse-markdown-sections.tsx
blob: e96b6116d745c12a30f8de27ac9e94af1111cf0f (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
import './collapse-markdown-sections.css';
import delegate from 'delegate-it';
import * as pageDetect from 'github-url-detection';

import features from '.';

function onHeadingClick(event: delegate.Event<MouseEvent, HTMLElement>): void {
	// Don't toggle the section if the title text is being selected instead of clicked
	if (document.getSelection()?.type === 'Range') {
		return;
	}

	// Don't toggle the section if a link in the heading is clicked (either the content or the anchor)
	if ((event.target as HTMLElement).closest('a, details')) {
		return;
	}

	const sectionHeading = event.delegateTarget;
	const isSectionHidden = sectionHeading.classList.toggle('rgh-markdown-section-collapsed');
	let element = sectionHeading.tagName === 'H1' ?
		sectionHeading.parentElement!.firstElementChild as HTMLElement :
		sectionHeading.nextElementSibling as HTMLElement;
	while (element) {
		if (/^H\d$/.test(element.tagName)) {
			if (sectionHeading.tagName !== 'H1' && element.tagName <= sectionHeading.tagName) {
				return;
			}

			element.classList.toggle('rgh-markdown-section-collapsed', isSectionHidden);
		} else {
			element.hidden = isSectionHidden;
		}

		element = element.nextElementSibling as HTMLElement;
	}
}

function init(): void {
	delegate(document, '.markdown-body > :is(h1, h2, h3, h4, h5, h6)', 'click', onHeadingClick);
	document.body.classList.add('rgh-' + __filebasename);
}

void features.add(__filebasename, {
	include: [
		pageDetect.isRepoTree,
		pageDetect.isRepoWiki,
		() => pageDetect.isSingleFile() && location.pathname.endsWith('.md')
	],
	init
});