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

const splittingRegex = /`(.*?)`/g;

function splitTextReducer(fragment: DocumentFragment, text: string, index: number): DocumentFragment {
	// Code is always in odd positions
	if (index % 2 && text.length >= 1) {
		// `span.sr-only` keeps the backticks copy-pastable but invisible
		fragment.append(
			<code className="rgh-parse-backticks">
				<span className="sr-only">`</span>
				{text.trim()}
				<span className="sr-only">`</span>
			</code>
		);
	} else if (text.length > 0) {
		fragment.append(text);
	}

	return fragment;
}

export default function parseBackticks(description: string): DocumentFragment {
	return description
		.split(splittingRegex)
		.reduce(splitTextReducer, new DocumentFragment());
}