2023-07-07 12:54:21 +02:00
|
|
|
import { Fragment, VFC } from 'react';
|
2022-12-28 11:35:27 +01:00
|
|
|
import { safeRegExp } from '@server/util/escape-regex';
|
2023-01-05 15:23:40 +01:00
|
|
|
import { styled } from '@mui/material';
|
2022-05-05 15:34:46 +02:00
|
|
|
|
2022-04-20 14:22:50 +02:00
|
|
|
interface IHighlighterProps {
|
2022-05-05 15:34:46 +02:00
|
|
|
search?: string;
|
|
|
|
children?: string;
|
2022-04-20 14:22:50 +02:00
|
|
|
caseSensitive?: boolean;
|
|
|
|
}
|
|
|
|
|
2023-01-05 15:23:40 +01:00
|
|
|
export const StyledSpan = styled('span')(({ theme }) => ({
|
|
|
|
'&>mark': {
|
|
|
|
backgroundColor: theme.palette.highlight,
|
|
|
|
},
|
|
|
|
}));
|
|
|
|
|
2022-05-05 15:34:46 +02:00
|
|
|
export const Highlighter: VFC<IHighlighterProps> = ({
|
2022-04-20 14:22:50 +02:00
|
|
|
search,
|
|
|
|
children,
|
|
|
|
caseSensitive,
|
2022-05-05 15:34:46 +02:00
|
|
|
}) => {
|
|
|
|
if (!children) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!search) {
|
|
|
|
return <>{children}</>;
|
|
|
|
}
|
|
|
|
|
2022-12-28 11:35:27 +01:00
|
|
|
const regex = safeRegExp(search, caseSensitive ? 'g' : 'gi');
|
2022-04-20 14:22:50 +02:00
|
|
|
|
2023-07-07 12:54:21 +02:00
|
|
|
const parts = children.split(regex);
|
|
|
|
|
2023-08-22 16:00:21 +02:00
|
|
|
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];
|
|
|
|
});
|
2023-07-07 12:54:21 +02:00
|
|
|
|
|
|
|
return <StyledSpan>{highlightedText}</StyledSpan>;
|
2022-04-20 14:22:50 +02:00
|
|
|
};
|