summaryrefslogtreecommitdiff
path: root/source/github-helpers/parse-backticks.tsx
blob: 1e4202f580c3fe7653eec60242c66d80095b1ed0 (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
import React from 'dom-chef';

const splittingRegex = /`` (.*?) ``|`([^`\n]+)`/g;

export function getParsedBackticksParts(string: string): string[] {
	return string.split(splittingRegex)
		.filter(part => part !== undefined); // Only one of the regexp's capture groups matches
}

export default function parseBackticks(description: string): DocumentFragment {
	const fragment = new DocumentFragment();
	for (const [index, text] of getParsedBackticksParts(description).entries()) {
		if (index % 2 && text.length > 0) {
			// `span.sr-only` keeps the backticks copy-pastable but invisible
			fragment.append(
				<span className="sr-only">`</span>,
				<code className="rgh-parse-backticks">{text.trim()}</code>,
				<span className="sr-only">`</span>,
			);
		} else if (text.length > 0) {
			fragment.append(text);
		}
	}

	return fragment;
}