summaryrefslogtreecommitdiff
path: root/source/features/collapsible-content-button.tsx
blob: 5eeae5809c3fd62567d7321489e79ade40b7b2a1 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import React from 'dom-chef';
import {FoldDownIcon} from '@primer/octicons-react';
import * as pageDetect from 'github-url-detection';
import * as textFieldEdit from 'text-field-edit';
import delegate, {DelegateEvent} from 'delegate-it';
import {elementExists} from 'select-dom';

import features from '../feature-manager.js';
import smartBlockWrap from '../helpers/smart-block-wrap.js';
import observe from '../helpers/selector-observer.js';

function addContentToDetails({delegateTarget}: DelegateEvent<MouseEvent, HTMLButtonElement>): void {
	/* There's only one rich-text editor even when multiple fields are visible; the class targets it #5303 */
	const field = delegateTarget.form!.querySelector('textarea.js-comment-field')!;
	const selection = field.value.slice(field.selectionStart, field.selectionEnd);

	// Don't indent <summary> because indentation will not be automatic on multi-line content
	const newContent = `
		<details>
		<summary>Details</summary>

		${selection}

		</details>
	`.replaceAll(/(\n|\b)\t+/g, '$1').trim();

	field.focus();
	textFieldEdit.insert(field, smartBlockWrap(newContent, field));

	// Restore selection.
	// `selectionStart` will be right after the newly-inserted text
	field.setSelectionRange(
		field.value.lastIndexOf('</summary>', field.selectionStart) + '</summary>'.length + 2,
		field.value.lastIndexOf('</details>', field.selectionStart) - 2,
	);
}

function addButtons(referenceButton: HTMLElement): void {
	const classes
	= elementExists('md-ref', referenceButton)
		? [
			'toolbar-item',
			'btn-octicon',
			'p-2',
			'p-md-1',
			'tooltipped',
			'tooltipped-sw',
			'rgh-collapsible-content-btn',
		]
		: [
			'Button',
			'Button--iconOnly',
			'Button--invisible',
			'Button--medium',
			'tooltipped',
			'tooltipped-sw',
			'rgh-collapsible-content-btn',
		];

	referenceButton.after(
		<button type="button" className={classes.join(' ')} aria-label="Add collapsible content">
			<FoldDownIcon/>
		</button>,
	);
}

function init(signal: AbortSignal): void {
	observe([
		'md-ref', // TODO: Drop in June 2024
		'.ActionBar-item:has([data-md-button=\'ref\'])',
	], addButtons, {signal});
	delegate('.rgh-collapsible-content-btn', 'click', addContentToDetails, {signal});
}

void features.add(import.meta.url, {
	include: [
		pageDetect.hasRichTextEditor,
	],
	init,
});

/*

Test URLs:

- Any issue or PR

*/