blob: f433cf5ad6616a9022c938e66d3297ea152b5415 (
plain)
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
|
import React from 'react';
interface PropTypes {
data: string;
}
interface Closures {
[key: string]: string;
}
interface Patterns {
[key: string]: RegExp;
}
interface Styles {
[key: string]: React.CSSProperties;
}
const captureInside = (closure: string): any => {
return new RegExp(closure + '([^' + closure + ']+)' + closure);
}
const capture = (closure: string): any => {
return new RegExp('(' + closure + '[^' + closure + ']+' + closure + ')');
}
const closures: Closures = {
inlineCode: '`',
bold: '\\*\\*',
};
const styles: Styles = {
inlineCode: { background: '#444444', padding: '4px' },
bold: { fontWeight: 'bold' },
};
const patterns: Patterns = {};
Object.keys(closures).forEach((key: string): void => {
patterns[key] = capture(closures[key]);
});
const matcher = new RegExp(Object.values(patterns).map(regex => regex.source).join('|'));
Object.keys(closures).forEach((key: string): void => {
patterns[key] = captureInside(closures[key]);
});
const SyntaxSpan: React.FC<PropTypes> = ({ data }) => {
if (!data) return null;
for (let key in styles) {
const match = data.match(patterns[key]);
if (match) return <span style={styles[key]}>{match[1]}</span>;
};
return <>{data}</>;
}
const Paragraph: React.FC<PropTypes> = ({ data }) => {
let result;
result = data.split(matcher);
result = result.map(span => <SyntaxSpan data={span} />);
return <p> {result} </p>;
}
export default Paragraph;
|