summaryrefslogtreecommitdiff
path: root/source/features/wait-for-attachments.tsx
blob: 5a78c98ab84addc24bcf9af312fce4fd05a8eade (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
// GitHub natively marks `.js-upload-markdown-image textarea.js-comment-field` as invalid while a file is uploading.
// `textarea[data-required-trimmed]` conflicts with this behavior by overriding the validity states in the meantime.
// `button[data-disable-invalid]` are automatically disabled while the form is invalid, but some buttons don't have it.

import {$, $$} from 'select-dom';
import * as pageDetect from 'github-url-detection';

import features from '../feature-manager.js';

const attribute = 'data-required-trimmed';
const attributeBackup = 'data-rgh-required-trimmed';

function toggleSubmitButtons({target, type}: Event): void {
	const fileAttachment = target as HTMLElement;

	for (const button of $$('.btn-primary[type="submit"]:not([data-disable-invalid])', fileAttachment.closest('form')!)) {
		button.dataset.disableInvalid = '';
	}

	// Temporarily disable `data-required-trimmed` so that it doesn't conflict with the desired behavior.
	// The complex selector ensures that we don't add the attribute to fields that never had it in the first place.
	const textarea = $(`[${attribute}], [${attributeBackup}]`, fileAttachment)!;
	if (textarea) {
		if (type === 'upload:setup') {
			textarea.setAttribute(attributeBackup, textarea.getAttribute(attribute)!);
			textarea.removeAttribute(attribute);
		} else {
			textarea.setAttribute(attribute, textarea.getAttribute(attributeBackup)!);
			textarea.removeAttribute(attributeBackup);
		}
	}
}

function init(signal: AbortSignal): void {
	document.addEventListener('upload:setup', toggleSubmitButtons, {signal, capture: true});
	document.addEventListener('upload:complete', toggleSubmitButtons, {signal});
	document.addEventListener('upload:error', toggleSubmitButtons, {signal});
	document.addEventListener('upload:invalid', toggleSubmitButtons, {signal});
}

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