-
-
Notifications
You must be signed in to change notification settings - Fork 658
/
Highlighter.tsx
49 lines (40 loc) · 1.2 KB
/
Highlighter.tsx
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
import type { VFC } from 'react';
import { safeRegExp } from '@server/util/escape-regex';
import { styled } from '@mui/material';
interface IHighlighterProps {
search?: string;
children?: string;
caseSensitive?: boolean;
}
export const StyledSpan = styled('span')(({ theme }) => ({
'&>mark': {
backgroundColor: theme.palette.highlight,
},
}));
export const Highlighter: VFC<IHighlighterProps> = ({
search,
children,
caseSensitive,
}) => {
if (!children) {
return null;
}
if (!search) {
return <>{children}</>;
}
const searchTerms = search.split(',').map((term) => term.trim());
const searchRegex = searchTerms
.map((term) => safeRegExp(term, '').source)
.join('|');
const regex = new RegExp(searchRegex, caseSensitive ? 'g' : 'gi');
const parts = children.split(regex);
const matches = Array.from(children.matchAll(regex)).map(
(match) => match[0],
);
const highlightedText = parts.flatMap((part, index) => {
return index < matches.length
? [part, <mark key={index}>{matches[index]}</mark>]
: [part];
});
return <StyledSpan>{highlightedText}</StyledSpan>;
};